
    eiY                    ^   d dl Zd dlmZmZm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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 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% 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)AnyBalancesBoolIntNumOrder	OrderBook	OrderSide	OrderTypeStrStringsTickerTickersTrade)Client)List)ExchangeError)AuthenticationError)PermissionDenied)AccountSuspended)ArgumentsRequired)
BadRequest)	BadSymbol)InsufficientFunds)InvalidOrder)OrderNotFound)NotSupported)RateLimitExceeded)ExchangeNotAvailable)ChecksumError)Precisec                       e Zd Zdef 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	de
ded	edefdZd Zddi fdedede	de
ded	edefdZdi fdee         defdZdi fdededefdZd Zdi fdedee         fdZd Zd ZdefdZdefdZd Zi f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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i fdee         d e"de&fd$Z(d%ddi fded&ede"d e"dee)         f
d'Z*d(i f fd)	Z+defd*Z,defd+Z-i fd,Z.defd-Z/defd.Z0d/ Z1d0 Z2defd1Z3i fd2Z4dddi fdede"d e"fd3Z5dddi fdede"d e"dee#         fd4Z6dEdefd5Z7dEd6Z8dddi fdede"d e"dee         fd7Z9dEdefd8Z:dEd9Z;ddi fd:ed;edefd<Z<i fde=fd=Z>defd>Z?dFd?ed@edefdAZ@defdBZAdedeBfdCZCdefdDZD xZES )Gkrakenreturnc                    |                      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i ddid| j        dd dd!t
          ii d"t
          d#t          d$t          d%t
          d&t
          d't
          d(t          d)t
          d*t
          d+t
          d,t
          d-t
          d.t
          d/t
          d0t
          d1t          d2t          i d3t          d4t          d5t          d6t          d7t          d8t
          d9t          d:t          d;t          d<t          d=t          d>t          d?t          d@t          dAt          dBt          dCt          t          t          t          t          t          t          t           t           t           t          t
          t          dDdEidF          S )GNwsTwatchBalancewatchMyTrades
watchOHLCVwatchOrderBookwatchOrderBookForSymbolswatchOrderswatchTickerwatchTickerswatchBidsAskswatchTradeswatchTradesForSymbolscreateOrderWseditOrderWscancelOrderWscancelOrdersWscancelAllOrdersWsapizwss://ws.kraken.comzwss://ws-auth.kraken.comzwss://ws-auth.kraken.com/v2zwss://ws.kraken.com/v2zwss://beta-ws.kraken.comzwss://beta-ws-auth.kraken.com)publicprivate	privateV2publicV2betazbeta-private  checksumF)tradesLimit
OHLCVLimitordersLimitsymbolsByOrderIdr-   ip  )ping	keepAlivezEvent(s) not foundzAlready subscribedz'Currency pair not in ISO 4217-A3 formatzCurrency pair not supportedzMalformed requestzPair field must be an arrayz1Pair field unsupported for self subscription typezPair(s) not foundz*Subscription book depth must be an integerz Subscription depth not supportedz$Subscription field must be an objectzSubscription name invalidz%Subscription object unsupported fieldz-Subscription ohlc interval must be an integerz(Subscription ohlc interval not supportedz#Subscription ohlc requires intervalzEAccount:Invalid permissionsz EAuth:Account temporary disabledzEAuth:Account unconfirmedzEAuth:Rate limit exceededzEAuth:Too many requestsz+EDatabase: Internal error(to be deprecated)z EGeneral:Internal error[:<code>]zEGeneral:Invalid argumentsz$EOrder:Cannot open opposing positionzEOrder:Cannot open positionz2EOrder:Insufficient funds(insufficient user funds)z[EOrder:Insufficient margin(exchange does not have sufficient funds to allow margin trading)zEOrder:Invalid pricez EOrder:Margin allowance exceededzEOrder:Margin level too lowzaEOrder:Margin position size exceeded(client would exceed the maximum position size for self pair)z,EOrder:Order minimum not met(volume too low)zEOrder:Orders limit exceededzEOrder:Positions limit exceeded)zEOrder:Rate limit exceededz&EOrder:Scheduled orders limit exceededzEOrder:Unknown positionzEOrder:Unknown orderzEOrder:Invalid orderzEService:Deadline elapsedz#EService:Market in cancel_only modez"EService:Market in limit_only modez!EService:Market in post_only modezEService:UnavailablezETrade:Invalid requestzESession:Invalid session)exactbroad)hasurlsoptions	streaming
exceptions)deep_extendsuperr&   describerF   r   r   r   r   r   r!   r   r   r   r   r"   r    )self	__class__s    M/var/www/html/volatility/venv/lib/python3.11/site-packages/ccxt/pro/kraken.pyrQ   zkraken.describe   s   fd 3 3 < < > >d   d	
 !$ +D t t    t (   t    !$!" $T#, "7#=%B$< :(G 	   $"#$&#  	! 
 ,j/,j/A9/ 6y/ ,Z	/
 6z/ LZ/ ,Y/ Ej/ ;J/ ?
/ 4Z/ @/ H/ CJ/ >z/  78H!/" ;<L#/ /$ 45H%/& 45F'/( 23D)/* F}+/, ;M-/. 5j//0 ?1/2 6|3/4 MN_5/6 v  xI7/8 /9/: ;L;/< 6|=/> |  ~J?/@ GA/B 7C/D :<E/ /F 7HBN3@0=0<5I?K>J=I0D2<4G]/ / /	4 46eiA
 iA
 i i i	    Nmethodsymboltyperequestamountpricec                    |                     d          }|rK|t          | j        dz             |                     |                     ||                    |d         d<   |dk    }	d }
