
    ih                         d dl Zd dlmZ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  G d d	ej        j                  ZdS )
    N)
ArrayCacheArrayCacheBySymbolByIdArrayCacheByTimestamp)BalancesIntOrder	OrderBookStrTrade)Client)List)AuthenticationError)NetworkErrorc            
           e Zd Z fdZi fdZi 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di fdededed	ee         fdZdefdZdi fdeded	efdZdi fdedefdZdi fdedefdZdefdZdefdZd Zd ZdefdZi fd	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$dZ 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%d! Z&defd"Z'i fd#Z( xZ)S )%ascendexc                     |                      t          t          |                                           ddddddddddddiddd	did
ddddddddd          S )NTF)wswatchBalance
watchOHLCVwatchOrderBookwatchOrderswatchTickerwatchTradesr   z(wss://ascendex.com:443/api/pro/v2/streamz7wss://ascendex.com:443/{accountGroup}/api/pro/v2/stream)publicprivatez9wss://api-test.ascendex-sandbox.com:443/api/pro/v2/streamzHwss://api-test.ascendex-sandbox.com:443/{accountGroup}/api/pro/v2/stream)apitest  spotswapmargin)cashfuturesr!   )tradesLimitordersLimit
OHLCVLimitcategoriesAccount)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/ascendex.pyr-   zascendex.describe   s    h 5 5 > > @ @ $""&#$#  "L#\  "]#m    $#""%&& &		 	1"C
 "C
 " " "	    c                    K   | j         d         d         d         }|                                 }t          |          dd}|                     ||          }|                     ||||           d {V S )Nr   r   r   sub)idop)r)   noncestrextendwatch)r.   messageHashparamsurlr4   requestmessages          r0   watch_publiczascendex.watch_public7   s      it$X.ZZ\\b''
 
 ++gv..ZZ[';GGGGGGGGGr1   c                   K   |                                   d {V  |                     | j        d          }| j        d         d         d         }|                     |d|i          }|                                 }t          |          d|d}|                     ||          }|                     ||           d {V  | 	                    ||||           d {V S )Nzaccount-groupr   r   r   accountGroupr3   )r4   r5   ch)
load_accountssafe_stringr*   r)   implode_paramsr6   r7   r8   authenticater9   )	r.   channelr:   r;   rA   r<   r4   r=   r>   s	            r0   watch_privatezascendex.watch_privateA   s        """""""""''oFFit$Y/!!#'EFFZZ\\b''
 

 ++gv..V,,,,,,,,,ZZ['7CCCCCCCCCr1   1mNsymbolsincelimitreturnc                   K   |                                   d{V  |                     |          }|d         }||dk    rd}|                     | j        ||          }d|z   dz   |d         z   }d|i}|                     ||           d{V }	| j        r|	                    ||          }|                     |	||d	d
          S )aQ  
        watches historical candlestick data containing the open, high, low, and close price, and the volume of a market
        :param str symbol: unified symbol of the market to fetch OHLCV data for
        :param str timeframe: the length of time each candle represents
        :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
        :returns int[][]: A list of candles ordered, open, high, low, close, volume
        NrJ   i  d   zbar::r4   rB   r   T)load_marketsmarketrD   
timeframesr?   
newUpdatesgetLimitfilter_by_since_limit)
r.   rJ   	timeframerK   rL   r;   rR   intervalrG   ohlcvs
             r0   watch_ohlcvzascendex.watch_ohlcvP   s       !!!!!!!!!V$$!Mut||E##DOY	JJ(3.='
 ''88888888? 	2NN6511E))%q$GGGr1   clientc                    |                      |d          }|                     |          }|                      |d          }|                     |di           }|                      |d          }|dz   |z   dz   |z   }|                     |          }	|                     |          }
|                     ||
          }|                     | j        |i           | j        |<   |                     | j        |         |	          }|;|                     | j        dd          }t          |          }|| j        |         |	<   |
                    |           |                    ||           |S )NsmdatairP   r&   r   )rD   safe_symbol
safe_valuefind_timeframerR   parse_ohlcvohlcvssafe_integerr*   r   appendresolve)r.   r[   r>   marketIdrJ   rG   r_   rX   r:   rW   rR   parsedstoredrL   s                 r0   handle_ohlcvzascendex.handle_ohlcvi   s[     ##GS11!!(++""7C00w33##D#..mh.4x?''11	V$$!!'622"oodk62FFFV!4i@@>%%dlL$GGE*511F-3DK	*fv{+++r1   c                 ^  K   |                                   d{V  |                     |          }|d         }d|d         z   }|                     |d|i          }|                     ||           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>`
        NrJ   ztrades:r4   rB   	timestampT)rQ   rR   r8   r?   rT   rU   rV   )r.   rJ   rK   rL   r;   rR   rG   tradess           r0   watch_tradeszascendex.watch_trades   s       !!!!!!!!!V$$! 6$</V'&
   ((&99999999? 	3OOFE22E))&%TRRRr1   c                 h   |                      |d          }|                     |          }|                      |d          }|dz   |z   }|                     |          }|                     |d          }|g }|                     ||          }	|                     | j        |          }
|
+|                     | j        dd          }t          |          }
t          dt          |	                    D ]}|
                    |	|                    |
| j        |<   |                    |
|           d S )NrJ   r^   rP   r_   r$   r   r   )rD   ra   rR   rb   parse_tradesro   rf   r*   r   rangelenrg   rh   )r.   r[   r>   ri   rJ   rG   r:   rR   rawDataro   tradesArrayrL   r`   s                r0   handle_tradeszascendex.handle_trades   s3     ##GX66!!(++""7C00mh.V$$//'622?G""7F33oodk6::%%dlM4HHE$U++Kq#f++&& 	* 	*Avay)))))F{K00000r1   c                 
  K   |                                   d{V  |                     |          }d|d         z   }|                     |d|i          }|                     ||           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
        Nzdepth:r4   rB   rQ   rR   r8   r?   rL   )r.   rJ   rL   r;   rR   rG   	orderbooks          r0   watch_order_bookzascendex.watch_order_book   s       !!!!!!!!!V$$&,.V'&
   ++GV<<<<<<<<	   r1   c                 (  K   |                                   d {V  |                     |          }d}|dz   |d         z   }|                     ||d|d         idd          }|                     ||           d {V }|                                S )Ndepth-snapshotrP   r4   rJ   req)actionargsr5   ry   )r.   rJ   rL   r;   rR   r   rG   rz   s           r0   watch_order_book_snapshotz"ascendex.watch_order_book_snapshot   s      !!!!!!!!!V$$!3,-V&, &
 &
   ++GV<<<<<<<<	   r1   c                    K   |                      |||           d {V }|| j        vr|                                 | j        |<   | j        |         }|                    |           |S N)fetch_rest_order_book_safe
orderbooks
order_bookreset)r.   rJ   rL   r;   restOrderBookrz   s         r0   fetch_order_book_snapshotz"ascendex.fetch_order_book_snapshot   sv      "==feVTTTTTTTT$/))&*oo&7&7DOF#OF+	&&&r1   c                 2   |                      |d          }|                     |          }|                      |d          }|dz   |z   }| j        |         }|                     |d          }|                     ||          }	|                     |d          |	d<   |                    |	           |j        }
t          dt          |
                    D ]!}|
|         }| 
                    |||           "|| j        |<   |                    ||           d S )NrJ   r^   rP   r_   seqnumr6   r   )rD   ra   r   rb   parse_order_bookrf   r   cachers   rt   handle_order_book_messagerh   )r.   r[   r>   ri   rJ   rG   r:   rz   r_   snapshotmessagesr`   messageItems                r0   handle_order_book_snapshotz#ascendex.handle_order_book_snapshot   s!   & ##GX66!!(++""7C00mf,OF+	w//((v66 --dH==!!!?q#h--(( 	K 	KA"1+K**6;	JJJJ"+y+.....r1   c                    |                      |d          }|                      |d          }|                     |          }|dz   |z   }|                     | j        |          }||                     i           }|d         |j                            |           d S |                     |||           |                    ||           d S )Nr^   rJ   rP   r6   )	rD   ra   rb   r   r   r   rg   r   rh   )r.   r[   r>   rG   ri   rJ   r:   rz   s           r0   handle_order_bookzascendex.handle_order_book  s     ""7C00##GX66!!(++mh.OODOV<<	++IW%O""7+++++**67IFFFNN9k22222r1   c                     |                      |d          }|                      |d          }|                    ||           d S )Nr      )
safe_floatstore)r.   booksidedeltapriceamounts        r0   handle_deltazascendex.handle_delta)  sD     q))**uf%%%%%r1   c                 ~    t          dt          |                    D ]}|                     |||                    d S )Nr   )rs   rt   r   )r.   r   deltasr`   s       r0   handle_deltaszascendex.handle_deltas1  sH    q#f++&& 	3 	3Ahq	2222	3 	3r1   c                    |                      |di           }|                     |d          }||d         k    r|                      |dg           }|                      |dg           }|                     |d         |           |                     |d         |           ||d<   |                     |d          }||d<   |                     |          |d<   |S )	Nr_   r   r6   asksbidstsrn   datetime)rb   rf   r   iso8601)	r.   r[   r>   rz   r_   seqNumr   r   rn   s	            r0   r   z"ascendex.handle_order_book_message5  s    ( w33""422Ig&&&??444D??444Dy0$777y0$777!'Ig))$55I%.Ik"$(LL$;$;Ij!r1   c                 t  K   |                                   d{V  |                     dd|          \  }}d}d}|dk    s|dk    rR|                     | j        di           }|                     ||d          }|                                }d|z   }d|z   }nd	}d
}|                     |||           d{V S )a  
        watch balance and get the amount of funds available for trading or funds locked in orders
        :param dict [params]: extra parameters specific to the exchange API endpoint
        :returns dict: a `balance structure <https://docs.ccxt.com/#/?id=balance-structure>`
        Nr   r   r!   accountCategoriesr"   order:balance:futures-account-updatezbalance:swap)rQ   handle_market_type_and_paramsrb   r*   rD   upperrH   )r.   r;   typequeryrG   r:   r   accountCategorys           r0   watch_balancezascendex.watch_balanceV  s       !!!!!!!!!88vVVeFNN 0 0 $>QSU V V"../@$OOO-3355O0G$t+KK.G(K''eDDDDDDDDDr1   c                 |   |                      |d          }d }d }|dk    s|dk    r0|                     |d          }|                      |d          }|                     |          }|                                 }	|                      |d          |	d<   |                      |d          |	d	<   |                                 }
|                      |d
          |
d<   |                      |d          |
d	<   |d         rd}|                     | j        |i           }n$|d         }|                     | j        |i           }|	||d         <   |
||d         <   n6|                     |dd          }|                     | j        d          }|                      ||d          }|                     | j        |i           }|                     |d          }d }||                     |d          }n|g}t          dt          |                    D ]}||         }| 	                    |                      |d                    }|                                 }|                      |d          |d<   | 
                    |dd          |d	<   |||<   d|z   }|                    |                     |          |           d S )Nr^   orderfutures-orderr_   r]   babfreebtbtotalqabqtbcontractr    r   basequoteacatr'   r   colr   aabtbbr   )rD   rb   safe_marketaccountbalancesafe_string_lower_2r*   rs   rt   safe_currency_codesafe_string_2rh   safe_balance)r.   r[   r>   rG   resultr   r_   ri   rR   baseAccountquoteAccountaccountTypecategoriesAccountsbalancesr`   r   coder   r:   s                      r0   handle_balancezascendex.handle_balancek  s   d ""7C00wG$>$>??7F33D''c22H%%h//F,,..K"&"2"24"?"?K#'#3#3D%#@#@K <<>>L#'#3#3D%#@#@L $($4$4T5$A$AL!j! AtR@@f~tR@@%0F6&>"&2F6'?##227D$GGK!%?R!S!S##$6VLLD__T\4<<F??7F33DH|??7E:: 61c(mm,, ' '"1+..t/?/?/M/MNN,,.."&"2"27D"A"A#'#5#5gtS#I#I &t%,t((00+>>>>>r1   c                 0  K   |                                   d{V  d}||                     |          }|d         }|                     d||          \  }}d}d}	|dk    r|dk    rd}	d}nN|                     | j        di           }
|                     |
|d	          }|                                }d
|z   }|}	||dz   |z   }|                     |	||           d{V }| j        r|	                    ||          }| 
                    ||||d          S )aA  
        :see: https://ascendex.github.io/ascendex-pro-api/#channel-order-and-balance
        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>`
        NrJ   r   r   r!   r   zorder:FUTURESr   r"   r   rP   T)rQ   rR   r   rb   r*   rD   r   rH   rT   rU   filter_by_symbol_since_limit)r.   rJ   rK   rL   r;   rR   r   r   r:   rG   r   r   orderss                r0   watch_orderszascendex.watch_orders  s`      !!!!!!!!![[((FH%F88PVWWe6>>dh..%G)KK $>QSU V V"../@$OOO-3355O'/9K!G%+f4K))';FFFFFFFF? 	3OOFE22E00tTTTr1   c                    |                      |d          }d|z   }|                     |d|          }|                     |          }| j        0|                     | j        dd          }t          |          | _        | j        }|                    |           |dz   |d         z   }	|                    ||	           |                    ||           d S )Nr   r   r_   r%   r   rP   rJ   )	rD   rb   parse_ws_orderr   rf   r*   r   rg   rh   )
r.   r[   r>   r   r:   r_   r   rL   r   symbolMessageHashs
             r0   handle_orderzascendex.handle_order  s    T &&w55,w88##D));%%dlM4HHE077DKe'#-h?v0111v{+++++r1   c           	         |                      |                     |d                    }|                     |d          }|                     |d          }|                     ||d          }|                     |d          }|                     |d          }|                     |d          }	|                     |d          }
|                     |d          }|                     |d	          }|                     |d
          }|                     |d          }|                     |d          }d }|0|                     |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!|          S )"Nstr]   t/pqapcfqorderIdotsdcffa)costcurrencyspinfor4   clientOrderIdrn   r   lastTradeTimestamprJ   r   timeInForcepostOnlysider   	stopPricetriggerPricer   r   average)filled	remainingstatusfeero   )parse_order_statusrD   rf   ra   safe_string_lowersafe_numberr   parse_number	omit_zero
safe_orderr   )r.   r   rR   r   ri   rn   rJ   r   r   r   r   r   r4   r   r   feeCostr   feeCurrencyIdfeeCurrencyCoder   s                       r0   r   zascendex.parse_ws_order   s   v (()9)9%)F)FGG##E3//%%eS11	!!(FC88!..uc::  ,,!!%--""5$//!!%//eY//%%eT22%%eT22""5$// ,,UD99M"55mDDO+ C %%dnnT5E5EeT5R5R&S&STT	  
E 
" 
 T 
 	 

 Y// 
 !"4 
 f 
 D 
 4 
  
 D 
 U 
  
 I 
 f 
  D! 
" w# 
$ - 
  
  
. /  	r1   c                    |                      |d          }	 ||| j        dz   |                     |          z   }|                     | j        d         ||           |                     |d          }|"|                     | j        d         ||           dS # t          $ r_}t          |t                    r*d}|
                    ||           ||j        v r|j        |= n|
                    |           Y d }~dS d }~ww xY w)	Nr    exactr>   broadFauthenticatedT)rf   r4   jsonthrow_exactly_matched_exception
exceptionsrb   throw_broadly_matched_exception	Exception
isinstancer   rejectsubscriptions)r.   r[   r>   	errorCodefeedbackmessageStringer:   s           r0   handle_error_messagezascendex.handle_error_message  s#    %%gv66		$7S=499W+=+==44T_W5MyZbccc $ C C ,889QS`bjkkk5 	 	 	!011 !-a---&"666,[9a   44444	s   A>B 
D"AC<<Dc                 6    d}|                     ||           d S )Nr  )rh   )r.   r[   r>   r:   s       r0   handle_authenticatezascendex.handle_authenticate  s#     &w,,,,,r1   c           
         |                      ||          rd S |                     |d          }| j        | j        | j        | j        | j        | j        | j        | j	        | j	        d	}| 
                    ||          }| |||           |dk    s|dk    r6|                     ||           |dk    r| 	                    ||           d S d S d S )Nr^   )	pingauthr3   depthr}   ro   barr   r   r   r   )r  rD   handle_pingr  handle_subscription_statusr   r   rw   rl   r   rb   r   )r.   r[   r>   subjectmethodsmethods         r0   handle_messagezascendex.handle_message  s
   $$VW55 	Fb ""7C00$,2+"=($*&*&9

 

 '22F67###wG$>$> fg...'!!##FG44444 "! %?$>r1   c                     |                      |dd          }|                    d          dk    r/|                    d          dk    s|                     ||           |S )NrB    r  r}   )rD   findhandle_order_book_subscription)r.   r[   r>   rG   s       r0   r  z#ascendex.handle_subscription_statusW  se     ""7D"55<<  2%%w||<L/M/MPR/R/R//@@@r1   c                    |                      |d          }|                    d          }|d         }|                     |          }|d         }|| j        v r| j        |= |                     i           | j        |<   | j        d         dk    s|d         r|                     | j        |           d S |                     | j        |           d S )NrB   rP   r   rJ   defaultTyper    r   )	rD   splitr   r   r   r*   spawnr   r   )r.   r[   r>   rG   partsri   rR   rJ   s           r0   r&  z'ascendex.handle_order_book_subscriptionb  s    ""7D11c""8!!(++!T_$$'"&//""5"5<&&00F:4F0JJt5v>>>>>JJt5v>>>>>r1   c                 $  K   	 |                     d|                     |d          d           d {V  d S # t          $ rM}t          | j        dz   |                     |          z             }|                    |           Y d }~d S d }~ww xY w)Nponghp)r5   r.  z handlePing failed with error )sendrf   r  r   r4   r  r   )r.   r[   r>   r  errors        r0   r-  zascendex.pongp  s      	 ++V43D3DWd3S3STTUUUUUUUUUUU 	  	  	  +K!KdiiXYll!Z[[ELL	 s   28 
BAB

Bc                 >    |                      | j        ||           d S r   )r*  r-  )r.   r[   r>   s      r0   r  zascendex.handle_pingz  s     

49fg.....r1   c                   K   |                                   d}|                     |          }|                     |j        |          }|<t	          |                                           }|                    d          }t          |          }|                     ||dz
            }	|                     ||dz
            }
|dz   |
z   dz   |	z   }| 	                    | j
                  }|                     |                     |          |t          j        d          }dt	          |                                           || j        |d}|                     |||                     ||          |           d {V }||j        |<   |S )	Nr  r   r      +base64r  )r5   r4   r   keysig)check_required_credentialsr[   rb   r  r7   millisecondsr)  rt   rD   base64_to_binarysecrethmacencodehashlibsha256r6   apiKeyr9   r8   )r.   r<   r;   r:   r[   futurern   urlPartspartsLengthpathversionr  r;  	signaturer=   s                  r0   rF   zascendex.authenticate}  sy     '')))%S!!!5{CC>D--//00Iyy~~Hh--K##HkAo>>D&&xqAAGs?W,s2T9D**4;77F		$++d"3"3VW^XVVI$**,,''{  G  ::c;GV8T8TVabbbbbbbbF06F -r1   r   )*__name__
__module____qualname__r-   r?   rH   r7   r   r   listrZ   r   rl   r   rp   rw   r	   r{   r   r   r   r   r   r   r   r   r   r   r
   r   r   r   r   r  r  r!  r  r&  r-  r  rF   __classcell__)r/   s   @r0   r   r      s       # # # # #J 68 H H H H @B D D D D 8<$]ajl H H HC HWZ Hquvzq{ H H H H2!6 ! ! ! !F <@d[] S S SS S Sbfglbm S S S S* 1F  1  1  1  1D @DB ! !S ! !S\ ! ! ! !" IMUW ! !c !# ! ! ! ! IMUW  c #    "/ "/ "/ "/ "/H3 3 3 3 34& & &3 3 3    B *, E E E E E E*Z?V Z? Z? Z? Z?x 04$UYbd  U  U  UC  Us  Uimnsit  U  U  U  UD5,6 5, 5, 5, 5,nh h h hT6    8-& - - - -h5V h5 h5 h5 h5T	 	 	 	 	?V ? ? ? ?     /& / / / / .0        r1   r   )ccxt.async_supportccxt ccxt.async_support.base.ws.cacher   r   r   r>  ccxt.base.typesr   r   r   r	   r
   r   !ccxt.async_support.base.ws.clientr   typingr   ccxt.base.errorsr   r   async_supportr    r1   r0   <module>rU     s        f f f f f f f f f f  G G G G G G G G G G G G G G G G 4 4 4 4 4 4       0 0 0 0 0 0 ) ) ) ) ) )D D D D Dt!* D D D D Dr1   