
    i                         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  G d dej        j                  ZdS )	    N)
ArrayCacheArrayCacheBySymbolByIdArrayCacheByTimestamp)IntOrder	OrderBookStrTickerTrade)Client)List)ExchangeErrorc            
           e Zd Z fdZd Zdddi fdedededee         fd	Z	dddi fdedededee         fd
Z
d Zi fdefdZi fdedefdZd Zd dZddi fdedededee         fdZddi fdedededee         fdZd Zd dZdddi fdedededee         fdZd Zd dZd Zdi fdededefdZdi fdededefdZd Zd Z de!fdZ"d Z#i fdZ$ xZ%S )!lbankc                     |                      t          t          |                                           dddddddddddddddddiiddd	d
ddddddddd
iii i d          S )NTF)wsfetchOHLCVWsfetchOrderBookWsfetchTickerWsfetchTradesWswatchBalancewatchTickerwatchTickerswatchTradeswatchMyTradeswatchOrderswatchOrderBook
watchOHLCVapir   zwss://www.lbkex.net/ws/V2/r   
timeframes1min5min15min30min1hr4hrdayweekmonthyear)
1m5m15m30m1h4h1d1w1M1y)hasurlsoptions	streaming
exceptions)deep_extendsuperr   describe)self	__class__s    T/var/www/html/crypto-bot/backend/venv/lib/python3.11/site-packages/ccxt/pro/lbank.pyr<   zlbank.describe   s    eT 2 2 ; ; = = $$(!%!% %# %#!&#"&"   6  $$&&###$%$# # O)@
 )@
 ) ) )	    c                 ~    |                      | j        dd          }|                     |d          }|| j        d<   |S )N	requestIdr      )safe_integerr7   sum)r=   previousValuenewValues      r?   
request_idzlbank.request_id=   s?    ))$,QGG88M1--$,[!r@   r+   Nsymbolsincelimitreturnc                 r  K   |                                   d{V  |                     |          }| j        d         d         }|                     | j        di           }|                     |di           }	|                     |	||          }
d|d         z   dz   |
z   }d	d
|
|d         d}|:|                     t          t          j	        |dz                                |d<   |||d<   | 
                    ||          }|                                 }|                     |||||           d{V S )a  
        :see: https://www.lbank.com/en-US/docs/index.html#request-amp-subscription-instruction
        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
        Nr   r   r   r    fetchOHLCV:rI   :requestkbarid)actionrP   rQ   pair  startsize)load_marketsmarketr6   
safe_valuer7   safe_stringparse_to_intintmathfloorr:   rH   watch)r=   rI   	timeframerJ   rK   paramsrY   urlwatchOHLCVOptionsr    timeframeIdmessageHashmessagerP   rB   s                  r?   fetch_ohlcv_wszlbank.fetch_ohlcv_wsC   s]      !!!!!!!!!V$$it$ OODL,KK__%6bII
&&z9iHH#fX&66<{J4L	
 
 #00TZ5M5M1N1NOOGG#GFO""7F33OO%%	ZZ['9gNNNNNNNNNr@   c                 .  K   |                                   d{V  |                     |          }|                     | j        di           }|                     |di           }|                     |||          }	d|d         z   dz   |	z   }
