
    ":h@                         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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 d d	lmZ d d
lmZ  G d dej@                  jB                        Z!y)    N)
ArrayCacheArrayCacheBySymbolByIdArrayCacheByTimestamp)AnyBalancesIntNumOrder	OrderBook	OrderSide	OrderTypeStrStringsTickerTickersTrade)Client)List)ExchangeError)AuthenticationError)
BadRequest)InvalidOrder)Precisec                       e Zd Zdef fdZi fdZdi fdedededefd	Z	i fdefd
Z
di fdedededededefdZdi fdedefdZdi fdee   defdZd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i fdedefdZdi fdedefdZddi fdedededee   fdZ ddi fdee   dededee   fdZ!di fdedede"f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%i fde&fd#Z'd6defd$Z(defd%Z)defd&Z*d6d'Z+d( Z,d6d)Z-defd*Z.d6d+Z/defd,Z0defd-Z1defd.Z2d/ Z3defd0Z4defd1Z5defd2Z6defd3Z7defd4Z8defd5Z9 xZ:S )7poloniexreturnc                     | j                  t        t        |          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dddddddddiiddddddiddddd d!d"d#d$d%d&d'd(d)d*d+d,d-d.| j                  d/d0      S )1NwsT
watchOHLCVwatchOrderBookwatchTickerwatchTickerswatchTradeswatchTradesForSymbolswatchBalancewatchStatusFwatchOrderswatchMyTradescreateOrderWseditOrderWsfetchOpenOrdersWsfetchOrderWscancelOrderWscancelOrdersWs)cancelAllOrdersWsfetchTradesWsfetchBalanceWsapizwss://ws.poloniex.com/ws/publicz wss://ws.poloniex.com/ws/private)publicprivate  namebook_lv2i  i  candles_minute_1candles_minute_5candles_minute_10candles_minute_15candles_minute_30candles_hour_1candles_hour_2candles_hour_4candles_hour_6candles_hour_12candles_day_1candles_day_3candles_week_1candles_month_1)1m5m10m15m30m1h2h4h6h12h1d3d1w1M)!createMarketBuyOrderRequiresPricetradesLimitordersLimit
OHLCVLimitr    connectionsLimitrequestsLimit
timeframesi:  )	keepAliveping)hasurlsoptions	streaming)deep_extendsuperr   describer\   )self	__class__s    K/var/www/html/turnos/venv/lib/python3.12/site-packages/ccxt/pro/poloniex.pyrc   zpoloniex.describe   s   h > @dd !$ t	
  t (  u t     u $U    !" !$#$ &*!&"'). "C#E 6:##"J# %)!$,,...****,))*+8 #		u>C
 > >	    c                 R  K   | j                          | j                  | j                               }| j                  d   d   d   }d}| j	                  |      }| j                  |j                  |      }|d}d|z   dz   |z   }| j                  | j                  |      | j                  | j                        t        j                  d	      }	d
dg| j                  ||	dddd}
| j                  |
|      }| j                  ||||       d{   }||j                  |<   |S 7 w)z
 @ignore
        authenticates the user to access private web socket channels

        https://api-docs.poloniex.com/spot/websocket/authentication

        :returns dict: response from exchange
        r2   r   r4   authenticatedNz/wszGET
z
signTimestamp=base64	subscribeauth
HmacSHA2562)keysignTimestamp	signaturesignatureMethodsignatureVersion)eventchannelparams)check_required_credentialsnumber_to_stringmillisecondsr^   client
safe_valuesubscriptionshmacencodesecrethashlibsha256apiKeyextendwatch)rd   rv   	timestampurlmessageHashrz   future
accessPathrequestStringrq   requestmessages               rf   authenticatezpoloniex.authenticateV   s,     	'')))$*;*;*=>	iit$Y/%S!!5!5{C>J#j03EE	QM		$++m"<dkk$++>VX_XfXfhpqI$"8;;%.!*'3(+
G kk'62G::c;MMF* 17F  -- Ns   DD'D%D'Nr6   r   	isPrivatesymbolsc                 Z  K   |rdnd}| j                   d   d   |   }d|gd}g }	| j                  |      r|	j                  d       n(|dz   d	j                  |      z   }| j	                  |      }	|d
k7  r|	|d<   | j                  ||      }
| j                  |||
|       d{   S 7 w)a  
 @ignore
        Connects to a websocket channel
        :param str name: name of the channel
        :param str messageHash: unique identifier for the message
        :param boolean isPrivate: True for the authenticated url, False for the public url
        :param str[] [symbols]: CCXT market symbols
        :param dict [params]: extra parameters specific to the poloniex api
        :returns dict: data from the websocket stream
        r4   r3   r2   r   rk   )rt   ru   all::,balancesr   N)r^   is_emptyappendjoin
