
    eio                         d dl Zd dlmZmZ d dl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  G d	 d
ej        j                  ZdS )    N)
ArrayCacheArrayCacheBySymbolById)AnyBoolIntOrder	OrderBookStrTickerTrade)Client)List)ExchangeError)AuthenticationError)UnsubscribeErrorc            
           e Zd Zdef fdZd Zd Zdi fdedede	fdZ
d	efd
Zi fdedefdZd	efdZi fdedefdZi fdedefdZd Zd	efdZd	efdZd	efdZddi fdedededee         fdZd	efdZi fdZ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ddi fdedededee         fdZ d	efdZ!d	ede"fdZ#d	efdZ$d	efdZ% xZ&S )derivereturnc                     |                      t          t          |                                           dddddddddddddddiddidddi d	d
diddi iid          S )NFT)wswatchBalancewatchMyTrades
watchOHLCVwatchOrderBookwatchOrderswatchTickerwatchTickerswatchBidsAskswatchTradeswatchTradesForSymbolswatchPositionsr   zwss://api.lyra.finance/wszwss://api-demo.lyra.finance/ws)apitest  )tradesLimitordersLimit	requestId	keepAlivei(#  exact)hasurlsoptions	streaming
exceptions)deep_extendsuperr   describe)self	__class__s    M/var/www/html/volatility/venv/lib/python3.11/site-packages/ccxt/pro/derive.pyr1   zderive.describe   s    fd 3 3 < < > > %!%#"&## %!&#)."'   5 :	   $#  T R?$A
 $A
 $ $ $	    c                     |                      | j        di           }|                     ||d          }|                     |d          }|| j        d         |<   |S )Nr'   r      )
safe_valuer,   safe_integersum)r2   urlr,   previousValuenewValues        r4   
request_idzderive.request_id9   sY    //$,R@@))'3::88M1--)1[!#&r5   c                    K   | j         d         d         }|                     |          }|                     |d|i          }|                     ||dd          }|                     |||||           d {V S Nr"   r   id	subscriberA   methodr+   r>   extendwatchr2   messageHashmessagesubscriptionr;   r'   requests          r4   watch_publiczderive.watch_public@   s      it$OOC((	++g)(
   {{<!2
 2
   ZZ[';UUUUUUUUUr5   Nsymbollimitc                 4  K   |                                   d{V  |d}|                     |          }d|d         z   dz   |                     |          z   }dd|gid}||||d	}|                     |||           d{V }|                                S )
aD  

        https://docs.derive.xyz/reference/orderbook-instrument_name-group-depth

        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
   
orderbook.rA   .10.rB   channelsrD   params)namerN   rO   rV   )load_marketsmarketnumber_to_stringrM   rO   )	r2   rN   rO   rV   rY   topicrL   rK   	orderbooks	            r4   watch_order_bookzderive.watch_order_bookL   s       !!!!!!!!!=EV$$vd|+f4t7L7LU7S7SS!
 
 	
 
 ++E7LIIIIIIII	   r5   clientc                    |                      |d          }|                      |d          }|                     |d          }|                     |          }|d         }|                     |d          }|| j        vr^|                     | j        dd          }	|j        |         }
|                     |
d|	          }|                     i |          | j        |<   | j        |         }|                     |d	          }|                     |||d
d          }|	                    |           |
                    ||           d S )NrV   datainstrument_namerN   channelwatchOrderBookLimitr$   rO   	timestampbidsasks)	safe_dictsafe_stringsafe_market