|                     |	d|          \  }
}|
rd|d         d<   |                     |d	          }|||d         d
<   |                     |d          }|2|                     |                     ||                    |d         d<   |                     |di           }|                     |di           }|                     |d          }|                     |d          }|                     |d          }|                     |d          }|d u}|d u}|                     |d          }|                     |d          }|d u}|d u}|                     |d          }|                     |d          }|                     |d          }|                     |d          }|d u}|d u}|d u}|d u} |                     |dd          }!||!| 	                    |          z   nd }"||!| 	                    |          z   nd }#||!| 	                    |          z   nd }$||!| 	                    |          z   nd }%|s| rdnd}&|dk    rW| 
                    |d          }'|'rd|d         d<   |                     |d          }(|(|(|d         d<   |                     |ddg          }|s
|s|s|s|s| ri |d         d <   |s|rSi |d         d!<   |rJd"|d         d!         d#<   |                     |                     ||                    |d         d!         d$<   nK|rId%|d         d!         d#<   |                     |                     ||                    |d         d!         d$<   |Jd&|d         d!         d#<   |                     |                     ||                    |d         d!         d<   nK|Id'|d         d!         d#<   |                     |                     ||                    |d         d!         d<   |                     |ddg          }n|s|r|rT|                     |                     ||                    |d         d          d<   |rd&|d         d#<   nnd"|d         d#<   na|                     |                     ||                    |d         d          d<   |rd'|d         d#<   nd%|d         d#<   n|s|s|s| r|&|d         d          d(<   |s]|s|rYd)|d         d#<   |r&|                     |"          |d         d          d<   n|                     |#          |d         d          d<   n|&|d         d*<   d+|d         d#<   |r&|                     |$          |d         d          d<   nW|                     |%          |d         d          d<   n1|d,k    r*|s|rt          | j        d-z             |s|rh|r3|                     |                     ||                    |d         d$<   n|                     |                     ||                    |d         d$<   n|s|s|s| r|&|d         d.<   |sD|s|r@|r|                     |"          |d         d$<   ni|                     |#          |d         d$<   nJ|&|d         d*<   |r|                     |$          |d         d$<   n|                     |%          |d         d$<   |                     |g d/          }||gS )0Nlimitz& limit orders require a price argumentparamslimit_pricemarketFT	post_onlyclientOrderId	cl_ord_idcost	order_qtystopLoss
takeProfittriggerPricer[   stopLossPricetakeProfitPricetrailingAmounttrailingPercenttrailingLimitAmounttrailingLimitPercentoffset pctquoter5   
reduceOnlyreduce_onlytimeInForcetime_in_forcetriggersconditionalz	stop-loss
order_typetrigger_priceztake-profitzstop-loss-limitztake-profit-limit
price_typeztrailing-stoplimit_price_typeztrailing-stop-limitr6   zR editing the stopLoss and takeProfit on existing orders is currently not supportedtrigger_price_type)	rb   rd   ro   ri   rj   rk   rl   rm   rn   )endswithr   idparse_to_numericprice_to_precisionhandle_post_onlysafe_stringcost_to_precision	safe_dictnumber_to_string	safe_boolsafe_string_loweromitr    ))rR   rV   rW   rX   rY   rZ   r[   r^   isLimitOrderisMarketpostOnlyrb   rd   rf   rg   presetStopLosspresetTakeProfitpresetStopLossLimitpresetTakeProfitLimitisPresetStopLossisPresetTakeProfitri   rj   isStopLossPriceOrderisTakeProfitPriceOrderrk   rl   rm   rn   isTrailingAmountOrderisTrailingPercentOrderisTrailingLimitAmountOrderisTrailingLimitPercentOrderro   trailingAmountStringtrailingPercentStringtrailingLimitAmountStringtrailingLimitPercentString	priceTypers   ru   s)                                            rT   order_request_wszkraken.order_request_ws   s	   }}W-- 	m}'2Z(Z[[[/3/D/DTE\E\]cejEkEk/l/lGHm,H$005&II& 	2-1GHk*((AA$-:GHk*//-1-B-B4CYCYZ`bfCgCg-h-hGHk*>>&*b99^^FL"==
))(NCC++JGG"..xAA $ 0 0W E E)5-T9((AA**63DEE,D8!0!<))&2BCC**63DEE"..v7LMM#//8NOO .d :!0!<%8%D"&:$&F#!!&(B77R`Rlv(=(=n(M(MMMswTcTo)>)>)O)O O Ovz\o\{FT-B-BCV-W-W$W$W  CG!^r^~Vd.C.CDX.Y.Y%Y%Y  FJ"4a8SaEEZa	_$$==J 837!-000GGK&5@!/2YYvm'DEEF# 3'= 3AV 3Zp 3  uO 3  Sn 302!*- +s#5 +s35!-0# QEPGH%m4\BHLH]H]^b^u^uv|  M  _N  _N  IO  IOGH%m4_EE' QERGH%m4\BHLH]H]^b^u^uv|  O  _P  _P  IQ  IQGH%m4_E&2EVGH%m4\BFJF[F[\`\s\stz  }P  ]Q  ]Q  GR  GRGH%m4]CC*6EXGH%m4\BFJF[F[\`\s\stz  }R  ]S  ]S  GT  GTGH%m4]C6J+EFF% s)? s' H=A=R=RSWSjSjkq  tA  TB  TB  >C  >CGH%j1':# F:K),77:E),77=A=R=RSWSjSjkq  tC  TD  TD  >E  >EGH%j1':# H:M),77:G),77& s*@ sD^ sb} s>G!*-l;# s)> sBX s6EGH%l3, nAEAVAVWkAlAl)*5g>>AEAVAVWlAmAm)*5g>> =FGH%&896KGH%l31 sAEAVAVWpAqAq)*5g>>AEAVAVWqArAr)*5g>}$$ C#5 C"47  .B  $B  C  C  C# o'= o' A9=9N9NtOfOfgmo|O}O}9~9~GH%o669=9N9NtOfOfgmo~OO  :A  :AGH%o66& o*@ oD^ ob} o:C!"67# 
o)> 
oBX 
o, j=A=R=RSg=h=h)/::=A=R=RSh=i=i)/::<EGH%&891 o=A=R=RSl=m=m)/::=A=R=RSm=n=n)/:6  $  $  $  @  @  rU   sidec           	      .  K   |                                   d{V  |                                  d{V }|                     |          }| j        d         d         d         }	|                                 }
|                     |
          }d|||                     |                     ||                    |d         |d|