market_idsr   r   )rd   r6   r   r   r   rv   publicOrPrivater   rk   	marketIdsr   s              rf   rk   zpoloniex.subscribe   s      (1)hiit$_5 
	 	==!U#%,sxx/@@K0I:#,Ii ++i0ZZ[';GGGGs   B"B+$B)%B+c                    K   | j                   d   d   d   }t        | j                               }|||d}| j                  ||||       d{   S 7 w)z
 @ignore
        Connects to a websocket channel
        :param str name: name of the channel
        :param dict [params]: extra parameters specific to the poloniex api
        :returns dict: data from the websocket stream
        r2   r   r4   )idrt   rv   N)r^   strnoncer   )rd   r6   rv   r   r   rk   s         rf   trade_requestzpoloniex.trade_request   s]      iit$Y/$**,'
	
 ZZ[)[IIIIs   AAAAsymboltypesideamountpricec                   K   | j                          d{    | j                          d{    | j                  |      }|j                         }|j                         }	| j	                  |dk(  |dk(  |      }
|
rd}|d   |j                         |j                         d}|dk(  r|	dk(  rd}d}| j                  |dd	d      \  }}| j                  |d
      }| j                  |d
      }|| j                  ||      }ny|re|t        | j                  dz         | j                  |      }| j                  |      }t        j                  ||      }| j                  ||      }n| j                  ||      }||d<   n/| j                  |d   |      |d<   || j                  ||      |d<   | j!                  d| j#                  ||             d{   }| j%                  |d      }|S 7 7 7 w)a  

        https://api-docs.poloniex.com/spot/websocket/trade-request#create-order

        create a trade order
        :param str symbol: unified symbol of the market to create an order in
        :param str type: 'market' or 'limit'
        :param str side: 'buy' or 'sell'
        :param float amount: how much of currency you want to trade in units of base currency
        :param float [price]: the price at which the order is to be fulfilled, in units of the quote currency, ignored in market orders
        :param dict [params]: extra parameters specific to the poloniex api endpoint
        :param str [params.timeInForce]: GTC(default), IOC, FOK
        :param str [params.clientOrderId]: Maximum 64-character length.*
        :param float [params.cost]: *spot market buy only* the quote quantity that can be used alternative for the amount

 EXCHANGE SPECIFIC PARAMETERS
        :param str [params.amount]: quote units for the order
        :param boolean [params.allowBorrow]: allow order to be placed by borrowing funds(Default: False)
        :param str [params.stpMode]: self-trade prevention, defaults to expire_taker, none: enable self-trade; expire_taker: taker order will be canceled when self-trade happens
        :param str [params.slippageTolerance]: used to control the maximum slippage ratio, the value range is greater than 0 and less than 1
        :returns dict: an `order structure <https://github.com/ccxt/ccxt/wiki/Manual#order-structure>`
        NMARKETLIMIT_MAKERr   )r   r   r   BUYTcreateOrderrT   costa	   createOrder() requires the price argument for market buy orders to calculate the total cost to spend(amount * price), alternatively set the createMarketBuyOrderRequiresPrice option or param to False and pass the cost to spend(quote quantity) in the amount argumentr   r   quantityr   r   )load_marketsr   marketupperis_post_onlyhandle_option_and_paramssafe_numberomitcost_to_precisionr   r   rx   r   
string_mulamount_to_precisionprice_to_precisionr   r   	safe_dict)rd   r   r   r   r   r   rv   r   uppercaseTypeuppercaseSide
isPostOnlyr   quoteAmountrT   r   amountStringpriceStringcostRequestordersorders                       rf   create_order_wszpoloniex.create_order_ws   s"    . !!!!!!V$