| j        d         d         }d	d
|	|d         d}|                     ||          }|                     ||
||
           d{V }| j        r|	                    ||          }| 
                    |||dd          S )a  
        :see: https://www.lbank.com/en-US/docs/index.html#subscription-of-k-line-data
        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
        Nr   r    ohlcv:rI   rO   r   r   	subscriberQ   rR   )rS   rk   rQ   rT   r   T)rX   rY   rZ   r7   r[   r6   r:   r`   
newUpdatesgetLimitfilter_by_since_limit)r=   rI   ra   rJ   rK   rb   rY   rd   r    re   rf   rc   rk   rP   ohlcvs                  r?   watch_ohlcvzlbank.watch_ohlcvc   sA      !!!!!!!!!V$$ OODL,KK__%6bII
&&z9iHH!11C7+Eit$!4L	
 
	 ""9f55jjk7KHHHHHHHH? 	2NN6511E))%q$GGGr@   c           	         |                      |d          }|                     |d d          }|                     | j        di           }|                     |di           }|                     |d          }|}|                     |dg           }|                     |d          |                     |d          |                     |d          |                     |d	          |                     |d
          |                     |d          g}	|                      |d          }
|                     |
|          }|                     | j        |i           | j        |<   |                     | j        |         |          }|;|                     | j        dd          }t          |          }|| j        |         |<   |	                    |	           d|z   dz   |
z   }|
                    ||           d S |                     |di           }|                      |d          }
|                      |d          }|                     |          |                     |d          |                     |d          |                     |d          |                     |d          |                     |d          g}	|                     |
|          }|                     | j        |i           | j        |<   |                     | j        |         |          }|;|                     | j        dd          }t          |          }|| j        |         |<   |	                    |	           d|z   dz   |
z   }|
                    ||           d S )NrT   _r   r    recordsr   rC               rQ   
OHLCVLimitrU   rN   rO   slottohlcvrj   )r[   safe_symbolrZ   r7   rD   safe_numberfind_timeframeohlcvsr   appendresolve	parse8601)r=   clientrg   marketIdrI   rd   r    rs   rawOHLCVparsedre   ra   storedrK   rf   datetimes                   r?   handle_ohlcvzlbank.handle_ohlcv   se   h ##GV44!!(D#66 OODL,KK__%6bII
//'955w266H!!(A..  1--  1--  1--  1--  1--F **7F;;K++KDDI"&//$+vr"J"JDK__T[%8)DDF~))$,dKK.u5517F#I.MM&!!!'&036DKNN6;/////w;;H**8V<<K''#66Hx((  3//  3//  3//  3//  3//F ++KDDI"&//$+vr"J"JDK__T[%8)DDF~))$,dKK.u5517F#I.MM&!!!"V+c1K?KNN6;/////r@   c                 J  K   |                                   d{V  |                     |          }| j        d         d         }d|d         z   }dd|d         d	}|                     ||          }|                                 }|                     |||||           d{V S )
a  
        :see: https://www.lbank.com/en-US/docs/index.html#request-amp-subscription-instruction
        fetches 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 cex api endpoint
        :returns dict: a `ticker structure <https://docs.ccxt.com/#/?id=ticker-structure>`
        Nr   r   fetchTicker:rI   rP   tickrR   )rS   rP   rT   rX   rY   r6   r:   rH   r`   )	r=   rI   rb   rY   rc   rf   rg   rP   rB   s	            r?   fetch_ticker_wszlbank.fetch_ticker_ws   s       !!!!!!!!!V$$it$$vh'774L
 

 ""7F33OO%%	ZZ['9gNNNNNNNNNr@   c                 "  K   |                                   d{V  |                     |          }| j        d         d         }d|d         z   }dd|d         d	}|                     ||          }|                     |||||           d{V S )
a  
        :see: https://www.lbank.com/en-US/docs/index.html#market
        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 lbank api endpoint
        :returns dict: a `ticker structure <https://docs.ccxt.com/en/latest/manual.html#ticker-structure>`
        Nr   r   ticker:rI   rk   r   rR   rS   rk   rT   )rX   rY   r6   r:   r`   )r=   rI   rb   rY   rc   rf   rg   rP   s           r?   watch_tickerzlbank.watch_ticker   s       !!!!!!!!!V$$it$&"22!4L
 

 ""7F33ZZ[';PPPPPPPPPr@   c                 2   |                      |d          }|                     |          }|                     |          }|                     ||          }|| j        |<   d|z   }|                    ||           d|z   }|                    ||           d S )NrT   r   r   )r[   r   safe_marketparse_ws_tickertickersr   )r=   r   rg   r   rI   rY   parsedTickerrf   s           r?   handle_tickerzlbank.handle_ticker  s    , ##GV44!!(++!!(++++GV<<+V&(|[111$v-|[11111r@   c                 f   |                      |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 d|                      |d          dd |                      |d          |                      |d          |d|          S )NrT   TSr   rI   	timestampr   highlowbid	bidVolumeask	askVolumevwapopencloselastlatestpreviousClosechange
percentageaveragevolturnover)
baseVolumequoteVolumeinfo)r[   r   rZ   safe_tickerr   )r=   tickerrY   r   rI   r   
tickerDatas          r?   r   zlbank.parse_ws_ticker/  s   , ##FF33!!(F33##FD11__VV44
 !
f!
11!
 !
 D$$Z88	!

 4##J66!
 4!
 !
 4!
 !
 D!
 D!
 T!
 D$$Z::!
 T!
 d!
  $**:x@@!!
" t#!
$ **:u==++J
CC)!
 !
 !
* +  	r@   c                 T  K   |                                   d{V  |                     |          }| j        d         d         }d|d         z   }|d}dd|d	         |d
}|                     ||          }	|                                 }
|                     |||	|
|	           d{V S )a<  
        get the list of most recent trades for a particular symbol
        :see: https://www.lbank.com/en-US/docs/index.html#request-amp-subscription-instruction
        :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 Trade[]: a list of `trade structures <https://docs.ccxt.com/#/?id=public-trades>`
        Nr   r   fetchTrades:rI   
   rP   traderR   )rS   rP   rT   rW   r   )r=   rI   rJ   rK   rb   rY   rc   rf   rg   rP   rB   s              r?   fetch_trades_wszlbank.fetch_trades_ws`  s       !!!!!!!!!V$$it$$vh'77=E4L	
 
 ""7F33OO%%	ZZ['9gNNNNNNNNNr@   c                 T  K   |                                   d{V  |                     |          }| j        d         d         }d|d         z   }dd|d         d	}|                     ||          }	|                     |||	||	           d{V }
|                     |
||d
d          S )a#  
        :see: https://www.lbank.com/en-US/docs/index.html#trade-record
        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>`
        Nr   r   trades:rI   rk   r   rR   r   r   T)rX   rY   r6   r:   r`   rn   )r=   rI   rJ   rK   rb   rY   rc   rf   rg   rP   tradess              r?   watch_tradeszlbank.watch_tradesz  s       !!!!!!!!!V$$it$&"22! 4L
 

 ""7F33zz#{G['RRRRRRRR))&%TRRRr@   c                    |                      |d          }|                     |          }|                     |          }|                     | j        |          }|5|                     | j        dd          }t          |          }|| j        |<   |                     |d          }|                     |d|g          }	t          dt          |	                    D ]8}
| 
                    |	|
         |          }||d<   |                    |           9|| j        |<   d|z   }|                    | j        |         |           d	|z   }|                    | j        |         |           d S )
NrT   tradesLimitrU   r   r   r   rI   r   r   )r[   r   r   rZ   r   rD   r7   r   rangelenparse_ws_trader   r   )r=   r   rg   r   rI   rY   r   rK   rawTrade	rawTradesir   rf   s                r?   handle_tradeszlbank.handle_trades  sg   6 ##GV44!!(++!!(++f55>%%dlM4HHE&&F"(DK??7G44OOGXzBB	q#i..)) 	! 	!A''	!f==E$E(OMM%    $F&(t{6*K888$v-t{6*K88888r@   c                    |                      |d          }||                     |          n|                     |d          }||                     |          }|                     |dd          }|                    dd          }|                     ||d d d d d ||                     |dd          |                     |d	d
          |                     |d          d |d|          S )Nr   r   	directionru   _market pricerC   volumert   amount)r   r   rI   rR   ordertypetakerOrMakersider   r   costfeer   )rD   iso8601r[   r   safe_string_2replace
safe_trade)r=   r   rY   r   r   r   s         r?   r   zlbank.parse_ws_trade  s    %%eQ//	1:1FDLL+++dN^N^_dfjNkNkx00I!!%a88||Ir**"  ''w::((!<<$$UH55 
  
   	r@   c                   K   |                                   d{V  |                     |           d{V }| j        d         d         }d}d}|d}n=|                     |          }	|                     |          }d|	d         z   }|	d         }d	d
||d}
|                     |
|          }|                     |||||           d{V }|                     ||||d          S )ax  
        :see: https://github.com/LBank-exchange/lbank-official-api-docs/blob/master/API-For-Spot-EN/WebSocket%20API(Asset%20%26%20Order).md#websocketsubscribeunsubscribe
        get the list of trades associated with the user
        :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 lbank api endpoint
        :returns dict[]: a list of `trade structures <https://docs.ccxt.com/#/?id=public-trades>`
        Nr   r   allz