d}|                     d	||||||          \  }}| 	                    |	|| 
                    ||          |           d{V S )
a  
        create a trade order

        https://docs.kraken.com/api/docs/websocket-v2/add_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 exchange API endpoint
        :returns dict: an `order structure <https://docs.ccxt.com/?id=order-structure>`
        Nr:   r)   r=   	add_orderrW   )ry   r   re   rW   tokenrV   r^   req_idr5   )load_marketsauthenticater`   rK   
request_idr   r   amount_to_precisionr   watchextend)rR   rW   rX   r   rZ   r[   r^   r   r`   url	requestIdmessageHashrY   s                rT   create_order_wszkraken.create_order_ws  sJ      !!!!!!!!!''))))))))V$$it$[1OO%%	++I66!"!2243K3KFTZ3[3[\\ *   

 

 //wX^`egmnnZZ[$++gv2N2NP[\\\\\\\\\rU   c                     |                      |di           }|                     |          }|                     |dd          }|                    ||           d S )Nresultreqidr   )r   parse_ordersafe_string_2resolve)rR   clientmessager   orderr   s         rT   handle_create_edit_orderzkraken.handle_create_edit_order%  s]    6 266  (((('8DDuk*****rU   r   c           	        K   |                                   d{V  |                                  d{V }| j        d         d         d         }	|                                 }
|                     |
          }d||                     |                     ||                    |d|
d}|                     d||||||          \  }}|                     |	|| 	                    ||          |           d{V S )	a  
        edit a trade order

        https://docs.kraken.com/api/docs/websocket-v2/amend_order

        :param str id: order id
        :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 the currency you want to trade in units of the 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 exchange API endpoint
        :returns dict: an `order structure <https://docs.ccxt.com/?id=order-structure>`
        Nr:   r)   r=   amend_order)order_idre   r   r   r6   )
r   r   rK   r   r   r   r   r   r   r   )rR   r   rW   rX   r   rZ   r[   r^   r   r   r   r   rY   s                rT   edit_order_wszkraken.edit_order_wsE  s.      !!!!!!!!!''))))))))it$[1OO%%	++I66#!2243K3KFTZ3[3[\\ 
  
 
 //vtWV\^cekllZZ[$++gv2N2NP[\\\\\\\\\rU   idsc                   K   |t          | j        dz             |                                  d{V  |                                  d{V }| j        d         d         d         }|                                 }|                     |          }d||d|d}|                     |||                     ||          |           d{V S )	a  
        cancel multiple orders

        https://docs.kraken.com/api/docs/websocket-v2/cancel_order

        :param str[] ids: order ids
        :param str [symbol]: unified market symbol, default is None
        :param dict [params]: extra parameters specific to the exchange API endpoint
        :returns dict: an list of `order structures <https://docs.ccxt.com/?id=order-structure>`
        NzK cancelOrdersWs() does not support cancelling orders for a specific symbol.r:   r)   r=   cancel_orderr   r   r   	r    r   r   r   rK   r   r   r   r   )	rR   r   rW   r^   r   r   r   r   rY   s	            rT   cancel_orders_wszkraken.cancel_orders_wse  s      tw)vvwww!!!!!!!!!''))))))))it$[1OO%%	++I66$   
 
 ZZ[$++gv2N2NP[\\\\\\\\\rU   c                   K   |t          | j        dz             |                                  d{V  |                                  d{V }| j        d         d         d         }|                                 }|                     |          }d|g|d|d}|                     |||                     ||          |           d{V S )	a  
        cancels an open order

        https://docs.kraken.com/api/docs/websocket-v2/cancel_order

        :param str id: order id
        :param str [symbol]: unified symbol of the market the order was made in
        :param dict [params]: extra parameters specific to the exchange API endpoint
        :returns dict: An `order structure <https://docs.ccxt.com/?id=order-structure>`
        NzJ cancelOrderWs() does not support cancelling orders for a specific symbol.r:   r)   r=   r   r   r   r   )	rR   r   rW   r^   r   r   r   r   rY   s	            rT   cancel_order_wszkraken.cancel_order_ws  s      tw)uuvvv!!!!!!!!!''))))))))it$[1OO%%	++I66$D   
 
 ZZ[$++gv2N2NP[\\\\\\\\\rU   c                 ^    |                      |d          }|                    ||           d S Nr   r   r   rR   r   r   reqIds       rT   handle_cancel_orderzkraken.handle_cancel_order  3       (33w&&&&&rU   c                   K   |t          | j        dz             |                                  d{V  |                                  d{V }| j        d         d         d         }|                                 }|                     |          }dd|i|d}|                     |||                     ||          |           d{V S )	a  
        cancel all open orders

        https://docs.kraken.com/api/docs/websocket-v2/cancel_all

        :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 exchange API endpoint
        :returns dict[]: a list of `order structures <https://docs.ccxt.com/?id=order-structure>`
        NzM cancelAllOrdersWs() does not support cancelling orders in a specific market.r:   r)   r=   