orderbooksr9   r,   subscriptions
order_bookparse_order_bookresetresolve)r2   r^   rJ   rV   r`   marketIdrY   rN   r[   defaultLimitrK   rO   r\   rd   snapshots                  r4   handle_order_bookzderive.handle_order_bookm   s@     22~~ff--##D*;<<!!(++!  33$/)),,T\;PRVWWL!/6L%%lG\JJE&*oob%&@&@DOF#OF+	%%dK88	((vy&&QQ!!!y%(((((r5   c                    K   |                                   d{V  |                     |          }d|d         z   dz   }dd|gid}|||d}|                     |||           d{V S )	a  

        https://docs.derive.xyz/reference/ticker-instrument_name-interval

        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>`
        Nzticker.rA   z.100rB   rT   rU   rW   rN   rV   )rX   rY   rM   )r2   rN   rV   rY   r[   rL   rK   s          r4   watch_tickerzderive.watch_ticker   s       !!!!!!!!!V$$F4L(61!
 
 
 

 &&ug|DDDDDDDDDr5   c                 ,   |                      |d          }|                      |d          }|                      |d          }|                     |d          }|                     |          }|| j        |d         <   |                    ||           |S )NrV   r`   instrument_tickerrb   rN   )rg   r8   parse_tickertickersro   )r2   r^   rJ   rV   rawDatar`   r[   tickers           r4   handle_tickerzderive.handle_ticker   s    B 22..00~~g':;;	22""4(()/VH%&vu%%%r5   c                 <  K   |                                   d{V  |                     |d          }|d}|                     |          }d|d         z   dz   |                     |          z   }d|z   }dd	|gid
}d|i}|                     |||           d{V S )a  
        unsubscribe from the orderbook channel
        :param str symbol: unified symbol of the market to fetch the order book for
        :param dict [params]: extra parameters specific to the exchange API endpoint
        :param int [params.limit]: orderbook limit, default is None
        :returns dict: A dictionary of `order book structures <https://docs.ccxt.com/?id=order-book-structure>` indexed by market symbols
        NrO   rQ   rR   rA   rS   unwatchunsubscriberT   rU   rW   )rX   r9   rY   rZ   un_watch_public)	r2   rN   rV   rO   rY   r[   rI   rL   rK   s	            r4   un_watch_order_bookzderive.un_watch_order_book   s       !!!!!!!!!!!&'22=EV$$vd|+f4t7L7LU7S7SS%'#
 
 E
 ))+wMMMMMMMMMr5   c                    K   |                                   d{V  |                     |          }d|d         z   }d|z   }dd|gid}d|i}|                     |||           d{V S )	a  
        unsubscribe from the trades channel
        :param str symbol: unified symbol of the market to unwatch the trades for
        :param dict [params]: extra parameters specific to the exchange API endpoint
        :returns any: status of the unwatch request
        Ntrades.rA   r   r   rT   rU   rW   )rX   rY   r   )r2   rN   rV   rY   r[   
messageHahrL   rK   s           r4   un_watch_tradeszderive.un_watch_trades  s       !!!!!!!!!V$$F4L(&
#
 
 E
 ))*g|LLLLLLLLLr5   c                    K   | j         d         d         }|                     |          }|                     |d|i          }|                     ||dd          }|                     |||||           d {V S )Nr"   r   rA   r   rC   rE   rH   s          r4   r   zderive.un_watch_public(  s      it$OOC((	++g)(
   {{<#2
 2
   ZZ[';UUUUUUUUUr5   c                 l   |                     d          }|                     |d          }|                     |          }|d         }|| j        v r| j        |= ||j        v r|j        |= t          | j        dz   |z             }|                    ||           |                    |d|z              d S )N.r7   rN   z orderbook r   )	splitrh   ri   rj   rk   r   rA   rejectro   r2   r^   r[   parsedTopicrp   rY   rN   errors           r4   !handle_order_book_un_subscriptionz(derive.handle_order_book_un_subscription4  s    kk#&&##K33!!(++!T_$$'F((($U+ =!86!ABBeU###ui%/00000r5   c                 l   |                     d          }|                     |d          }|                     |          }|d         }|| j        v r| j        |= ||j        v r|j        |= t          | j        dz   |z             }|                    ||           |	                    |d|z              d S )Nr   r7   rN   z trades r   )
r   rh   ri   rj   tradesrk   r   rA   r   ro   r   s           r4   handle_trades_un_subscriptionz$derive.handle_trades_un_subscriptionA  s    kk#&&##K33!!(++!T_$$F#F((($U+ :!5!>??eU###ui%/00000r5   c                    |                      |d          }|                      |d          }|t          |                                          }t          dt	          |                    D ]i}||         }|                    d          dk    r|                     ||           :|                    d          dk    r|                     ||           j|S )Nresultstatusr   r\   r   )rg   listkeysrangelenfindr   r   )r2   r^   rJ   r   r   topicsir[   s           r4   handle_un_subscribezderive.handle_un_subscribeN  s     2211&++--((F1c&kk** F Fq	::k**a//::65IIIIZZ))Q..66vuEEEr5   sincec                 H  K   |                                   d{V  |                     |          }d|d         z   }dd|gid}|||d}|                     |||           d{V }	| j        r|	                    |d         |          }|                     |	|||d	          S )
a-  
        watches information on multiple trades made in a market

        https://docs.derive.xyz/reference/trades-instrument_name

        :param str symbol: unified market symbol of the market trades were made in
        :param int [since]: the earliest time in ms to fetch trades for
        :param int [limit]: the maximum number of trade structures to retrieve
        :param dict [params]: extra parameters specific to the exchange API endpoint
        :returns dict[]: a list of `trade structures <https://docs.ccxt.com/?id=trade-structure>`
        Nr   rA   rB   rT   rU   ru   rN   T)rX   rY   rM   
newUpdatesgetLimitfilter_by_symbol_since_limit)
r2   rN   r   rO   rV   rY   r[   rL   rK   r   s
             r4   watch_tradeszderive.watch_tradesd  s       !!!!!!!!!V$$F4L(!
 
 
 

 ((FFFFFFFF? 	=OOF8$4e<<E00tTTTr5   c                    |                      |d          }|                      |d          }|                     |d          }|                    d          }|                     |d          }|                     |          }|d         }	|                     | j        |	          }