&&}'@-S`B`bhi
)MTlJJLJJL

 X%MU,BK04-8<8U8UV\^k  nQ  SW  9X5-v##FF3DYYvv.F"44VTB2=&tww  2}  (}  ~  ~#'#8#8#@L"&"7"7">K")"4"4\;"OK"&"8"8"MK"44VVD +GH"&":":6(;KV"TGJ #'#:#:65#I ))-Wf9UVVvq)M 	"!F Ws2   G8G0G8G3F(G8G6G83G86G8r   c                    K   | j                  |d      }|)| j                  |dg       }| j                  ||g      |d<   | j                  |g||       d{   }| j	                  |d      }|S 7 w)a  

        https://api-docs.poloniex.com/spot/websocket/trade-request#cancel-multiple-orders

        cancel multiple orders
        :param str id: order id
        :param str [symbol]: unified market symbol
        :param dict [params]: extra parameters specific to the poloniex api endpoint
        :param str [params.clientOrderId]: client order id
        :returns dict: an list of `order structures <https://github.com/ccxt/ccxt/wiki/Manual#order-structure>`
        clientOrderIdNclientOrderIdsr   )safe_stringr{   array_concatcancel_orders_wsr   )rd   r   r   rv   r   r   r   r   s           rf   cancel_order_wszpoloniex.cancel_order_ws   s      ((A$!__V_bIN'+'8'8-'YF#$,,bT66BBvq) Cs   AA2A0A2idsc                    K   | j                          d{    | j                          d{    d|i}| j                  d| j                  ||             d{   S 7 J7 47 w)a  

        https://api-docs.poloniex.com/spot/websocket/trade-request#cancel-multiple-orders

        cancel multiple orders
        :param str[] ids: order ids
        :param str symbol: unified market symbol, default is None
        :param dict [params]: extra parameters specific to the poloniex api endpoint
        :param str[] [params.clientOrderIds]: client order ids
        :returns dict: an list of `order structures <https://github.com/ccxt/ccxt/wiki/Manual#order-structure>`
        NorderIdscancelOrders)r   r   r   r   )rd   r   r   rv   r   s        rf   r   zpoloniex.cancel_orders_ws  sk      !!!!!!
 ''GV8TUUU 	"! Vs1   A'A!A'A#-A'A%A'#A'%A'c                    K   | j                          d{    | j                          d{    | j                  d|       d{   S 7 67  7 w)a$  

        https://api-docs.poloniex.com/spot/websocket/trade-request#cancel-all-orders

        cancel all open orders of a type. Only applicable to Option in Portfolio Margin mode, and MMP privilege is required.
        :param str symbol: unified market symbol, only orders in the market of self symbol are cancelled when symbol is not None
        :param dict [params]: extra parameters specific to the poloniex api endpoint
        :returns dict[]: a list of `order structures <https://github.com/ccxt/ccxt/wiki/Manual#order-structure>`
        NcancelAllOrders)r   r   r   )rd   r   rv   s      rf   cancel_all_orders_wszpoloniex.cancel_all_orders_ws"  sP      !!!!!!''(96BBB 	"!Bs1   AAAAAA	AAArz   c                     | j                  |d      }| j                  |dg       }g }t        dt        |            D ])  }||   }| j	                  |      }|j                  |       + |j                  ||       y )Nr   datar   )r   r{   rangelenparse_ws_orderr   resolve)	rd   rz   r   r   r   r   ir   parsedOrders	            rf   handle_order_requestzpoloniex.handle_order_request0  s|     &&w5w3q#d)$ 	'AGE--e4KMM+&	' 	v{+rg   rF   sincelimitc                 ~  K   | j                          d{    | j                  | j                  di       }| j                  |||      }|t	        | j
                  dz   |z         | j                  ||d|g|       d{   }| j                  r|j                  ||      }| j                  |||dd      S 7 7 9w)a  
        watches historical candlestick data containing the open, high, low, and close price, and the volume of a market

        https://api-docs.poloniex.com/spot/websocket/market-data#candlesticks

        :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
        NrZ   z' watchOHLCV cannot take a timeframe of Fr   T)
r   r{   r_   r   r   r   rk   
newUpdatesgetLimitfilter_by_since_limit)	rd   r   	timeframer   r   rv   rZ   ru   ohlcvs	            rf   watch_ohlcvzpoloniex.watch_ohlcvE  s      !!!__T\\<D
"":y)D?TWW'PPS\\]]nnWguvhOO??NN651E))%q$GG 	"
 Ps"   B=B9A*B=B;8B=;B=c                    K   | j                          d{    | j                  |      }| j                  |g|       d{   }| j                  ||      S 7 B7 w)a  
        watches a price ticker, a statistical calculation with the information calculated over the past 24 hours for a specific market

        https://api-docs.poloniex.com/spot/websocket/market-data#ticker

        :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>`
        N)r   r   watch_tickersr{   )rd   r   rv   tickerss       rf   watch_tickerzpoloniex.watch_ticker\  sY      !!!V$**F8V<<w// 	"<s!   AA+AAAAc                    K   | j                          d{    d}| j                  |      }| j                  ||d||       d{   }| j                  r|S | j	                  | j
                  d|      S 7 _7 1w)a  
        watches a price ticker, a statistical calculation with the information calculated over the past 24 hours for a specific market

        https://api-docs.poloniex.com/spot/websocket/market-data#ticker

        :param str[] symbols:
        :param dict [params]: extra parameters specific to the exchange API endpoint
        :returns dict: a `ticker structure <https://docs.ccxt.com/#/?id=ticker-structure>`
        NtickerFr   )r   market_symbolsrk   r   filter_by_arrayr   )rd   r   rv   r6   