cancel_allr   r   r   )rR   rW   r^   r   r   r   r   rY   s           rT   cancel_all_orders_wszkraken.cancel_all_orders_ws  s       tw)xxyyy!!!!!!!!!''))))))))it$[1OO%%	++I66"  
 
 ZZ[$++gv2N2NP[\\\\\\\\\rU   c                 ^    |                      |d          }|                    ||           d S r   r   r   s       rT   handle_cancel_all_orderszkraken.handle_cancel_all_orders  r   rU   c                 t   |                      |dg           }|d         }|                     |d          }|                     dd |          }|                     |d          }d }|                     |d          }	|	|t          j        |	|          }|                     |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          }|| j        |<   |                    ||           d S )Ndatar   rW   tickervwapvolumelast	timestampdatetimehighlowbid	bidVolumebid_qtyask	askVolumeask_qtyopenclosepreviousClosechange
percentage
change_pctaverage)
baseVolumequoteVolumeinfo)	safe_listr   get_message_hashr$   
string_mulsafe_tickertickersr   )rR   r   r   r   r   rW   r   r   r   r   r   r   s               rT   handle_tickerzkraken.handle_ticker  sS   . ~~gvr22a!!&(33++HdFCC//%%fh77
!d&6!,Z>>K//!! #
f#
#
 #
 D$$VV44	#

 4##FE22#
 4##FE22#
 ))&)<<#
 4##FE22#
 ))&)<<#
 D#
 D#
 T#
 D#
 T#
 d&&vx88#
  $**6<@@!#
" t##
$ %&)#
 #
 #
  ,  &Vv{+++++rU   r   c                 :   |                      |dg           }|d         }|                     |d          }|                     dd |          }|                     | j        |          }|5|                     | j        dd          }t          |          }|| j        |<   |                     |          }	| 	                    ||	          }
t          dt          |
                    D ]}|                    |
|                    |                    ||           d S )Nr   r   rW   traderB   r@   )r   r   r   
safe_valuetradessafe_integerrL   r   r`   parse_tradesrangelenappendr   )rR   r   r   r   r   rW   r   storedr]   r`   parsedis               rT   handle_tradeszkraken.handle_trades  s   $ ~~gvr22Q!!%22++GT6BBf55>%%dlM4HHE&&F"(DKV$$""400q#f++&& 	% 	%AMM&)$$$$v{+++++rU   c           
      ,   |                      |dg           }|d         }|                     |d          }|                     |          }|| j        vr
i | j        |<   |                     |d          }|                     |          }|                     dd |          }	|                     | j        |         |          }
|                     | j        |i           | j        |<   |
;|                     | j        dd          }t          |          }
|
| j        |         |<   t          |          }t          d|          D ]}|||z
  dz
           }|                     |d	          }|                     |          }||                     |d
          |                     |d          |                     |d          |                     |d          |                     |d          g}|
                    |           |                    |
|	           d S )Nr   r   rW   intervalohlcvrC   r@      r   r   r   r   r   r   )r   r   safe_symbolohlcvsr   find_timeframer   r   rL   r   r   r   	parse8601r   r   )rR   r   r   r   firstmarketIdrW   r   	timeframer   r   r]   ohlcvsLengthr   candler   r   r   s                     rT   handle_ohlcvzkraken.handle_ohlcv2  s   . ~~gvr22Q##E844!!(++$+%%"$DK$$UJ77''11	++GT6BBV!4i@@"oodk62FFF>%%dlL$GGE*511F-3DK	*4yyq,'' 	" 	"A,*Q./F''<<Hx00I  00  00  //  11  22F MM&!!!!v{+++++rU   c                     |                                   |                     |                     | j        dd          d          }|| j        d<   |                                  |S )Nr   r   r  )lock_idsumr   rL   	unlock_id)rR   r   s     rT   r   zkraken.request_idh  sW    **4<!DDaHH %WrU   c                    K   |                                   d{V  |                     |          }|                     |g|           d{V }||         S )a  
        watches a price ticker, a statistical calculation with the information calculated over the past 24 hours for a specific market

        https://docs.kraken.com/api/docs/websocket-v2/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   rW   watch_tickers)rR   rW   r^   r   s       rT   watch_tickerzkraken.watch_tickerp  sp       !!!!!!!!!V$$**F8V<<<<<<<<vrU   symbolsc                 
  K   |                                   d{V  |                     |dd          }|                     dd|d|           d{V }| j        ri }|||d         <   |S |                     | j        d|          S )a  
        watches a price ticker, a statistical calculation with the information calculated over the past 24 hours for a specific market

        https://docs.kraken.com/api/docs/websocket-v2/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>`
        NFr   rW   )r   market_symbolswatch_multi_helper