|
+|                     | j        dd          }t          |          }
t          d	t          |                    D ]2}|                     ||                   }|
                    |           3|
| j        |	<   |                    |
|           d S )
NrV   r`   rb   r   r7   rN   r%   r$   r   )rg   r8   r   rh   ri   r   r9   r,   r   r   r   parse_tradeappendro   )r2   r^   rJ   rV   r`   r[   r   rp   rY   rN   tradesArrayrO   r   trades                 r4   handle_tradezderive.handle_trade  s4    22~~ff--	22kk#&&##K33!!(++!oodk6::%%dlM4HHE$U++Kq#d))$$ 	& 	&A$$T!W--Eu%%%%)F{E*****r5   c                 @  K   |                                   | j        d         d         }|                     |          }d}|                    |          }|                     |j        |          }||                     |          }t          |                                           }| 	                    || j
                  }	|                     | j        d          }
|d|
||	dd}|                     ||          }|                     |||||           | d {V S )Nr"   r   authenticatedderiveWalletAddresspublic/login)walletrd   	signature)rA   rD   rV   )check_required_credentialsr+   r^   reusableFuturer8   rk   r>   strmillisecondssignMessage
privateKeyrh   r,   rF   rG   )r2   rV   r;   r^   rI   futurer   r'   nowr   r   rL   rJ   s                r4   authenticatezderive.authenticate  s.     '')))it$S!!%&&{33(<kJJ ,,Id''))**C((do>>I"&"2"24<AV"W"W(1!$!*  G kk'622GJJsK+wGGG||||||r5   c                 *  K   |                                   d {V  | j        d         d         }|                     |          }|                     |d|i          }|                     ||dd          }|                     |||||           d {V S r@   )r   r+   r>   rF   rG   rH   s          r4   watch_privatezderive.watch_private  s      !!!!!!!!!it$OOC((	++g)(
   {{<!2
 2
   ZZ[';UUUUUUUUUr5   c                   K   |                                   d{V  d}|                     d|          \  }}|                     |          dz   }|}|%|                     |          }|d         }|d|z   z  }dd|gid}	||d	}
|                     |	|          }|                     |||
           d{V }| j        r|                    ||          }|                     ||||d
          S )as  

        https://docs.derive.xyz/reference/subaccount_id-orders

        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
        :param str [params.subaccount_id]: *required* the subaccount id
        :returns dict[]: a list of `order structures <https://docs.ccxt.com/?id=order-structure>`
        Nr   z.ordersrN   :rB   rT   rU   rW   rV   T	rX   handleDeriveSubaccountIdrZ   rY   rF   r   r   r   r   )r2   rN   r   rO   rV   subaccountIdr[   rI   rY   rL   rK   rJ   orderss                r4   watch_orderszderive.watch_orders  sA      !!!!!!!!!#<<]FSSf%%l33i?[[((FH%F3<'K!
 
 
 
 ++gv..))+wMMMMMMMM? 	3OOFE22E00tTTTr5   c                    |                      |d          }|                     |d          }|                     |d          }t          dt	          |                    D ]~}||         }|                     |          }|                     |d          }	|                     |d          }