newTickerss        rf   r   zpoloniex.watch_tickersk  sz      !!!%%g.>>$eWfMM
??##DLL(GDD 	" Ns!   A:A6/A:A80A:8A:c                 H   K   | j                  |g|||       d{   S 7 w)a&  
        get the list of most recent trades for a particular symbol

        https://api-docs.poloniex.com/spot/websocket/market-data#trades

        :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)watch_trades_for_symbols)rd   r   r   r   rv   s        rf   watch_tradeszpoloniex.watch_trades}  s'      22F8UE6RRRRs   " "c                 F  K   | j                          d{    | j                  |dddd      }d}| j                  d   d   d   }| j                  |      }d|g|d	}| j	                  ||      }	g }
|4t        d
t        |            D ]  }|
j                  |dz   ||   z           | j                  ||
|	|
       d{   }| j                  r6| j                  |d
      }| j                  |d      }|j                  ||      }| j                  |||dd      S 7 7 ^w)a'  
        get the list of most recent trades for a list of symbols

        https://api-docs.poloniex.com/spot/websocket/market-data#trades

        :param str[] symbols: 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>`
        NFTtradesr2   r   r3   rk   )rt   ru   r   r   r   r   r   )r   r   r^   r   r   r   r   r   watch_multipler   r{   r   r   r   )rd   r   r   r   rv   r6   r   r   rk   r   messageHashesr   r   firsttradeSymbols                  rf   r   z!poloniex.watch_trades_for_symbols  s=     !!!%%gtUD$Giit$X.OOG,	  !
	 ++i01c'l+ ?$$TD[71:%=>?**3wVV??OOFA.E**5(;KOOK7E))&%TRR- 	"" Ws#   D!DB)D! DAD!D!c                 *  K   | j                          d{    | j                  | j                  d      }| j                  |dd      }| j	                  |dd|      \  }}| j                  ||d|g|       d{   }|j                         S 7 x7 w)a4  
        watches information on open orders with bid(buy) and ask(sell) prices, volumes and other data

        https://api-docs.poloniex.com/spot/websocket/market-data#book-level-2

        :param str symbol: unified symbol of the market to fetch the order book for
        :param int [limit]: not used by poloniex watchOrderBook
        :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
        Nr    r6   r7   methodF)r   r{   r_   r   r   rk   r   )rd   r   r   rv   watchOrderBookOptionsr6   	orderbooks          rf   watch_order_bookzpoloniex.watch_order_book  s      !!! $>N O 5vzJ44VXvtTf..tUVHfMM	   	" Ns"   BBA#B:B;BBc                 N  K   | j                          d{    d}| j                          d{    || j                  |      }|dn|g}| j                  ||d||       d{   }| j                  r|j                  ||      }| j                  |||dd      S 7 7 p7 ;w)a  
        watches information on multiple orders made by the user

        https://api-docs.poloniex.com/spot/websocket/order

        :param str symbol: unified market symbol of the market orders were made in
        :param int [since]: not used by poloniex watchOrders
        :param int [limit]: not used by poloniex watchOrders
        :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   Tr   r   r   r   rk   r   r   r   )rd   r   r   r   rv   r6   r   r   s           rf   watch_orderszpoloniex.watch_orders  s      !!!!!![[(F!>$~~dD$HH??OOFE2E))&%TRR 	"! Is1   B%BB%B!6B%'B#(8B%!B%#B%c                 R  K   | j                          d{    d}d}| j                          d{    || j                  |      }|dn|g}| j                  ||d||       d{   }| j                  r|j                  ||      }| j                  |||dd      S 7 7 p7 ;w)a  
        watches information on multiple trades made by the user using orders stream

        https://api-docs.poloniex.com/spot/websocket/order

        :param str symbol: unified market symbol of the market orders were made in
        :param int [since]: not used by poloniex watchMyTrades
        :param int [limit]: not used by poloniex watchMyTrades
        :param dict [params]: extra parameters specific to the poloniex strean
        :returns dict[]: a list of `trade structures <https://docs.ccxt.com/#/?id=trade-structure>`
        Nr   myTradesTr   r   )	rd   r   r   r   rv   r6   r   r   r   s	            rf   watch_my_tradeszpoloniex.watch_my_trades  s      !!! !!![[(F!>$~~dKwOO??OOFE2E))&%TRR 	" 	" Ps1   B'B!B'B#6B')B%*8B'#B'%B'c                    K   | j                          d{    d}| j                          d{    | j                  ||dd|       d{   S 7 ;7 #7 w)a\  
        watch balance and get the amount of funds available for trading or funds locked in orders

        https://api-docs.poloniex.com/spot/websocket/balance

        :param dict [params]: extra parameters specific to the exchange API endpoint
        :returns dict: a `balance structure <https://docs.ccxt.com/#/?id=balance-structure>`
        Nr   T)r   r   rk   )rd   rv   r6   s      rf   watch_balancezpoloniex.watch_balance  sX      !!!!!!^^D$dFCCC 	"!Cs1   AAAAAAAAAc           	          | j                  |d      | j                  |d      | j                  |d      | j                  |d      | j                  |d      | j                  |d      gS )N	startTimeopenhighlowcloser   )safe_integerr   )rd   r   r   s      rf   parse_ws_ohlcvzpoloniex.parse_ws_ohlcv  sn    " e[1UF+UF+UE*UG,UJ/
 	
rg   c                    | j                  |d      }| j                  |d      }| j                  |d      }| j                  |d      }| j                  |      }| j                  |      }| j                  | j                  di       }| j                  ||      }	|dz   |z   }
| j                  ||      }| j                  | j                  |i       | j                  |<   | j                  | j                  |   |	      }|_|:| j                  | j                  dd      }t        |      }|| j                  |   |	<   |j                  |       |j                  ||
       |S )	Nr   r   ru   r   rZ   r   rW   r5   )r{   r   safe_symbolsafe_marketr_   find_timeframer  ohlcvsr  r   r   r   )rd   rz   r   r   ru   marketIdr   r   rZ   r   r   parsedstoredr   s                 rf   handle_ohlcvzpoloniex.handle_ohlcv  sG   * w/tQ'""7I6##D(3!!(+!!&)__T\\<D