newUpdatesfilter_by_arrayr   rR   r  r^   r   r   s        rT   r  zkraken.watch_tickers  s       !!!!!!!!!%%gtU;;..x7DRXYYYYYYYY? 	F'-F6(#$M##DL(GDDDrU   c                   K   |                                   d{V  |                     |dd          }d|d<   |                     dd|d|           d{V }| j        ri }|||d         <   |S |                     | j        d|          S )at  
        watches best bid & ask for symbols

        https://docs.kraken.com/api/docs/websocket-v2/ticker

        :param str[] symbols: 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>`
        NFbboevent_triggerbidaskr   rW   )r   r  r  r  r  bidsasksr  s        rT   watch_bids_askszkraken.watch_bids_asks  s       !!!!!!!!!%%gtU;;"'..x7DRXYYYYYYYY? 	F'-F6(#$M##DM8WEEErU   sincer]   c                 D   K   |                      |g|||           d{V S )a  
        get the list of most recent trades for a particular symbol

        https://docs.kraken.com/api/docs/websocket-v2/trade

        :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rR   rW   r   r]   r^   s        rT   watch_tradeszkraken.watch_trades  s6       22F8UE6RRRRRRRRRrU   c                   K   |                      dd|d|           d{V }| j        rB|                     |d          }|                     |d          }|                    ||          }|                     |||dd          S )a  
        get the list of most recent trades for a list of symbols

        https://docs.kraken.com/api/docs/websocket-v2/trade

        :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>`
        r   Nr   rW   r   T)r  r  r   r   getLimitfilter_by_since_limit)rR   r  r   r]   r^   r   r  tradeSymbols           rT   r"  zkraken.watch_trades_for_symbols  s       ..w$PVWWWWWWWW? 	8NN61--E**5(;;KOOK77E))&%TRRRrU   c                 B   K   |                      |g||           d{V S )a.  
        watches information on open orders with bid(buy) and ask(sell) prices, volumes and other data

        https://docs.kraken.com/api/docs/websocket-v2/book

        :param str symbol: unified symbol of the market to fetch the order book for
        :param int [limit]: the maximum amount of order book entries to return
        :param dict [params]: extra parameters specific to the exchange API endpoint
        :returns dict: A dictionary of `order book structures <https://docs.ccxt.com/?id=order-book-structure>` indexed by market symbols
        N)watch_order_book_for_symbols)rR   rW   r]   r^   s       rT   watch_order_bookzkraken.watch_order_book  s4       66xOOOOOOOOOrU   c           
      
  K   i }|5|                      |g d          r||d<   nt          | j        dz             |                     dd|d|i|                     ||                     d{V }|                                S )a  
        watches information on open orders with bid(buy) and ask(sell) prices, volumes and other data

        https://docs.kraken.com/api/docs/websocket-v2/book

        :param str[] symbols: unified array of symbols
        :param int [limit]: the maximum amount of order book entries to return
        :param dict [params]: extra parameters specific to the exchange API endpoint
        :returns dict: A dictionary of `order book structures <https://docs.ccxt.com/?id=order-book-structure>` indexed by market symbols
        N)
      d   i  r@   depthzF watchOrderBook accepts limit values of 10, 25, 100, 500 and 1000 only	orderbookbookr]   )in_arrayr    r   r  r   r]   )rR   r  r]   r^   requiredParamsr1  s         rT   r*  z#kraken.watch_order_book_for_symbols  s        "}}U$<$<$<== w*/w''"47-u#uvvv11+vwQXZ_P`bfbmbmn|  E  cF  cF  G  G  G  G  G  G  G  G	   rU   1mr  c                   K   |                                   d{V  d}|                     |          }|d         }| j        d         d         d         }|                                 }	|                     dd|          }
d||g|                     | j        ||          d	|	d
}|                     ||          }|                     ||
||
           d{V }| j	        r|
                    ||          }|                     |||dd          S )a  
        watches historical candlestick data containing the open, high, low, and close price, and the volume of a market

        https://docs.kraken.com/api/docs/websocket-v2/ohlc

        :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
        NohlcrW   r:   r)   r>   r   	subscribe)channelrW   r   r   r   T)r   r`   rK   r   r   r   
timeframesrO   r   r  r&  r'  )rR   rW   r  r   r]   r^   namer`   r   r   r   r8  rY   r   s                 rT   watch_ohlcvzkraken.watch_ohlcv  s<      !!!!!!!!!V$$!it$Z0OO%%	++GT6BB!!( OODOY	RR 
  
 
	 ""9f55jjk7KHHHHHHHH? 	2NN6511E))%{DQQQrU   Fc                   K   t          t          |                               ||           d {V }|                     | j        d          }||r}i }t          dt          | j                            D ]N}| j        |         }| j        |         }|                     |di           }| 	                    |d          }	|||	<   O|| j        d<   |S )NmarketsByWsNamer   r   wsname)
rP   r&   r   r   rL   r   r   r  marketsr   )rR   reloadr^   r@  r>  r   rW   r`   r   wsNamerS   s             rT   r   zkraken.load_markets  s      fd++88HHHHHHHH//$,8IJJ## O1c$,//00 1 1af-vvr::))$99*0''.=DL*+rU   c                 `    |j         }i }|                    d          dk    rd|d<   nd|d<   |S )Nv2r   rF   rV   event)r   find)rR   r   r   rY   s       rT   rF   zkraken.ping  s?    j88D>>Q &GH%GGrU   c                 8    |                                  |_        |S N)millisecondslastPongrR   r   r   s      rT   handle_pongzkraken.handle_pong"  s    ++--rU   c                    K   |                                   d {V  d}| j        d         d         d         }|                     ||           d {V S )N	heartbeatr:   r)   r>   )r   rK   r   )rR   r^   rE  r   s       rT   watch_heartbeatzkraken.watch_heartbeat&  sk      !!!!!!!!!it$Z0ZZU+++++++++rU   c                 ^    |                      |d          }|                    ||           d S )Nr9  r   )rR   r   r   rE  s       rT   handle_heartbeatzkraken.handle_heartbeat,  s3       )44w&&&&&rU   c                    |                      |d          }|                     |dg           }|                     |di           }|                      |d          }|                     |dg           }|                     |dg           }|                     |d          }	|                     dd |          }
d }|d	k    r| j        |         }|d         }|d         }||                     ||           ||                     ||           |                      |d
          }||d<   |                     |          |d
<   ||d<   nt          |          }| 
                    i |          | j        |<   | j        |         }ddg}t          dt          |                    D ]R}||         }||         }|                     ||g           }t          |          dk    r|                     ||           S||d<   |                                 |                     ddd          }|rg }|	|d         }|d         }t          dd          D ]e}|                     ||i           }|                     |d                   |                     |d                   z   }|                    |           ft          dd          D ]e}|                     ||i           }|                     |d                   |                     |d                   z   }|                    |           fd                    |          }|                     |d          }||	k    rUt%          | j        dz   |                     |          z             }|j        |