orders:allorders:rI   rR   rk   orderUpdate)rS   rk   subscribeKeyrT   T)rX   authenticater6   rY   rI   r:   r`   filter_by_symbol_since_limit)r=   rI   rJ   rK   rb   keyrc   rf   rT   rY   rg   rP   orderss                r?   watch_orderszlbank.watch_orders  s(      !!!!!!!!!%%f--------it$>&KK[[((F[[((F#fX&66K$<D!&	
 
 ""7F33zz#{G['RRRRRRRR00tTTTr@   c                    |                      |d          }|                     |d d          }d }| j        ,|                     | j        dd          }t          |          }n| j        }|                     |          }|                    |           || _        |                    |d           d|z   }|                    ||           d S )NrT   rr   ordersLimitrU   r   r   )	r[   r   r   rD   r7   r   parse_ws_orderr   r   )	r=   r   rg   r   rI   myOrdersrK   r   rf   s	            r?   handle_orderszlbank.handle_orders  s    & ##GV44!!(D#66;%%dlM4HHE-e44HH{H##G,,x***&(x-----r@   c           	      <   |                      |di           }|                     |dd          }|                    d          }|                     |d          }|                     |d          }d }|dk    r|dk    r
|d	k    rd	nd
}|                     |d          }	|                     |	|d          }
|                     |d          }|                     |d          }|                     |d          }d }|d	k    r|dk    r|}|                     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%|          S )&Nr   r   r   rr   r   rC   buysellrY   rK   rT   
updateTimeorderStatusorderAmtr   rR   uuidclientOrderId
customerIDr   r   lastTradeTimestamplastUpdateTimestamprI   r   r   
orderPrice	stopPricer   avgPricer   	remaining	remainAmtfilledaccAmtstatus)r   r   r   )	rZ   r[   splitr   rD   
safe_orderr   r   parse_ws_order_status)r=   r   rY   r   rawType	typePartsr   exchangeTyper   r   rI   r   r   orderAmountr   s                  r?   r   zlbank.parse_ws_order%  s   T ooe]B??"";;;MM#&&		1--''	155e6 1 1 , 8 888wD##E622!!(FC88%%k<@@	!!+}==&&{J??H45==D  
E 
$"";77 
 T--k<HH 
 	 

 Y// 
 !$ 
 "4#4#4[,#O#O 
 f 
 D 
 D 
 T''WlKK 
  
 t''Z@@ 
 d((h
KK 
 ))+{CC 
  d&&{H==! 
" d0088# 
$ ) 
  
  
* +  	r@   c                 @    dddddd}|                      |||          S )Ncanceledr   closed)z-10124)r[   )r=   r   statusess      r?   r   zlbank.parse_ws_order_statusv  s7    
 
 &&999r@   c                 R  K   |                                   d{V  |                     |          }| j        d         d         }d|d         z   }|d}dd||d	         d
}|                     ||          }|                     ||||           d{V }	|	                                S )a`  
        :see: https://www.lbank.com/en-US/docs/index.html#request-amp-subscription-instruction
        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|None limit: the maximum amount of order book entries to return
        :param dict params: extra parameters specific to the lbank api endpoint
        :returns dict: A dictionary of `order book structures <https://docs.ccxt.com/en/latest/manual.html#order-book-structure>` indexed by market symbols
        Nr   r   fetchOrderbook:rI   d   rP   depthrR   )rS   rP   r  rT   )rX   rY   r6   r:   r`   rK   
r=   rI   rK   rb   rY   rc   rf   rk   rP   	orderbooks
             r?   fetch_order_book_wszlbank.fetch_order_book_ws  s       !!!!!!!!!V$$it$'&*::=E4L	
 
	 ""9f55**S+wLLLLLLLL	   r@   c                 ~  K   |                                   d{V  |                     |          }| j        d         d         }d|d         z   }|                     |d          }|d}dd	||d
         d}|                     ||          }|                     ||||           d{V }	|	                                S )a  
        :see: https://www.lbank.com/en-US/docs/index.html#market-depth
        :see: https://www.lbank.com/en-US/docs/index.html#market-increment-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|None limit: the maximum amount of order book entries to return
        :param dict params: extra parameters specific to the lbank api endpoint
        :returns dict: A dictionary of `order book structures <https://docs.ccxt.com/en/latest/manual.html#order-book-structure>` indexed by market symbols
        Nr   r   