''<	nv-$$T62"oodkk62FFV!4i@~))$,,dK.u517F#I.MM&!NN6;/rg   c                    | j                  |dg       }t        dt        |            D ]  }||   }| j                  |d      }|| j	                  |      }|d   }d}	|	dz   |z   }
| j                  | j
                  |      }|7| j                  | j                  dd      }t        |      }|| j
                  |<   |j                  |       |j                  ||
        |S )Nr   r   r   r   r   rU   r5   )r{   r   r   r   parse_ws_trader   r  r_   r   r   r   )rd   rz   r   r   r   itemr  trader   r   r   tradesArrayrU   s                rf   handle_tradezpoloniex.handle_tradeA  s    $ w3q#d)$ 	9A7D''h7H#++D1x"TkF2"oodkk6B&"&"3"3DLL-QU"VK",["9K*5DKK'""5){K8	9 rg   c                    | j                  |d      }| j                  ||      }| j                  |d      }| j                  |dd      }| j	                  || j                  |dd      | j                  |d      || j                  |      | j                  |d      | j                  |d      | j                  |d	d
      || j                  | j                  |dd            | j                  | j                  |dd            | j                  |dd      d | j                  |d      | j                  |d      dd|      S )Nr   
createTime	matchRoletakerr   tradeIdorderIdr   	takerSider   
tradePricer   filledQuantityr   r   filledAmounttradeFeefeeCurrencyrater   currencyinfor   r   r   datetimer   r   r   takerOrMakerr   r   r   fee)	r   r  r  safe_string_lower_2
safe_tradesafe_string_2iso8601safe_string_lower	omit_zero)rd   r  r   r  r   
takerMakers         rf   r  zpoloniex.parse_ws_tradee  sE   V ##E84!!(F3%%e\:	--e['J
$$UD)<&&vx8"Y/%%eY7**5&9,,UKH&^^D$6$6ulG$TUnnT%7%7?OQ[%\]&&uhG((
; ,,UMB 
$ % 	rg   c                 :    ddddddd}| j                  |||      S )Nr  closedcanceled)NEWPARTIALLY_FILLEDFILLEDPENDING_CANCELPARTIALLY_CANCELEDCANCELED)r   )rd   statusstatusess      rf   parse_statuszpoloniex.parse_status  s2     &$"("
 &&99rg   c                    | j                  |d      }| j                  |d      }| j                  || j                  |d      | j                  ||      || j	                  |      | j                  |d      | j                  |d      | j                  |d      | j                  |d      | j                  |d      | j                  |d	      d d | j                  |d
      | j                  |d      dd|      S )N	tradeTimer   r  r  r   r   r  r   tradeAmountr"  r#  r$  r'  )r  r   r-  r
  r/  r0  )rd   r  r   r   r  s        rf   parse_ws_order_tradezpoloniex.parse_ws_order_trade  s    : %%e[9	##E84""5)4&&x8"Y/%%eY7**5&9$$UF3 225+F%%eW5&&um<((
; ,,UMB 
$ % 	rg   c                    | j                  |dg       }| j                  }|.| j                  | j                  d      }t	        |      }|| _        g }t        dt        |            D ]'  }| j                  ||      }| j                  |d      }	| j                  |d      }
|	=| j                  |	      }| j                  |d      }| j                  |d      }|
dk(  s|
d	k(  r$| j                  |      }|j                  |       nw| j                  |j                  |i       }| j                  |||      }| j                  |      }| j                  ||       |d
   g |d