|	/| j        0|                     | j        dd          }t          |          | _        | j        }| 
                    |j        |	i           }| 
                    ||
          }|| 
                    |d	          }|||d	<   | 
                    |d
          }|||d
<   | 
                    |d          |d<   |                     |d          |d<   |                     |d          |d<   |                    |           |dz   |	z   }|                    | j        |           |                    | j        |           d S )NrV   rb   r`   r   rN   rA   r&   r$   feefeesr   rd   datetimer   )rg   rh   	safe_listr   r   parse_orderr   r9   r,   r   r8   hashmapr   ro   )r2   r^   rJ   rV   r[   	rawOrdersr   r`   parsedrN   orderIdrO   cachedOrdersr   orderr   r   messageHashSymbols                     r4   handle_orderzderive.handle_order  s   T 22  33NN6622	q#i..)) 	? 	?AQ<D%%d++F%%fh77F&&vt44G!;& --dlM4PPE"8"?"?DK#{)=vrJJ88$//%77C(+u??5&99D')-v'+uh'G'GF8$*.*;*;E;*O*OF;')-)9)9%)L)LF:&##F+++$)CK&$8!t{,=>>>t{E*****r5   c                   K   |                                   d{V  d}|                     d|          \  }}|                     |          dz   }|}|%|                     |          }|d         }|d|z   z  }dd|gid}	||d	}
|                     |	|          }|                     |||
           d{V }| j        r|                    ||          }|                     ||||d
          S )as  

        https://docs.derive.xyz/reference/subaccount_id-trades

        watches information on multiple trades 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
        :param str [params.subaccount_id]: *required* the subaccount id
        :returns dict[]: a list of `trade structures <https://docs.ccxt.com/?id=trade-structure>`
        Nr   z.tradesrN   r   rB   rT   rU   r   Tr   )r2   rN   r   rO   rV   r   r[   rI   rY   rL   rK   rJ   r   s                r4   watch_my_tradeszderive.watch_my_trades4  sA      !!!!!!!!!#<<_fUUf%%l33i?[[((FH%F3<'K!
 
 
 
 ++gv..))+wMMMMMMMM? 	3OOFE22E00tTTTr5   c                    | j         }|+|                     | j        dd          }t          |          }|                     |d          }|                     |d          }|                     |d          }t          dt          |                    D ]c}| 	                    |          }	|
                    |	           |                    ||           ||	d         z   }