= | j        |= |                    ||
           d S |                    ||
           d S )NrX   r   r   rW   asksbidsrA   r1  updater   r   r-   Fr-  r  rp    )r   r   r   r   r   r   
orderbookscustom_handle_deltasr  r   
order_bookr   r]   handle_optionformat_numberr   joincrc32r#   r   orderbook_checksum_messagesubscriptionsrejectr   ) rR   r   r   rX   r   r  rW   abcr   r1  
storedAsks
storedBidsr   r0  keysr   keybooksidedeltasrA   payloadArray	checkAsks	checkBids
currentAskformattedAsk
currentBidformattedBidpayloadlocalChecksumerrors                                    rT   handle_order_bookzkraken.handle_order_book5  s   p 00~~gvr22tQ++!!%22OOE62..OOE62..eZ00++KvFF	8/I"6*J"6*J}))*a888}))*a888''{;;H"(Ih%)^^H%=%=Ik"$,Ij!! FFE&*oob%&@&@DOF#/IF#D1c$ii(( @ @1g$S>R88v;;??--h???"(Ih%%&6
EJJ 	L}%f-	%f-	 q" 6 6A!%Ar!B!BJ#'#5#5jm#D#DtGYGYZdefZgGhGh#hL ''5555q" 6 6A!%Ar!B!BJ#'#5#5jm#D#DtGYGYZdefZgGhGh#hL ''5555ggl++G JJw66M!!%dgmd6U6UV\6]6]&]^^(5OF+e[111y+.....rU   c                     t          dt          |                    D ]L}||         }|                     |d          }|                     |d          }|                    ||           Md S )Nr   r[   qty)r   r   safe_numberstore)rR   rh  ri  jdeltar[   rZ   s          rT   rX  zkraken.custom_handle_deltas  su    q#f++&& 	* 	*A1IE$$UG44E%%eU33FNN5&))))		* 	*rU   c                     |                     d          }|                     |d          }|                     |dd          }||z   }d}||         dk    r|dz  }||         dk    |dk    r
||d          }|S )N.r   r  rp   0)splitr   )rR   r   partsintegerdecimalsjoinedResultr   s          rT   r[  zkraken.format_number  s    

3""5!,,##E1b11)1o$$FA 1o$$q55'+LrU   c                     |S rH   rK  s      rT   handle_system_statuszkraken.handle_system_status  s	    6 rU   c                   K   | j         d         d         d         }|                     |          }d}|                     |j        |          }|                                 }|                     |d          }|                     |d          }||I||z   |k    r@|                     |           d {V }	|                     |	d          }||d<   ||j        |<   |                     |d          S )	Nr:   r)   r<   authenticatedstartexpiresr   r   )	rK   r   r   r_  secondsr   privatePostGetWebSocketsTokenr   r   )
rR   r^   r   r   r  subscriptionnowr  r  responses
             rT   r   zkraken.authenticate  s      it$Y/S!!'v';]KKllnn!!,88##L)<< |'?egoZ]E]E]!??GGGGGGGGH  >>(H==L$'L!2>F /g666rU   c                   K   |                                   d {V  |                                  d {V }d}|}||                     |          }|d|z   z  }| j        d         d         d         }	|                                 }
dd|d|
d}||                     |d	         |          |d	<   |                     |	|||           d {V }| j        r|                    ||          }| 	                    ||||          S )
N
executions:r:   r)   r=   r8  r9  r   r   r^   )
r   r   rW   rK   r   rO   r   r  r&  filter_by_symbol_since_limit)rR   r;  rW   r   r]   r^   r   subscriptionHashr   r   r   r8  r   s                rT   watch_privatezkraken.watch_private  sN     !!!!!!!!!''))))))))'[[((F3<'Kit$[1OO%%	!'   
 
	 "&"2"29X3F"O"OIhzz#{I?OPPPPPPPP? 	3OOFE22E00NNNrU   c                 N   K   d|d<   |                      d||||           d{V S )a-  
        watches information on multiple trades made by the user

        https://docs.kraken.com/api/docs/websocket-v2/executions

        :param str symbol: unified market symbol of the market trades were made in
        :param int [since]: the earliest time in ms to fetch trades for
        :param int [limit]: the maximum number of trade structures to retrieve
        :param dict [params]: extra parameters specific to the exchange API endpoint
        :returns dict[]: a list of `trade structures <https://docs.ccxt.com/?id=trade-structure>`
        Tsnap_tradesmyTradesN)r  r#  s        rT   watch_my_tradeszkraken.watch_my_trades  s@       !%}''
FE5&QQQQQQQQQrU   c                    |                      |dg           }t          |          }|dk    r5| j        0|                     | j        dd          }t          |          | _        | j        }i }t          dt          |                    D ]P}	|                     ||	i           }
|                     |
          }|	                    |           |d         }d||<   Qd}|
                    | j        |           t          |                                          }t          dt          |                    D ]-}	|dz   ||	         z   }|
                    | j        |           ,d S d S )	Nr   r   rB   r@   rW   Tr  r  )r   r   r  r   rL   r   r   r   parse_ws_trader   r   listrf  )rR   r   r   r  	allTradesallTradesLengthr]   r   r  r   r   r   rW   r;  rf  r   s                   rT   handle_my_tradeszkraken.handle_my_trades%  sf   @ NN7FB77	i..Q}$))$,tLL *5 1 1]FG1c)nn-- ' 'y!R88,,U33f%%%)"&DNN4=$///''D1c$ii(( ; ;"Sj472t}k::::# ; ;rU   c                    |                      |d          }||d         }d }d|v r[|                     |dg           }|                     |di           }|                     |d          |                      |d          d}|                      |d          }|                      |d          }|d	k    rd