<   |d
   j                  |       |d   |d<   d}d}|d
   }t        dt        |            D ][  }||   }| j                  |d         }| j                  |d         }t!        j"                  ||      }t!        j"                  ||      }] t!        j$                  |d      r(| j'                  t!        j(                  ||            |d<   | j'                  |      |d<   |d   | j                  |d         }| j                  |d         }t!        j"                  ||      }||d<   |d   <| j                  |d         }| j'                  t!        j*                  ||            |d<   |d   d d|d   d   d|d<   |d   d   R|d   d   J| j                  |d   d         }| j                  |d   d         }t!        j"                  ||      |d   d<   | j                  |d      }| j-                  |      }||d<   |j                  |       |j                  |	       * t        dt        |            D ]4  }||   }	| j/                  |	      } | d   }d|z   }!|j1                  ||!       6 |j1                  |d       |S )Nr   rV   r   r   	eventTyper  r   placer5  r   r   lastTradeTimestamp0r   r   averagefilled	remainingr+  r&  r$  stater<  zorders::r   )r{   r   r  r_   r   r   r   r   r
  r   r   hashmapsafe_value_2r  handle_my_tradesrx   r   
string_add	string_gtparse_number
string_div
string_subr>  r   r   )"rd   rz   r   r   r   r   r   r   r   r  rD  r   r  r   r  previousOrderspreviousOrderr  	totalCosttotalAmountpreviousOrderTradesjpreviousOrderTrader   r   rA  previousOrderFilledpreviousOrderAmountstringOrderCoststringTradeCostrawStaterK  r   r   s"                                     rf   handle_orderzpoloniex.handle_order  sR   H w3>%%dllMBE+E2F DK	q#d)$ 7	+AOOD!,E''x8H((<I#))(3**5)< $ 0 0 H'9
+B!007FMM&)%)__V^^VR%PN$($5$5ng}$]M //6E))&%8$X.624h/!(+2259:?:LM"67 #I"%K*7*A'"1c*=&>? N-@-C*#445G5OP!%!6!67I(7S!T$+$6$6y$$G	&-&8&8f&MN ((c:373D3DWEWEWXacnEo3pi0,0,=,=i,HM&)$X.:&*&;&;E(O&L.2.C.CMRZD[.\+.5.@.@ATVa.b+2Eh/(2>262G2GV^H_2`/9=9J9J7K]K]^q  tG  LH  :IM+6$U+3$($%(-eZ(@0e,
 &e,V4@uU|TZG[Gg*.*?*?e@TU[@\*]*.*?*?eV@T*U7>7I7I/[j7ke,V4#//w?H --h7E.3M(+MM-0  *o7	+p q#i.) 	0A |H[[*FH%F$v-KNN6;/	0 	vx(rg   c                 .   | j                  |d      }| j                  |d      }| j                  |d      }| j                  |d      }| j                  |d      }| j                  |d      }d }	t        j                  |d      s$g }	| j                  |      }
|	j	                  |
       | j                  i d|d| j                  ||      d	|d|d
|d| j                  |      dd d| j                  |d      dd dd d| j                  |d      d| j                  |d      dd dd d| j                  |d      dd dd || j                  |d      | j                  |      d | j                  |d      | j                  |d      d|	d      S )Nr  r   r   tsr!  rK  rG  r(  r   r   r)  rF  r   timeInForcepostOnlyr   r   	stopPricetriggerPricer   r   r   rH  remaining_sizer"  r#  r$  )rI  rJ  r<  r+  r   )	r   r   	string_eqrB  r   
safe_orderr
  r/  r>  )rd   r   r   r   r   r  r   r!  r<  r   r  s              rf   r   zpoloniex.parse_ws_orderS  s$   : eY/((@##E84$$UD1	''~>!!%1  s3F--e4EMM%   
E 
d&&x8 
 " 
 ]	 

  
 Y/ 
 !$ 
 D$$UF3 
 4 
  
 D$$UF3 
 T%%eW5 
  
 D 
 d&&uj9 
  D! 
" t# 
$ #))%1AB''/((
; ,,UMB
 5 
  	rg   c                 .   | j                  |dg       }i }t        dt        |            D ]F  }||   }| j                  |d      }|| j	                  |      }|d   }	|| j
                  |	<   |||	<   H | j                  |d      }