|                    ||
           dd S )Nr%   r$   rV   rb   r`   r   rN   )myTradesr9   r,   r   rg   rh   r   r   r   r   r   ro   )r2   r^   rJ   r   rO   rV   r[   	rawTradesr   r   rI   s              r4   handle_my_tradezderive.handle_my_trade\  s     =%%dlM4HHE-e44H22  33NN6622	q#i..)) 	2 	2A$$W--EOOE"""NN8U+++%/1KNN8[1111	2 	2r5   c                    d|vrdS |                      |d          }|                     |d          }	 |Q| j        dz   |                     |          z   }|                     | j        d         ||           t          |          dS # t          $ r_}t          |t                    r*d}|
                    ||           ||j        v r|j        |= n|
                    |           Y d }~dS d }~ww xY w)Nr   Fcode r)   r   T)rg   rh   rA   jsonthrow_exactly_matched_exceptionr.   r   	Exception
isinstancer   r   rk   )r2   r^   rJ   errorMessage	errorCodefeedbackr   rI   s           r4   handle_error_messagezderive.handle_error_messagem  s    7""5~~gw77$$\6::		$7S=499W+=+==44T_W5MyZbccc#H---5 	 	 	%!455 %-e[111&"666,[9e$$$44444	s   AB	 	
C2AC--C2c                 X   |                      ||          rd S | j        | j        | j        | j        | j        d}d }|                     |d          }||                     |d          }|||                    d          }|	                    d          dk    s|	                    d          dk    r|                     |d          }|dk    rd	}n|                     |d          }| 
                    ||          }| |||           d S d
|v r|                     |d
          }	|                     |j        d
          }
| 
                    |
|	i           }d|v rJ|d         dk    r|                     ||           d S |d         dk    r|                     ||           d S d S d S d S )N)r\   r|   r   r   mytradesrV   rb   r   r   r   r   r7   r   rA   rD   r   r   )r   rs   r}   r   r   r   rg   rh   r   r   r8   index_byrk   handle_authr   )r2   r^   rJ   methodseventrV   rb   parsedChannelrD   rA   subscriptionsByIdrK   s               r4   handle_messagezderive.handle_message  s   $$VW55 	F/('',
 
 22&&vy99G" 'c 2 2LL**a//GLL4J4JQ4N4N ,,]A>>E(( * ,,]A>>E%00F67###F7??!!'400B $f.BD I I??+<b"EEL<'')^;;$$VW55555!(+}<<,,VW===== ? (' =<r5   c                 V   d}|                      |d          }t          |          dk    r2|                     |j        d          }|                    d           d S t          |                     |                    }|                    ||           ||j        v r
|j        d= d S d S )Nr   r   r   T)	r   r   r8   futuresro   r   r   r   rk   )r2   r^   rJ   rI   idsr   r   s          r4   r   zderive.handle_auth  s     &nnWh//s88a<<__V^_EEFNN4     '		'(:(:;;EMM%---f222(999 32r5   )'__name__
__module____qualname__r   r1   r>   rM   r   r   r	   r]   r   rs   r   rv   r}   r   r   r   r   r   r   r   r   r   r   r   r   r
   r   r   r   r   r   r   r   r   r   __classcell__)r3   s   @r4   r   r      s       %# % % % % % %N  
V 
V 
V @DB ! !S ! !S\ ! ! ! !B) ) ) ) )B 68 E E EF E E E E8HF H H H HT =? N N N3 N N N N8 9; M MC Ms M M M M0
V 
V 
V1 1 1 1 11F 1 1 1 1&    , <@d[] U U US U Ubfglbm U U U UB+6 + + + +( )+    <V V V 04$UYbd &U &U &UC &Us &Uimnsit &U &U &U &UPF+6 F+ F+ F+ F+P 37TX\eg &U &UC &Us &URU &Ulpqvlw &U &U &U &UP2f 2 2 2 2"6 t    6#>V #> #> #> #>L:& : : : : : : : :r5   r   )ccxt.async_supportccxt ccxt.async_support.base.ws.cacher   r   ccxt.base.typesr   r   r   r   r	   r
   r   r   !ccxt.async_support.base.ws.clientr   typingr   ccxt.base.errorsr   r   r   async_supportr    r5   r4   <module>r      s       O O O O O O O O P P P P P P P P P P P P P P P P P P P P 4 4 4 4 4 4       * * * * * * 0 0 0 0 0 0 - - - - - -p
: p
: p
: p
: p
:T& p
: p
: p
: p
: p
:r5   