nd}	||                      |d          |                      |d          |                     |          |||                      |d          |                      |d          |	|                     |d          |                     |d          |                     |d          |dS )NrW   feesr   rv  assetrd   currencyr   liquidity_indttakermakerexec_idr   ry   r   
last_pricelast_qtyrd   )r   r   r   r   r   rW   rX   r   takerOrMakerr[   rZ   rd   fee)r   r   r   rw  r  )
rR   r   r`   rW   r  r  firstFeer   liquidityIndicatorr  s
             rT   r  zkraken.parse_ws_tradeZ  s   2 !!%22H%FU??>>%44D~~dAr22H((599 ,,Xw?? C ##E;77!--e_EE#5#<#<ww7""5)44%%eZ8811 $$UL99$$UF33(%%e\::&&uj99$$UF33
 
 	
rU   c                 p   K   |                      d||||                     |ddi                     d{V S )a-  
        watches information on multiple orders made by the user

        https://docs.kraken.com/api/docs/websocket-v2/executions

        :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  orde structures to retrieve
        :param dict [params]: maximum number of orderic to the exchange API endpoint
        :returns dict[]: a list of `order structures <https://docs.ccxt.com/?id=order-structure>`
        orderssnap_ordersTN)r  r   r#  s        rT   watch_orderszkraken.watch_orders  sL       ''&%TZ]jlp\qHrHrsssssssssrU   c                    |                      |dg           }t          |          }|dk    r|                     | j        dd          }| j        t          |          | _        | j        }i }t          dt          |                    D ]1}	|                     ||	i           }
|                     |
d          }| 	                    |
          }|                     |
d          }| 
                    |j        |          }| 
                    ||          }|}|7|                     |d         |d                   }| 	                    |          }t          |          }||k    r9|7|d         }| 
                    | j        di           }|d	         |v r	||d	         = |                    |           |d
||<   3d}|                    | j        |           t          |                                          }t          dt          |                    D ]-}	|dz   ||	         z   }|                    | j        |           ,d S d S )Nr   r   rD   r@   r   rW   r   rE   r   Tr  r  )r   r   r   rL   r  r   r   r   r   parse_ws_orderr   hashmapr   r   r   r  rf  )rR   r   r   r  	allOrdersallOrdersLengthr]   r   r  r   r   r   r   rW   previousOrderspreviousOrdernewOrdernewRawOrderlengthr  rE   r;  rf  r   s                           rT   handle_orderszkraken.handle_orders  sE   8 NN7FB77	i..Q%%dlM4HHE{"4U;;[FG1c)nn-- + +y!R88%%eZ88,,U33))%::!%!H!H $ C C! ,"&++mF.CXfEU"V"VK#22;??HVU??(="1IE'+t|EWY['\'\$T{&666,U4[9h'''%&*GFODNN4;---''D1c$ii(( 9 9"Sj472t{K8888? :9 9rU   c           
      2   |                      |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 d|                      |d          d|                      |d          d|d|d|                      |d          d|                     |dd          d |                      |d          d |d d           S )!Nfee_usd_equivUSDr  
stop_pricer   r   r   rb   order_userrefr   r   lastTradeTimestampstatusorder_statusrW   rX   ry   ru   rv   r   r   r[   r_   	stopPricerh   rd   cum_costrZ   re   cum_qty	avg_price)filledr   	remainingr  r   )r   
safe_orderr  parse_order_statusr   )rR   r   r`   r  r  r   s         rT   r  zkraken.parse_ws_order  s"   R $$UO<<
 
 $$UL99	##E;77  
$""5*55 
T--e_EE 
 E 
 11	 

  
 !$ 
 d--d.>.>un.U.UVV 
 d&&uh77 
 D$$UL99 
 4++E?CC 
  
 D$$UF33 
 T%%e];; 
  
 I 
  D$$UJ77! 
" d((YGG# 
$ ''{;;- 
  
  
   	rU   unifiedNamechannelNamec                   K   |                                   d {V  |                     |d ddd          }g }t          dt          |                    D ]}|                     |d          }|D|                    |                     |d |                     ||                                        ^|                    |                     |d |                     ||                                        d||d|                                 d}	| 	                    |	d         |          |	d<   | j
        d	         d
         d         }
|                     |
||	||           d {V S )NFTr   r  r8  )r9  rW   r   r^   r:   r)   r>   )r   r  r   r   r   r   r   rW   r   rO   rK   watch_multiple)rR   r  r  r  subscriptionArgsr^   messageHashesr   eventTriggerrY   r   s              rT   r  zkraken.watch_multi_helper%  s     !!!!!!!!!%%gtUD%HHq#g,,'' 	h 	hA++FODDL'$$T%:%:;dkkZabcZdNeNe%f%fgggg$$T%:%:;dkkZabcZdNeNe%f%fgggg!&!  oo''
 
 !,,WX->GGit$Z0((mWmUefffffffffrU   c                 F  K   |                                   d{V  |                                  d{V }d}| j        d         d         d         }|                                 }d|d|dd}|                     ||          }|                     ||||           d{V S )	a\  
        watch balance and get the amount of funds available for trading or funds locked in orders

        https://docs.kraken.com/api/docs/websocket-v2/balances

        :param dict [params]: extra parameters specific to the exchange API endpoint
        :returns dict: a `balance structure <https://docs.ccxt.com/?id=balance-structure>`
        Nbalancesr:   r)   r=   r8  r  )rV   r   r^   )r   r   rK   r   rO   r   )rR   r^   r   r   r   r   r8  rY   s           rT   watch_balancezkraken.watch_balance<  s       !!!!!!!!!'')))))))) it$[1OO%%	!% 
 
	 ""9f55ZZ[';GGGGGGGGGrU   c                    |                      |dg           }d|i}t          dt          |                    D ]m}|                     ||         d          }|                     |          }|                                 }|                     ||         d          }	|	|d<   |||<   nd}
|                     |          }|                     | j        |
i           }| 	                    ||          }|                     |          | j        |
<   |                     |d          }|
                    | j        |
         |           d S )	Nr   r   r   r  balancetotalspotr9  )r   r   r   r   safe_currency_codeaccountsafe_balancer   r  rO   r   )rR   r   r   r   r   r   