t        dt        |
            D ]e  }|
|   }|j                  d      }|d   }|j                  d      }| j                  |d|      }| j                  |      rT|j                  ||       g |j                  |d       |S )	Nr   r   r   zticker::r      r   r   )r{   r   r   r   parse_tickerr   find_message_hashessplitr   r   r   )rd   rz   r   r   r   r   r  r  r   r   r   r   partssymbolsStringr   r   s                   rf   handle_tickerzpoloniex.handle_ticker  s-   . w3
q#d)$ 	,A7D''h7H#**40)'-V$%+
6"	, 00Dq#m,- 	5A'*K%%d+E!!HM#))#.G**:xIG==)w4	5 	z8,rg   c                 @   | j                  |dg       }| j                  |d      }|dk(  }|dk(  }t        dt        |            D ]  }||   }| j                  |d      }	| j	                  |	      }
|
d   }d}|dz   |z   }| j                  |j
                  |i       }| j                  |d	      }| j                  |d
      }| j                  |d      }| j                  |d      }|s|s|r| j                  i |      | j                  |<   | j                  |   }|gt        dt        |            D ]O  }| j                  ||      }| j                  |d      }| j                  |d      }|d   }|j                  ||       Q |gt        dt        |            D ]O  }| j                  ||      }| j                  |d      }| j                  |d      }|d   }|j                  ||       Q ||d<   ||d<   | j                  |      |d<   |j                  ||        y )Nr   actionsnapshotupdater   r   r7   r   r   rb  asksbidsrk  r   r)  )r{   r   r   r   r  r|   r  
order_book
orderbooksr   storer/  r   )rd   rz   r   r   r   rt  ru  r   r  r  r   r   r6   r   subscriptionr   r   rv  rw  r   rY  bidr   r   bidsSideaskasksSides                              rf   handle_order_bookzpoloniex.handle_order_book  s<   ` w32:%!q#d)$ !	7A7D''h7H%%h/FH%FD+.K??6+?+?bQL%%lG<E))$5I??40D??40D6.2oob%.HDOOF+ OOF3	#"1c$i0 6"oodA6 $ 0 0a 8!%!1!1#q!9#,V#4 uf56 #"1c$i0 6"oodA6 $ 0 0a 8!%!1!1#q!9#,V#4 uf56 '-	(#)2	+&(,Y(?	*%y+6C!	7rg   c                     | j                  |dg       }d}| j                  |      | _        |j                  | j                  |       y )Nr   r   )r{   parse_ws_balancebalancer   )rd   rz   r   r   r   s        rf   handle_balancezpoloniex.handle_balance  s?    ( w3 ,,T2t||[1rg   c                    | j                  |di       }| j                  |d      }||| j                  |      d}t        dt	        |            D ]v  }| j                  ||      }| j                  |d      }| j                  |      }| j                         }	| j                  |d      |	d<   | j                  |d      |	d<   |	||<   x | j                  |      S )	Nr   rb  )r(  r   r)  r&  	availablefreeholdused)	r{   r  r/  r   r   r   safe_currency_codeaccountsafe_balance)
rd   responsefirstBalancer   resultr   r  
currencyIdcode
newAccounts
             rf   r  zpoloniex.parse_ws_balance5  s    " xB7%%lD9	"Y/

 q#h-( 	&Aooh2G))':>J**:6DJ!%!1!1';!GJv!%!1!1'6!BJv%F4L	&   ((rg   c                    d}|d   }| j                   -| j                  | j                  dd      }t        |      | _         | j                   }|j	                  |       |j                  ||       |dz   |z   }|j                  ||       y )Nr   r   rU   r5   :)r   r  r_   r   r   r   )rd   rz   parsedTrader   r   r   r   symbolMessageHashs           rf   rN  zpoloniex.handle_my_tradesW  s     X&== %%dllM4HE259DMk"v{+'#-6v01rg   c                 .    | j                         |_        y N)ry   lastPongrd   rz   s     rf   handle_pongzpoloniex.handle_pongd  s    ++-rg   c           	         | j                  ||      ry | j                  |d      }| j                  |d      }|dk(  r| j                         |_        i d| j                  d| j                  d| j                  d| j                  d| j                  d	| j                  d
| j                  d| j                  d| j                  d| j                  d| j                  d| j                  d| j                  d| j                  d| j
                  d| j
                  d| j                  | j                  | j                  | j                  | j                  | j                  | j                  | j                  d}| j                  ||      }|dk(  r| j                  ||       y || j                  ||       y | j                  |dg       }t        |      }|dkD  r
 |||       y y )Nru   rt   pongr8   r9   r:   r;   r<   r=   r>   r?   r@   rA   rB   rC   rD   rE   bookr7   r   )r   r   r   r   cancelOrderr   rl   rl   r   r   )handle_error_messager   ry   r  r  r  rq  r  r`  r  r   handle_authenticater{   r   )	rd   rz   r   r   rt   methodsr   r   