orderbook:rI   aggregationr  rk   r  rR   )rS   rk   r  rT   )rX   rY   r6   omitr:   r`   rK   r  s
             r?   watch_order_bookzlbank.watch_order_book  s       !!!!!!!!!V$$it$"VH%556=11=E! 4L	
 
	 ""9f55**S+wLLLLLLLL	   r@   c                     |                      |d          }|                     |          }|                     |d|          }|                      |d          }|                     |          }|                     | j        |          }||                     i           }|| j        |<   |                     |||dd          }	|                    |	           d|z   }
|                    ||
           d|z   }
|                    ||
           d S )NrT   r  r   bidsasksr  r  )	r[   r   rZ   r   
orderbooks
order_bookparse_order_bookresetr   )r=   r   rg   r   rI   	orderBookr   r   r  snapshotrf   s              r?   handle_order_bookzlbank.handle_order_book  s   r ##GV44!!(++OOGWg>>	##GT22NN8,,	OODOV<<	++I&/DOF#((FIvvVV!!!"V+y+...'&0y+.....r@   c                     |                      |dd          }t          | j        dz   |z             }|                    |           d S )Nrg   r    )r[   r   rR   reject)r=   r   rg   errMsgerrors        r?   handle_error_messagezlbank.handle_error_message  sK     !!'9b99dgmf455er@   r   c                 r   K   |                      |d          }|                    d|d           d {V  d S )Npingpong)rS   r)  )r[   send)r=   r   rg   pingIds       r?   handle_pingzlbank.handle_ping
  sk       !!'622kk
 
   	 	 	 	 	 	 	 	 	r@   c                 r   |                      |d          }|dk    r|                     ||           d S |                     |dd          }|dk    r|                     | j        ||           d S | j        | j        | j        | j        | j	        d}| 
                    ||          }| |||           d S d S )Nr   r%  r   rS   r(  )rQ   r  r   r   r   )r[   r&  r   spawnr,  r   r   r   r   r   rZ   )r=   r   rg   r   r   handlershandlers          r?   handle_messagezlbank.handle_message  s    !!'844W%%fg666F!!'68<<6>>JJt'999F%+'&-
 
 //(D11GFG$$$$$ r@   c                 j  K   | j         d         d         }|                     |          }|                                 }d}|                     |j        |          }||                                  |                     |           d {V }|                     |d          }|durt          | j        dz             | 	                    |d          | 
                    |d          d	|j        d<   n|                     |d
d          }	|	|k     rd|d         i}
|                     |                     |
|                     d {V }| 	                    |d          }|dk    rt          | j        dz             | 
                    |d          |d         d         d
<   |j        d         d         S )Nr   r   authenticatedresultTz failed to get subscribe keydataiZ2 )r   expiresr6  r   r   r   truez# failed to refresh the SubscribeKeysubscriptions)r6   r   millisecondsrZ   r8  check_required_credentialsspotPrivatePostSubscribeGetKeyr   rR   r[   rE   rD   "spotPrivatePostSubscribeRefreshKeyextend)r=   rb   rc   r   nowrf   r3  responser4  r6  rP   s              r?   r   zlbank.authenticate(  s      it$S!!!!%(<kJJ ++---!@@HHHHHHHHH __Xx88FT!!#DG.L$LMMM''&9988C115 5F 11
 ''y!DDG}}"M%$8 "&!H!HU\^dIeIe!f!fffffff ))(H==V##'2W(WXXXFJhhsT[F\F\'8C#O4U;;r@   )N)&__name__
__module____qualname__r<   rH   strr   r   listrh   rp   r   r
   r   r   r   r   r   r   r   r   r   r	   r   r   r   r   r   r   r  r  r   r&  r   r,  r1  r   __classcell__)r>   s   @r?   r   r      s       * * * * *X   ;?T`dmo O O3 Os OZ] Otxy}t~ O O O O@ 8<$]ajl H H HC HWZ Hquvzq{ H H H H<c0 c0 c0J 46 O O& O O O O* 68 Q Q QF Q Q Q Q(2 2 2@/ / / /b ?CQU^` O OC O O3 Oeijoep O O O O4 <@d[] S S SS S Sbfglbm S S S S.-9 -9 -9^! ! ! !F 04$UYbd U U UC Us Uimnsit U U U U@ .  .  .DO O O Ob: : : CGr ! ! !C !V_ ! ! ! !2 @DB ! !S ! !S\ ! ! ! !6G/ G/ G/R      % % %( )+ #< #< #< #< #< #< #< #<r@   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   async_supportr    r@   r?   <module>rO     s        f f f f f f f f f f  E E E E E E E E E E E E E E E E 4 4 4 4 4 4       * * * * * *|< |< |< |< |<D$ |< |< |< |< |<r@   