currencyIdcoder  eqrX   r  
oldBalance
newBalancer9  s                  rT   handle_balancezkraken.handle_balanceU  s=   , ~~gvr22(q#d))$$ 	# 	#A))$q'7;;J**:66DllnnG!!$q'955B!GG"F4LL##F++__T\4<<
%%j'::
!..z::T""7I66t|D)733333rU   unifiedElementNamesubChannelNamec                 F    |d u}|}|s|dz  }n|d|z   z  }||d|z   z  }|S )Ns@#r  )rR   r  r  rW   
withSymbolr   s         rT   r   zkraken.get_message_hash|  sP     4'
( 	(3KK3<'K%3//KrU   c                 N    |                      |d          }|||j        |<   d S d S )N	channelID)r   r_  )rR   r   r   	channelIds       rT   handle_subscription_statusz!kraken.handle_subscription_status  s:    0 $$Wk::	 .5F +++ ! rU   c                 6   |                      |dd          }||                      |dd          }| j        d         d         }|                     ||          }d }|t          |          }n ||         |          }||                    ||           dS dS )	NerrorMessagers  r   r   r)   rI   FT)r   rN   find_broadly_matched_keyr   r`  )rR   r   r   r  r   rI   broadKey	exceptions           rT   handle_error_messagezkraken.handle_error_message  s    ( ))'>7KK#**7GXFFIOD)'2E44ULIIHI),77		+E(OL99	$i3335trU   c           	         |                      |d          }||dk    rN|                     |dg           }|                     |di           }|                      |d          }|dk    rdnd}| j        | j        | j        | j        | j        | j        | j	        d	}| 
                    ||          }| |||           |                     ||          rp|                     |d
d          }	| j        | j        | j        | j        | j        | j        | j        | j        d}| 
                    ||	          }| |||           d S d S d S )Nr9  r  r   r   	exec_typer   r  r  )r  r2  r7  r   r   r  r  rE  rV   )rN  systemStatussubscriptionStatusr   r   r   r   pong)r   r   r   r  rt  r  r   r   r  r  r   r  r   rQ  r  r  r   r   r   rL  )
rR   r   r   r9  r   r  execTypemethodsrV   rE  s
             rT   handle_messagezkraken.handle_message  s   ""7I66,&&~~gvr::tQ33++E;??)1W)<)<**8 /.),+ 1,	 	G __Wg66F!vw'''$$VW55 	(&&wBBE!2 $ 9&*&E!:#< $ 8";(	 	G __We44F!vw'''''	( 	( "!rU   rH  )NN)F__name__
__module____qualname__r   rQ   strdictr
   r   r   r   floatr   r   r   r   r   r   r   r   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   rL  rO  rQ  rt  rX  r[  r  r   r  r  r  r  r  r  r  r  r   r  r  r   r  r   r  r  __classcell__)rS   s   @rT   r&   r&      sF       j# j j j j j jX nrz| w! w!s w!C w!s w!T w![^ w!gj w! w! w! w!r pt|~  ]  ]C  ]y  ]	  ][`  ]il  ]  DI  ]  ]  ]  ]D+ + +@ im{  IK ] ]c ]3 ]i ]y ]be ]ux ]  PU ] ] ] ]@ DHPR ] ]$s) ]S ] ] ] ]8 <@ ] ] ]S ]u ] ] ] ]8' ' '  8<B ] ] ]4PU; ] ] ] ]4' ' ' 8, 8, 8,t,F , , , ,B4,6 4, 4, 4, 4,l   68   F     6:" E E7 E E E E E& 8<B F FW F7 F F F F( <@d[] S S SS S Sbfglbm S S S S OSaenp S Sd3i S S[^ Suyz  vA S S S S& @DB P PS P PS\ P P P P SW_a ! !$s) !C !fo ! ! ! !( ?CQUdhqs !R !R !R !R3 !R^a !Rx|  ~B  yC !R !R !R !RF ).b      6    &     ,. , , , ,'v ' ' ' 't/ t/ t/ t/ t/l* * * 
 
 
6    : )+ 7 7 7 72 7;\`ik O O O3 OVY O O O O2 37TX\eg R RC Rs RRU Rlpqvlw R R R R3; 3;v 3; 3; 3; 3;j5
 5
 5
 5
n 04$UYbd t t tC ts timnsit t t t t=9 =9F =9 =9 =9 =9~E E E EN _cuy  CE g gC gc gT[ g g g g. *, H H H H H H2%4V %4 %4 %4 %4N 3  \_    6 6 6 6 6@!6 !t ! ! ! !F#(V #( #( #( #( #( #( #( #(rU   r&   ),ccxt.async_supportccxt ccxt.async_support.base.ws.cacher   r   r   ccxt.base.typesr   r   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   r   r   r   r   r   r   r    r!   r"   r#   ccxt.base.preciser$   async_supportr&   r  rU   rT   <module>r     sg       f f f f f f f f f f H  H  H  H  H  H  H  H  H  H  H  H  H  H  H  H  H  H  H  H  H  H  H  H  H  H  H  H  H  H  H  H 4 4 4 4 4 4       * * * * * * 0 0 0 0 0 0 - - - - - - - - - - - - . . . . . . ' ' ' ' ' ' & & & & & & . . . . . . ) ) ) ) ) ) * * * * * * ) ) ) ) ) ) . . . . . . 1 1 1 1 1 1 * * * * * * % % % % % %S( S( S( S( S(T& S( S( S( S( S(rU   