dataLengths	            rf   handle_messagezpoloniex.handle_messageg  s:   $$VW53  '2F?"//1FO
 1 1
 1 1
  !2!2
  !2!2	

  !2!2
 d//
 d//
 d//
 d//
 t00
 T..
 T..
 d//
 t00
 D**
  ..!
" d((#
$ ''''++4444#88,,1
4 $/6>$$VW5\%%fg6??7FB7DTJA~vw' rg   c                    | j                  |d      }| j                  |d      }| j                  |d      }| j                  |d      }| j                  |d      }|dk(  s|dk(  r	 | j                  |d      }| j                  |d	      }	| j                  d
z   | j	                  |      z   }
| j                  | j                  d   |	|
       | j                  | j                  d   ||
       t        |
      y# t        $ r\}t        |t              r0d}|j                  ||       ||j                  v r |j                  |= n|j                  ||       Y d }~yd }~ww xY w)Nr   rt   r   r   r  errorrG  r   r   exactbroadri   TF)r   	safe_listr   r   jsonthrow_exactly_matched_exception
exceptionsthrow_broadly_matched_exceptionr   	Exception
isinstancer   rejectr|   )rd   rz   r   r   rt   r   r   r  r  r  feedbacker   s                rf   r  zpoloniex.handle_error_message  sQ   < gt,  '2~~gv.tQ'""5)4W'S.((	:''v677S=499W+==44T__W5MtU]^44T__W5MuV^_#H--   a!45"1KMM![1"f&:&::"00=MM!R(s   &BC7 7	E AEEc                 ,   | j                  |d      }| j                  |d      }d}|r|j                  ||       |S t        | j                  dz   | j	                  |      z         }|j                  ||       ||j                  v r|j                  |= |S )Nr   successri   r  )r{   r   r   r   r  r  r|   )rd   rz   r   r   r  r   r  s          rf   r  zpoloniex.handle_authenticate  s     w///$	2%NN7K0 	 (#		'8J(JKEMM%-f222((5rg   c                 
    ddiS )Nrt   r\    r  s     rf   r\   zpoloniex.ping  s    V
 	
rg   r  );__name__
__module____qualname__r   rc   r   r   boolr   rk   r   r   r   floatr	   r
   r   r   r   r   r   r   r   r   r   listr   r   r   r   r   r   r   r   r   r   r   r   r   r   r  r  r  r  r>  rB  r`  r   rq  r  r  r  rN  r  r  r  r  r\   __classcell__)re   s   @rf   r   r      s^   ?# ?B )+ 5n `dln HC Hc Hd HU\ H< 57 J J" pt|~ =C =y =	 =[` =il =  DI =~ <@  S ( DHPR V$s) VS V& 8<B C C,6 ,* 8<$]ajl H HC HWZ Hquvzq{ H. 68 0 0F 0 6:" E7 E E$ <@d[] S SS S Sbfglbm S OSaenp "Sd3i "S "S[^ "Suyz  vA "SH @DB !S ! !S\ !$ 04$UYbd S SC Ss Simnsit S. 37TX\eg SC Ss SRU Slpqvlw S0 *, D D
D 
2(6 (T"6 "HAF
:1fj6 jXCJ+F +ZU7 U7n2V 22 )D2v 2.& .*(V *(X46 4l& *
6 
rg   r   )"ccxt.async_supportccxt ccxt.async_support.base.ws.cacher   r   r   r   ccxt.base.typesr   r   r   r	   r
   r   r   r   r   r   r   r   r   !ccxt.async_support.base.ws.clientr   typingr   ccxt.base.errorsr   r   r   r   ccxt.base.preciser   async_supportr   r  rg   rf   <module>r     sZ     f f  B  B  B  B 4  * 0 ' ) %N
t!!** N
rg   