
    !:hxD                       d dl mZ d dl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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/ d dlm0Z0 d dlm1Z1 d dl2m3Z3 d dl2m4Z4 d dl5m6Z6  G d dee      Z7y)    )Exchange)ImplicitAPIN)AnyBalances
CurrenciesCurrencyDepositAddress	IndexTypeIntLedgerEntryMarketNumOrder	OrderBook	OrderSide	OrderTypePositionStrStringsTickerTickersTradeTradingFeeInterfaceTransactionTransferEntry)List)ExchangeError)AuthenticationError)PermissionDenied)AccountSuspended)ArgumentsRequired)
BadRequest)	BadSymbol)InsufficientFunds)InvalidAddress)InvalidOrder)OrderNotFound)NotSupported)DDoSProtection)RateLimitExceeded)ExchangeNotAvailable)OnMaintenance)InvalidNonce)CancelPending)TRUNCATE)	TICK_SIZE)Precisec                       e Zd Zdef fdZd Zi fdee   fdZdmde	f fdZ
d Zi fd	Zi fdefd
Zdmdede	def fdZi fdedefdZd ZdndededefdZdi fdededefdZdmdededefdZdi fdedefdZi fdedefdZ dmdede!fdZ"dddi fdedededee!   fdZ#d  Z$dmd!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i fd#efd%Z(di fd&ed#ede%fd'Z)dmd(edede*fd)Z+ddi fdedededee*   fd*Z,de-fd+Z.i fde-fd,Z/i fded-e0d.e1fd/Z2i fded.e1fd0Z3di fded1e4d-e0d2e1d3e5f
d4Z6d5 Z7d6 Z8d7efd8Z9d9 Z:dmd:edede;fd;Z<di fd<eded1ed=ed2e5d3e5fd>Z=ddi fd&eded1e4d-e0d2e5d3e5fd?Z>di fd&edefd@Z?dddi fd&edededefdAZ@di fdefdBZAdddi fdededefdCZBdi fd&edefdDZCdi fdefdEZDdi fdefdFZEi fdGefdHZFdddi fdedededee;   fdIZGdddi fdedededee;   fdJZHd7efdKZIdL ZJdmdMede	deKfdNZLdod#ededefdOZMdddi fd#edededeeK   fdPZNi fdefdQZOdddi fd#edededeeK   fdRZPdS ZQi fd#edeRfdTZSi fd#efdUZTi fd#edeRfdVZUdmde	deRfdWZVdi fd#ed2e1dXedeKfdYZWdi fdedeeX   fdZZYdmd[edefd\ZZd] Z[i fd#efd^Z\i fd#ed2e1d_ed`ede]f
daZ^dmdbede	de]fdcZ_dddei ddfdfZ`dg Zad#ebdhedied<edjedkefdlZc xZdS )pkrakenreturnc                    | j                  t        t        |          i ddddddgddd	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ddddddddd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*dd+dd,dd-dd.dd/dd0dd1di d2dd3dd4dd5dd6dd7dd8dd9dd:dd;dd<dd=dd>dd?dd@ddAddBdi dCddDdEdFddGddHddIddJddKddLddMddNddOddPddQddRddSddTdUdVdWdXdYdZd[d\d]d^	d_d`dadadbdcdddedfdgdhdidd| j	                  dj      | j	                  dk      | j	                  d      | j	                  dj      g| j	                  dl      | j	                  dm      g| j	                  dn      | j	                  do      g| j	                  dp      | j	                  dq      g| j	                  dr      | j	                  ds      g| j	                  dt      | j	                  dk      g| j	                  du      | j	                  dv      g| j	                  dw      | j	                  dx      g| j	                  dy      | j	                  dz      gg	| j	                  d      | j	                  dk      g| j	                  dl      | j	                  dv      g| j	                  dn      | j	                  dx      g| j	                  dp      | j	                  d{      g| j	                  dr      | j	                  d|      g| j	                  dt      | j	                  d}      g| j	                  du      | j	                  d~      g| j	                  dw      | j	                  d      g| j	                  dy      | j	                  d      gg	ddiddddddgiddUdUdddUdUdUdUdd	idi ddddddddddddddddddddddddddddddddddi dddddddddddddddddddddddddddddddddddddddddddd	idddddddddddddi i g ddddi ddddÓddēddƓddȓddʓdd̓ddΓddГddғddԓddՓddדddٓddۓddܓddޓi dddddddddddddddddddddddddddddddddd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i ddd d!d"d#d$d$d%d&d'd'd(d(d)d*d+d+d,d-d.d/d0d1d2d3d4d5d6d6d7d8d9d:i d;d<dd=ddd>d?d@dAdBdCdDdEdFdGdHdIdJdKdLdMdNdOdPdQdRdRdSdSdTdUdVdWdXdYdZd[d\d]d^d_d`da	i dbdbdddcdddddddedfdgddhdidjddkdidldldmdndoddpdqd[drdQddEdDi dddd֓dsdēdtd6dud]dd˓dvd'dAd@dddXdwdxdddœdyddzdiddd
d	ddi ddddd{d|ddd}d~dddd%ddBdd4ddؓdddddddd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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dd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 dddddʜdːdid͜	d d dΜd d dΜdϜdt
        di dt        dt        dt        dt        dt        dt        dt        dt        dt        dt        dt        dt        dt        dt        dt        dt        dt        t        t        t        t        t        t        t         t        t"        d	t        t        t        t        t        t$        t&        ddi      S (  Nidr3   nameKraken	countriesUSversion0	rateLimit  	certifiedFproThasCORSspotmarginswapfutureoption	addMargincancelAllOrderscancelAllOrdersAftercancelOrdercancelOrderscreateDepositAddresscreateMarketBuyOrderWithCostcreateMarketOrderWithCostcreateMarketSellOrderWithCostcreateOrdercreateStopLimitOrdercreateStopMarketOrdercreateStopOrdercreateTrailingAmountOrdercreateTrailingPercentOrder	editOrderfetchBalancefetchBorrowInterestfetchBorrowRateHistoriesfetchBorrowRateHistoryfetchClosedOrdersfetchCrossBorrowRatefetchCrossBorrowRatesfetchCurrenciesfetchDepositAddressfetchDepositAddressesfetchDepositAddressesByNetworkfetchDepositsfetchFundingHistoryfetchFundingRatefetchFundingRateHistoryfetchFundingRatesfetchIndexOHLCVfetchIsolatedBorrowRatefetchIsolatedBorrowRatesfetchLedgerfetchLedgerEntryfetchLeverageTiersfetchMarketsfetchMarkOHLCVfetchMyTrades
fetchOHLCVfetchOpenInterestHistoryfetchOpenOrders
fetchOrderfetchOrderBookfetchOrderTradesemulatedfetchPositionsfetchPremiumIndexOHLCVfetchStatusfetchTickerfetchTickers	fetchTimefetchTradesfetchTradingFeefetchTradingFeesfetchWithdrawalssetLeveragesetMarginModetransferwithdraw
timeframes            <      i  i`'  i`T  )	1m5m15m30m1h4h1d1w2wurlszdhttps://user-images.githubusercontent.com/51840849/76173629-fc67fb00-61b1-11ea-84fe-f2de582f58a3.jpgzhttps://api.kraken.comz<https://kraken.zendesk.com/api/v2/help_center/en-us/articles)publicprivatezendeskzhttps://www.kraken.comzhttps://docs.kraken.com/rest/z2https://www.kraken.com/en-us/features/fee-schedule)logoapiwwwdocfeesr   tradingz0.0026z0.001650000z0.0024100000z0.0022250000z0.0020500000z0.001810000002500000z0.00145000000z0.001210000000z0.0001z0.0010z0.0008z0.0006z0.0004z0.0002z0.0)takermaker)	tierBased
percentager   r   tiershandleContentTypeApplicationZipr   get360000292886	201893608g333333?)	Assets
AssetPairsDepthOHLCSpreadSystemStatusr   TimeTradespostAddOrderr   AddOrderBatch	AddExport   
AmendOrderBalance	CancelAllCancelAllOrdersAfterCancelOrderCancelOrderBatchClosedOrdersDepositAddressesDepositMethodsDepositStatus	EditOrderExportStatusGetWebSocketsTokenLedgers   
OpenOrdersOpenPositionsQueryLedgersQueryOrdersQueryTradesRetrieveExportRemoveExport	BalanceExTradeBalanceTradesHistoryTradeVolumeWithdrawWithdrawCancelWithdrawInfoWithdrawMethodsWithdrawAddressesWithdrawStatus)	WalletTransferCreateSubaccountAccountTransferzEarn/AllocatezEarn/DeallocatezEarn/AllocateStatuszEarn/DeallocateStatuszEarn/StrategieszEarn/Allocations)r   r   r   commonCurrenciesLUNCLUNAREPREPV1USTCBTCDOGE)r   LUNA2REPV2r   USTXBTXDGoptions)CADUSDJPYGBPERC20TRC20)ETHTRX1INCHz1inch (1INCH)AAVEAaveADAALGOAlgorandANKRzANKR (ANKR)ANTzAragon (ANT)ATOMCosmosAXSzAxie Infinity Shards (AXS)BADGERzBager DAO (BADGER)BALzBalancer (BAL)BANDzBand Protocol (BAND)BATBCHzBitcoin CashBNCzBifrost (BNC)BNTzBancor (BNT)BitcoinCHZzChiliz (CHZ)COMPzCompound (COMP)CQTz	Covalent Query Token (CQT)CRVzCurve DAO Token (CRV)CTSIzCartesi (CTSI)DAIDaiDASHDashDogecoinDOTPolkadotDYDXzdYdX (DYDX)ENJzEnjin Coin (ENJ)EOSETCzEther Classic (Hex)r   zEther (Hex)EWTzEnergy Web TokenFEEzKraken Fee CreditFILFilecoinFLOWFlowGHSTzAavegotchi (GHST)GNOGRTICXIconINJzInjective Protocol (INJ)KARzKarura (KAR)KAVAKavaKEEPzKeep Token (KEEP)KNCzKyber Network (KNC)KSMKusamaLINKLinkLPTzLivepeer Token (LPT)LRCzLoopring (LRC)LSKLiskLTCLitecoinMANAMATICzPolygon (MATIC)MINAMinaMIRzMirror Protocol (MIR)MKRzMaker (MKR)MLNMOVRzMoonriver (MOVR)NANOOCEANOGNzOrigin Protocol (OGN)OMGOXTzOrchid (OXT)OXYzOxygen (OXY)PAXGz
PAX (Gold)PERPzPerpetual Protocol (PERP)PHAzPhala (PHA)QTUMRARIzRarible (RARI)RAYzRaydium (RAY)RENzRen Protocol (REN)REPv2SANDzThe Sandbox (SAND)SCSiacoinSDNzShiden (SDN)SOLSolanaSNXzSynthetix  Network (SNX)SRMSerumSTORJzStorj (STORJ)SUSHIzSushiswap (SUSHI)TBTCtBTCr   TronUNIUSDCUSDTzTether USD (ERC20)z
USDT-TRC20zTether USD (TRC20)WaveszWrapped Bitcoin (WBTC)zStellar XLMMoneroz
Ripple XRPXTZYFIzZcash (Transparent)z0x (ZRX))	WAVESWBTCXLMXMRXRPr^  r_  ZECZRX	LightningRipplerd  Stellarrb  EthereumzArbitrum OneArbitrumPolygonzArbitrum NovaOptimismz
zkSync ErazkSynczEthereum ClassicZcashre  rc  CardanoQtumTezosNanor`  ICONzPolygon - USDC.ezArbitrum One - USDC.ez
Energy WebEW
CentrifugeCFGKarura	MoonriverShidenKhalazBifrost KusamaSongbirdSGBzTerra classicKILTBasiliskBSXFlareFLRzAvalanche C-ChainAVAXKintsugiKINTAltairAIRMoonbeamGLMRAcalaACAAstarASTRAkashAKT
RobonomicsXRTFantomFTMElrondEGLD	THORchainRUNESecretSCRTNearNEARzInternet Computer ProtocolICPPicassoPICAzCrust ShadowCSM
IntegriteeTEERzParallel FinancePARAHydraDXHDXINTRFETNYMr   JUNONODLSTXETHWAPTSUIGENSAVTSEIOTPTIA)InterlayzFetch.air  z	Terra 2.0JunoNodleStackszEthereum PoWAptosSuiGenshiroAventusSeiOriginTrailCelestia)timeDifferenceadjustForTimeDifferencemarketsByAltnamedelistedMarketsByIdinactiveCurrenciesnetworksdepositMethodswithdrawMethodsfeatures)IOCFOKPOGTD)
marginModetriggerPricetriggerPriceTypetriggerDirectionstopLossPricetakeProfitPriceattachedStopLossTakeProfittimeInForcehedgedtrailingleveragemarketBuyByCostmarketBuyRequiresPriceselfTradePreventioniceberg)r  limitdaysBack	untilDayssymbolRequired)r  triggerr  r  )r  r  r  r  r  i )r  r  r  daysBackCanceledr  r  r  r  r    )	sandboxrQ   createOrdersrp   rt   rs   fetchOrdersr\   rq   )linearinverserC   rE   rF   precisionMode
exceptionszEQuery:Invalid asset pairzEAPI:Invalid keyzEFunding:Unknown withdraw keyzEFunding:Invalid amountzEService:UnavailablezEDatabase:Internal errorzEService:BusyzEQuery:Unknown assetzEAPI:Rate limit exceededzEOrder:Rate limit exceededzEGeneral:Internal errorzEGeneral:Temporary lockoutzEGeneral:Permission deniedz EGeneral:Invalid arguments:priceEOrder:Unknown orderz+EOrder:Invalid price:Invalid price argumentzEOrder:Order minimum not met)	zEOrder:Insufficient fundszEGeneral:Invalid argumentszESession:Invalid sessionzEAPI:Invalid noncezEFunding:No funding methodzEFunding:Unknown assetz!EService:Market in post_only modezEGeneral:Too many requestszETrade:User Locked)z:Invalid orderz:Invalid arguments:volumez:Invalid arguments:viqcz:Invalid noncez:IInsufficient fundsz:Cancel pendingz:Rate limit exceeded)exactbroad)deep_extendsuperr3   describeparse_numberr0   r#   r   r%   r$   r+   r)   r   r&   r"   r-   r,   r    r.   r*   )self	__class__s    E/var/www/html/turnos/venv/lib/python3.12/site-packages/ccxt/kraken.pyr  zkraken.describe$   s   fd < > IA
(IA
HIA
 $IA
 s	IA
 IA
 IA
 4IA
  DDD $D 	D
 %D %D UD "4D 'D tD D 'D /D ,UD 0D  t!D" '#D$ (%D& "4'D( ,T)D* -d+D, T-D. /D0 &u1D2 +E3D4 )%5D6 $T7D8 '9D: (;D< "4=D> &t?D@ (ADB 1%CDD  EDF &uGDH #EIDJ *5KDL $UMDN "5ODP *5QDR +ESDT tUDV #DWDX %eYDZ [D\ !%]D^  _D` daDb +EcDd "4eDf dgDh !$iDj #JkDl !$mDn )%oDp tqDr tsDt uDv TwDx tyDz "4{D| #E}D~ #DD@ uADB  CDD DEDF DGDIA
` 
aIA
v ~67]
 06L
wIA
L !%"&!..x8!..x8 "..s3T5F5Fx5PQ!..w79J9J89TU!..x8$:K:KH:UV!..x8$:K:KH:UV!..x8$:K:KH:UV!..y94;L;LX;VW!..y94;L;LX;VW!..y94;L;LX;VW!..z:D<M<Mh<WX
" "..s3T5F5Fx5PQ!..w79J9J89TU!..x8$:K:KH:UV!..x8$:K:KH:UV!..x8$:K:KH:UV!..y94;L;LX;VW!..y94;L;LX;VW!..y94;L;LX;VW!..z:D<M<Me<TU
"MIA
L .tMIA
N  '#	 "#&'!$ #"#()"# !"%  ."A.'. $Q. %a	.
 "1. $Q. /. &q. +A. '. +A. )!. (. $Q. '.  -a!." "1#.$ %a%.& ('.( ').* &q+., &q-.. )!/.0 '1.2 $Q3.4 '5.6 (7.8 &q9.: #A;.< )!=.> '?.@ *1A.B ,QC.D )!E.F +,,-+,)*+,/012+,,-[.0/HOIA
` 	!aIA
t "#+0$&')&B""_#6_#F_# 5_# J	_#
 3_# 3_# H_# A_# <_# 5_# <_# 5_# >_# 4_# 3_#  9!_#" 3#_#$ 7%_#& C'_#( <)_#* 6+_#, 5-_#. F/_#0 J1_#2 :3_#4 35_#6 77_#8 59_#: :;_#< 2=_#> -?_#@ .A_#B :C_#D FE_#F 9G_#H 5I_#J 5K_#L 6M_#N ?O_#P 3Q_#R FS_#T 9U_#V :W_#X 8Y_#Z F[_#\ ;]_#^ 5__#` 6a_#b :c_#d Fe_#f 8g_#h Fi_#j <k_#l 2m_#n 5o_#p 8q_#r Fs_#t Wu_#v <w_#x 5y_#z 3{_#| 3}_#~ 2_#@ AA_#B 2C_#D FE_#F 6G_#H 4I_#J 9K_#L 7M_#N UO_#P :Q_#R )S_#T 3U_#V 8W_#X ?Y_#Z 7[_#\ 6]_#^ :__#` Fa_#b 6c_#d 5e_#f Fg_#h :i_#j !"@k_#l %>(#'  :/}_#@T$T$uT$ eT$ 	T$
 T$ uT$ T$ #JT$ wT$ $ZT$ 
T$ !(T$ 'T$ UT$ eT$  G!T$" e#T$$ 5%T$& #E'T$( u)T$* F+T$, U-T$. f/T$0 F1T$2 t3T$4 E5T$6 W7T$8 E9T$: ;T$< '=T$> ,Z?T$@ AT$B FCT$D ET$F eGT$H FIT$J !$KT$L FMT$N !%OT$P eQT$R  ST$T eUT$V UWT$X %eYT$Z [T$\ $V]T$^ F_T$` aT$b UcT$d (eT$f gT$h eiT$j kT$l UmT$n VoT$p UqT$r !%sT$t euT$v fwT$x  yT$z f{T$| F}T$~ 1%T$@ vAT$B #ECT$D !&ET$F 'GT$H uIT$J !' % !("##$*"  &$ #( %gT$W@uIA
v $&+(-,0,1)-+/6:#'#'"&#(	( #($($)+/27/3#')$, %)&+!%$(%)*/& ',#($)*/	# ',!%#($)*/( $(&+!%$(,0%+#($)*/	*  #q;z ##
 ##CEwIA
B YCIA
D /&(; 4^ ./@	
 +,@ /0D $%9 +I / 1. ./C 1. 12B 7 +L  B<!" 3L#$ 2C2<0C*62<.79F2@*:5: '31=/;&2,='4,=;&EIA
 I I	    c                 l    | j                  |t        | j                  |   d   d   | j                        S )N	precisionamount)decimal_to_precisionr/   marketsr  )r  symbolfees      r  fee_to_precisionzkraken.fee_to_precision0  s4    ((hV8L[8YZb8ceiewewxxr  c                    | j                   d   r| j                          | j                  |      }| j                  |di       }t	        |j                               }g }t        dt        |            D ]  }||   }||   }| j                  |d      }	| j                  |d      }
| j                  |	      }| j                  |
      }|j                  d      dk\  }| j                  |d      }| j                  |dg       }| j                  |dg       }| j                  |d	      }d
}|%| j                  t        j                  |d            }| j                  |dg       }| j                  |dg       }| j                  |d	      }d
}|%| j                  t        j                  |d            }| j                  |dg       }t        |      }| j                  | j                  | j                  |d                  }| j                  |d      }|dk(  }|j                  i d|d| j                  |d      d|r|n|dz   |z   d|d|dd
d|	d|
dd
d|d|d   ddddd|dkD  dd d!d d"d |d d
d
||d
d
d
d
d
| j                  | j                  | j                  |d#                  |d$| j                  d%      | j!                  ||d	z
  d	      d&| j!                  |d'      d
d&|d
d&| j!                  |d(      d
d&d)d
|d*        | j#                  |      }| j%                  |d      | j                   d+<   |S ),a2  
        retrieves data on all markets for kraken

        https://docs.kraken.com/rest/#tag/Spot-Market-Data/operation/getTradableAssetPairs

        :param dict [params]: extra parameters specific to the exchange API endpoint
        :returns dict[]: an array of objects representing market data
        r  resultr   basequote.daltname
fees_makerr   N100r   leverage_buypair_decimalsstatusonliner6   wsIdwsnamer  /settlebaseIdquoteIdsettleIddarkpooltyperC   TrD   rE   FrF   rG   lot_decimalsr  price1minmaxordermincostmin)r  r  r  cost)activecontractr  r  r   r   contractSizeexpiryexpiryDatetimestrike
optionTyper  limitscreatedinfor  )r   load_time_differencepublicGetAssetPairs
safe_valuelistkeysrangelensafe_stringsafe_currency_codefindr  r1   
string_divparse_precisionappendsafe_numberappend_inactive_marketsindex_by)r  paramsresponser  r)  r  ir6   marketr  r  r  r  r  r  	makerFeesfirstMakerFeefirstMakerFeeRater   	takerFeesfirstTakerFeefirstTakerFeeRater   leverageBuyleverageBuyLengthprecisionPricer  isActives                               r  fetch_marketszkraken.fetch_markets3  s    <<12%%'++F3` //(Hb9GLLN#q#d)$ O	AaBR[F%%ff5F&&vw7G**62D++G4Ewwt})H&&vy9GbAI OOIq"=M $ 0 0 BE ,))'*<*<=NPU*VW;I OOIq"=M $ 0 0 BE ,))'*<*<=NPU*VW//&."EK #K 0!..t/C/CDDTDTU[]lDm/noN%%fh7F)HMM 5b5((:5 X'D3J4F5 	5
 5 $5 &5 75 D5 H5 6),5 5 5 ,q05 5  %!5" %#5$ #! $"&""//0D0DTEUEUV\^lEm0no+  $005#//=NQR=RTUV!
  $//
C#
  .#
  $//	B#$  i5 55O	` --f5+/==+K'(r  Ncurrencyc                     |Tt        |      dkD  rF|j                  d      dk(  s|j                  d      dk(  r|j                  d      dkD  s
|dk7  r|dd  }t        t        |   ||      S )Nr   Xr   Z.ZEUSr   )r+  r.  r  r3   safe_currency)r  
currencyIdrD  r  s      r  rJ  zkraken.safe_currency  sm    !:"OOC(A-:??33G13L&OOC014:;O%/^
VT0XFFr  c                    | j                  d      | j                  d      d}d d d}|d   d d}|d   d d}|||d}dd d d d||d}g }t        d	t        |            D ]&  }	|j                  | j	                  |||	                ( |S )
Nz1e-8r  r  r  r  )r  r  r  F)r  r$  r   r   r  r  r"  r   )r  r*  r+  r1  extend)
r  r  r  
costLimitspriceLimitsamountLimitsr"  defaultsr  r7  s
             r  r3  zkraken.append_inactive_markets  s     ''/&&v.
	 $(5
$-g$6tD%.x%8F".jY"

 q#g,' 	=AMM$++h
;<	=r  c                     | j                  |      }| j                  |d      }| j                  |d      }|dk(  rdndddd|dS )aV  
        the latest known information on the availability of the exchange API

        https://docs.kraken.com/api/docs/rest-api/get-system-status/

        :param dict [params]: extra parameters specific to the exchange API endpoint
        :returns dict: a `status structure <https://docs.ccxt.com/#/?id=exchange-status-structure>`
        r  r  r  okmaintenanceN)r  updatedetaurlr$  )publicGetSystemStatus	safe_dictr,  )r  r5  r6  r  	statusRaws        r  fetch_statuszkraken.fetch_status  sZ     --f5 (3$$VX6	(H4d=
 	
r  c                     | j                  |      }| j                  |di       }t        |j                               }i }t	        dt        |            D ]%  }||   }||   }| j                  |      }	|j                  d      dk  rk| j                  |d      }
||
k7  rC|j                  d      s|j                  d      r!| j                  |
      }	|	| j                  |<   n| j                  |      }	| j                  | j                  | j                  |d                  }| j                  |d      d	k(  }|	j                  d
      dk\  }||	|| j                  |d      ||rdndddd||ddddddi d||	<   ( |S )a)  
        fetches all available currencies on an exchange

        https://docs.kraken.com/rest/#tag/Spot-Market-Data/operation/getAssetInfo

        :param dict [params]: extra parameters specific to the exchange API endpoint
        :returns dict: an associative dictionary of currencies
        r  r   rH  r  rF  rG  decimalsr  enabledz.HOLDfiatcryptoNr  )r  r   )r6   coder$  r7   r  r  depositr   r  r  r"  r  )publicGetAssetsr'  r(  r)  r*  r+  r-  r.  r,  
startswithr   r  r0  )r  r5  r6  
currenciesidsr  r7  r6   rD  ra  altNamer  r  isFiats                 r  fetch_currencieszkraken.fetch_currencies  s    ''/n __Xx<
:??$%q#c(# 6	AQB!"~H **2.Dwws|a**8Y? =bmmC&8BMM#<N227;D04D))"-2226D))$*>*>t?O?OPXZd?e*fgI%%h9YFFYYw'1,F ((9= "(h &  )#
  $#!	 +F4LA6	n r  rK  c                     ||S |j                  d      dkD  rO|j                  d      }| j                  |d      }| j                  |d      }t        t        |   ||      dz   |z   S t        t        |   ||      S )NrH  r   r   )r.  splitr,  r  r3   r-  )r  rK  rD  parts	firstPart
secondPartr  s         r  r-  zkraken.safe_currency_code}  s    ??3!#$$S)E((2I))%3J9)XNQTTWaaaVT5j(KKr  r  c                     | j                          | j                  |      }|d   dd}| j                  | j                  ||            }| j	                  |di       }| j                  ||      S )ab  
        fetch the trading fees for a market

        https://docs.kraken.com/rest/#tag/Account-Data/operation/getTradeVolume

        :param str symbol: unified market symbol
        :param dict [params]: extra parameters specific to the exchange API endpoint
        :returns dict: a `fee structure <https://docs.ccxt.com/#/?id=fee-structure>`
        r6   T)pairzfee-infor  )load_marketsr8  privatePostTradeVolumerM  r'  parse_trading_fee)r  r  r5  r8  requestr6  r  s          r  fetch_trading_feezkraken.fetch_trading_fee  ss     	V$4L
 ..t{{7F/KL< 8R8%%ff55r  c                    | j                  |di       }| j                  |di       }| j                  ||d   i       }| j                  ||d   i       }||d   | j                  t        j                  | j	                  |d      d            | j                  t        j                  | j	                  |d      d            dddS )	Nr  r   r6   r  r  r  T)r$  r  r   r   r   r   )r'  r  r1   r/  r,  )r  r6  r8  r9  r<  symbolMakerFeesymbolTakerFees          r  rs  zkraken.parse_trading_fee  s    OOHlB?	OOHfb9	F4L"EF4L"EX&&&w'9'9$:J:J>[`:ach'ij&&w'9'9$:J:J>[`:ach'ij
 	
r  priceKey	amountKeycountOrIdKeyc                 x    | j                  ||      }| j                  ||      }| j                  |d      }|||gS )N   )r2  safe_integer)r  bidaskry  rz  r{  r  r  	timestamps           r  parse_bid_askzkraken.parse_bid_ask  sE      2!!&)4%%fa0	vy))r  r  c                    | j                          | j                  |      }|d   rt        | j                  dz   |z         d|d   i}|||d<   | j	                  | j                  ||            }| j                  |di       }| j                  ||d         }| j                  |di       }	| j                  |	d      }
|
| j                  ||
|      }| j                  ||      S )	aG  
        fetches information on open orders with bid(buy) and ask(sell) prices, volumes and other data

        https://docs.kraken.com/rest/#tag/Spot-Market-Data/operation/getOrderBook

        :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
        r  zE fetchOrderBook() does not provide an order book for darkpool symbol rp  r6   countr  r$  r	  )rq  r8  r   r6   publicGetDepthrM  r'  parse_order_book)r  r  r  r5  r8  rt  r6  r  	orderbook
marketInfowsNames              r  fetch_order_bookzkraken.fetch_order_book  s     	V$**q qtz z{{F4L
 $GG&&t{{7F'CD( 8R8OOFF4L9	 __VVR8
X6	BI$$Y77r  tickerr8  c                 >   | j                  d |      }| j                  |dg       }| j                  |d      }| j                  |dg       }| j                  |d      }t        j                  ||      }| j                  |dg       }	| j                  |	d      }
| j                  |dg       }| j                  |dg       }| j                  |dg       }| j                  |d	g       }| j                  i d
|dd dd d| j                  |d      d| j                  |d      d| j                  |d      d| j                  |d      d| j                  |d      d| j                  |d      d|d| j                  |d      d|
d|
dd dd dd dd |||d|      S )Nvr   pcr   hlbar  r  datetimehighlowbid	bidVolumer}  ask	askVolumevwapopenocloselastpreviousClosechanger   average)
baseVolumequoteVolumer$  )safe_symbolr'  r,  r1   
string_mulsafe_ticker)r  r  r8  r  r  r  r  r  r  r  r  r  r  r  r  s                  r  parse_tickerzkraken.parse_ticker  s,    !!$/OOFC,%%a+
OOFC,1%((T:OOFC,1%vsB/oofc2.oofc2.oofc2. !
f!
!
 !
 D$$T1-	!

 4##C+!
 4##C+!
 ))#q1!
 4##C+!
 ))#q1!
 D!
 D$$VS1!
 T!
 D!
 T!
 d!
  $!!
" t#!
$ %&)!
* + 	r  symbolsc                 Z   | j                          i }|u| j                  |      }g }t        dt        |            D ]6  }||   }| j                  |   }|d   s|d   r#|j                  |d          8 dj                  |      |d<   | j                  | j                  ||            }|d   }	t        |	j                               }
i }t        dt        |
            D ]7  }|
|   }| j                  |      }|d   }|	|   }| j                  ||      ||<   9 | j                  |d|      S )	a-  
        fetches price tickers for multiple markets, statistical information calculated over the past 24 hours for each market

        https://docs.kraken.com/rest/#tag/Spot-Market-Data/operation/getTickerInformation

        :param str[]|None symbols: unified symbols of the markets to fetch the ticker for, all market tickers are returned if not assigned
        :param dict [params]: extra parameters specific to the exchange API endpoint
        :returns dict: a dictionary of `ticker structures <https://docs.ccxt.com/#/?id=ticker-structure>`
        r   r  r  r6   ,rp  r  r  )rq  market_symbolsr*  r+  r  r1  joinpublicGetTickerrM  r(  r)  safe_marketr  filter_by_array_tickers)r  r  r5  rt  	marketIdsr7  r  r8  r6  tickersrf  r  r6   r  s                 r  fetch_tickerszkraken.fetch_tickers0  sC    	))'2GI1c'l+ 3 f-(#F:,>$$VD\2	3
 "hhy1GFO''GV(DE8$7<<>"q#c(# 	?AQB%%b)FH%FR[F!..vv>F6N	? ++FHgFFr  c                 0   | j                          |j                  d      dk\  }|rt        | j                  dz   |z         | j	                  |      }d|d   i}| j                  | j                  ||            }|d   |d      }| j                  ||      S )a  
        fetches a price ticker, a statistical calculation with the information calculated over the past 24 hours for a specific market

        https://docs.kraken.com/rest/#tag/Spot-Market-Data/operation/getTickerInformation

        :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>`
        r   r   z= fetchTicker() does not provide a ticker for darkpool symbol rp  r6   r  )rq  r.  r   r6   r8  r  rM  r  )r  r  r5  r  r8  rt  r6  r  s           r  fetch_tickerzkraken.fetch_tickerQ  s     	;;t$)*i ilr rssV$F4L
 ''GV(DE(#F4L1  00r  c           	          | j                  |d      | j                  |d      | j                  |d      | j                  |d      | j                  |d      | j                  |d      gS )Nr   r   r}  r      r   )safe_timestampr2  )r  ohlcvr8  s      r  parse_ohlcvzkraken.parse_ohlcvg  sn     q)UA&UA&UA&UA&UA&
 	
r  r   sincec           	      (   | j                          d}| j                  |dd      \  }}|r| j                  d|||||d      S | j                  |      }| j	                  | j
                  |      }d|d   i}	|||	d<   n||	d<   |0| j                  |dz        }
|d	z  }| j                  |
|z
        |	d
<   | j                  | j                  |	|            }| j                  |di       }| j                  ||d   g       }| j                  |||||      S )a  
        fetches historical candlestick data containing the open, high, low, and close price, and the volume of a market

        https://docs.kraken.com/api/docs/rest-api/get-ohlc-data

        :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
        :param boolean [params.paginate]: default False, when True will automatically paginate by calling self endpoint multiple times. See in the docs all the [availble parameters](https://github.com/ccxt/ccxt/wiki/Manual#pagination-params)
        :returns int[][]: A list of candles ordered, open, high, low, close, volume
        Frq   paginater  rp  r6   intervalr>   r   r  r  )rq  handle_option_and_params"fetch_paginated_call_deterministicr8  r~  r   parse_to_intnumber_to_stringpublicGetOHLCrM  r'  	safe_listparse_ohlcvs)r  r  	timeframer  r  r5  r  r8  parsedTimeframert  scaledSincetimeFrameInSecondsr6  r  ohlcvss                  r  fetch_ohlcvzkraken.fetch_ohlcv}  sA    	88zZ&::<QVX]_hjpruvvV$++DOOYGF4L
 &"1GJ"+GJ++EDL9K!02!5#44[CU5UVGG%%dkk'6&BC 8R8tb9  E5IIr  c                 8    dddddd}| j                  |||      S )Ntradetransactionr   rD   )r  
withdrawalrb  r   rD   r,  )r  r  typess      r  parse_ledger_entry_typezkraken.parse_ledger_entry_type  s/    '$"
 tT22r  itemc                 t   | j                  |d      }d }d }| j                  |d      }d }| j                  | j                  |d            }| j                  |d      }	| j                  |	|      }
| j                  |	|      }| j                  |d      }t	        j
                  |d      rd}t	        j                  |      }nd}| j                  |d	d
      }| j                  ||||||||
| j                  |      d | j                  |d      d|| j                  |      | j                  |d      |
dd|      S )Nr6   refidr  assetr  r<   outintimer>   balancerS  r  r  rD  )r$  r6   	directionaccountreferenceIdreferenceAccountr  rD  r  beforeafterr  r  r  r  )r,  r  r-  rJ  r1   	string_lt
string_abssafe_integer_productsafe_ledger_entryr  r2  iso8601)r  r  rD  r6   r  r  r  r  r  rK  ra  r  r  s                r  parse_ledger_entryzkraken.parse_ledger_entry  s[     dD)	&&tW5++D,<,<T6,JK%%dG4
&&z8<%%j(;!!$1VS)I''/FI--dFDA	%%"& 0''/%%dI6"Y/((u5 '
& ' 	r  ra  c                    | j                          i }d}|| j                  |      }|d   |d<   || j                  |dz        |d<   | j                  |ddg      }|R| j	                  |ddg      }t        j                  |d      }| j                  t        j                  |d	            |d
<   | j                  | j                  ||            }	| j                  |	di       }
| j                  |
di       }t        |j                               }g }t        dt        |            D ]"  }||   }||   }||d<   |j                  |       $ | j!                  ||||      S )a  
        fetch the history of changes, actions done by the user or operations that altered the balance of the user

        https://docs.kraken.com/rest/#tag/Account-Data/operation/getLedgers

        :param str [code]: unified currency code, default is None
        :param int [since]: timestamp in ms of the earliest ledger entry, default is None
        :param int [limit]: max number of ledger entries to return, default is None
        :param dict [params]: extra parameters specific to the exchange API endpoint
        :param int [params.until]: timestamp in ms of the latest ledger entry
        :param int [params.end]: timestamp in seconds of the latest ledger entry
        :returns dict: a `ledger structure <https://docs.ccxt.com/#/?id=ledger>`
        Nr6   r  r>   startuntiltill1000r  endr  ledgerr   )rq  rD  r  safe_string_nomitr1   r/  
string_addprivatePostLedgersrM  r'  r(  r)  r*  r+  r1  parse_ledger)r  ra  r  r  r5  rt  rD  r  untilDividedr6  r  r  r)  itemsr7  keyvalues                    r  fetch_ledgerzkraken.fetch_ledger  sq    	}}T*H'~GG#00>GG""6GV+<=YYv'89F"--eV<L!..w/A/A,PS/TUGEN**4;;w+GH 8R826FKKM"q#d)$ 	 Aq'C3KEE$KLL		 
   %??r  c                 d   | j                          dj                  |      }| j                  d|i|      }| j                  |      }|d   }t	        |j                               }g }t        dt        |            D ]"  }	||	   }
||
   }|
|d<   |j                  |       $ | j                  |      S )Nr  r6   r  r   )
rq  r  rM  privatePostQueryLedgersr(  r)  r*  r+  r1  r  )r  rf  ra  r5  rt  r6  r  r)  r  r7  r  r  s               r  fetch_ledger_entries_by_idsz"kraken.fetch_ledger_entries_by_ids  s    hhsm++#
 //8 (#FKKM"q#d)$ 	 Aq'C3KEE$KLL		 
   ''r  r6   c                 4    | j                  |g||      }|d   S )Nr   )r  )r  r6   ra  r5  r  s        r  fetch_ledger_entryzkraken.fetch_ledger_entry:  s!    00"tVDQxr  r  c                    d }d }d }d }d }d }d }	d }
d }t        |t              rr| j                  |d      }|d   dk(  rdnd}|d   dk(  rdnd	}| j                  |d
      }| j                  |d      }t	        |      }|dkD  r| j                  |d      }nt        |t
              r|}nd|v r| j                  |d      }| j                  |      }||}n|| j                  |      }| j                  |d      }	| j                  |dd      }| j                  |d      }| j                  |d      }| j                  |d      }| j                  |d      }| j                  |d      }d|v rd }||d   }| j                  |d      |d}
||d   }| j                  |d      }| j                  |d      }d }||rdnd}| j                  ||	||| j                  |      ||||||||
d|      S )Nr}  r   ssellbuyr  r  r  r8  r   r   r   	ordertxidrp  r6   postxidr  r  	ordertyper  volr  r  r  r  r  r   r   )r6   orderr$  r  r  r  r  sidetakerOrMakerr  r  r  r  )
isinstancer(  r  r,  r+  strfind_market_by_altname_or_idget_delisted_market_by_idsafe_string_2	safe_bool
safe_trader  )r  r  r8  r  r  r  r  r  r6   orderIdr  r  tradeLengthmarketIdfoundMarketrD  r  r   r  s                      r  parse_tradezkraken.parse_trade>  sX   f 	eT"++E15I#Ah#o6ED$Qx37XD$$UA.E%%eQ/Fe*KQ%%eQ/s#BE!''v6H;;HEK&$%77A&&uk:G##E4;B++E6:I##E62D##E;7D$$UG4E%%eU3F~%%gH ,,UE: ( H%Fv.ug.&+7L"Y/( 
  	r  c                    | j                          | j                  |      }|d   }d|i}|&| j                  | j                  |dz              |d<   |||d<   | j	                  | j                  ||            }|d   }	|	|   }
t        |
      }|dk  rg S |
|dz
     }| j                  |	d	      }|j                  |       ||
|dz
  <   | j                  |
|||      S )
a4  
        get the list of most recent trades for a particular symbol

        https://docs.kraken.com/rest/#tag/Spot-Market-Data/operation/getRecentTrades

        :param str symbol: unified symbol of the market to fetch trades for
        :param int [since]: timestamp in ms of the earliest trade to fetch
        :param int [limit]: the maximum amount of trades to fetch
        :param dict [params]: extra parameters specific to the exchange API endpoint
        :returns Trade[]: a list of `trade structures <https://docs.ccxt.com/#/?id=public-trades>`
        r6   rp  r>   r  r  r  r   r   r  )
rq  r8  r  r  publicGetTradesrM  r+  r,  r1  parse_trades)r  r  r  r  r5  r8  r6   rt  r6  r  tradeslength	lastTradelastTradeIds                 r  fetch_tradeszkraken.fetch_trades  s    	V$D\B

 #44T5F5Fut|5TUGG$GG''GV(DE (#VQ;I6A:&	&&vv6%&vz  >>r  c                    | j                  |di       }|d d d}t        |j                               }t        dt	        |            D ]j  }||   }| j                  |      }| j                  ||i       }| j                         }	| j                  |d      |	d<   | j                  |d      |	d<   |	||<   l | j                  |      S )Nr  )r$  r  r  r   
hold_tradeusedr  total)	r'  r(  r)  r*  r+  r-  r  r,  safe_balance)
r  r6  balancesr  currencyIdsr7  rK  ra  r  r  s
             r  parse_balancezkraken.parse_balance  s    ??8Xr:

 8==?+q#k*+ 	#A$QJ**:6Dooh
B?GllnG"..wEGFO#//CGG"F4L	#   ((r  c                 f    | j                          | j                  |      }| j                  |      S )aw  
        query for balance and get the amount of funds available for trading or funds locked in orders

        https://docs.kraken.com/rest/#tag/Account-Data/operation/getExtendedBalance

        :param dict [params]: extra parameters specific to the exchange API endpoint
        :returns dict: a `balance structure <https://docs.ccxt.com/#/?id=balance-structure>`
        )rq  privatePostBalanceExr#  )r  r5  r6  s      r  fetch_balancezkraken.fetch_balance  s3     	,,V4  !!(++r  r  r  c                 v    | j                          d|i}| j                  |d||d| j                  ||            S )a5  
        create a market order by providing the symbol, side and cost

        https://docs.kraken.com/rest/#tag/Spot-Trading/operation/addOrder

        :param str symbol: unified symbol of the market to create an order in(only USD markets are supported)
        :param str side: 'buy' or 'sell'
        :param float cost: how much you want to trade in units of the quote currency
        :param dict [params]: extra parameters specific to the exchange API endpoint
        :returns dict: an `order structure <https://docs.ccxt.com/#/?id=order-structure>`
        r  r8  N)rq  create_orderrM  )r  r  r  r  r5  reqs         r  create_market_order_with_costz$kraken.create_market_order_with_cost  sH     	 D
   4tT[[QTV\E]^^r  c                 J    | j                          | j                  |d||      S )a  
        create a market buy order by providing the symbol, side and cost

        https://docs.kraken.com/rest/#tag/Spot-Trading/operation/addOrder

        :param str symbol: unified symbol of the market to create an order in
        :param float cost: how much you want to trade in units of the quote currency
        :param dict [params]: extra parameters specific to the exchange API endpoint
        :returns dict: an `order structure <https://docs.ccxt.com/#/?id=order-structure>`
        r   )rq  r*  )r  r  r  r5  s       r  !create_market_buy_order_with_costz(kraken.create_market_buy_order_with_cost$  s'     	11&%vNNr  r  r  r  c           	         | j                          | j                  |      }|d   ||| j                  ||      d}| j                  d||||||      }	| j	                  |	d   dd      }
|
j                  d      dkD  }| j                  | j                  |	d   |	d	               }| j                  |d
      }||d<   | j                  |      S )a<  
        create a trade order

        https://docs.kraken.com/api/docs/rest-api/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
        :param bool [params.postOnly]: if True, the order will only be posted to the order book and not executed immediately
        :param bool [params.reduceOnly]: *margin only* indicates if self order is to reduce the size of a position
        :param float [params.stopLossPrice]: *margin only* the price that a stop loss order is triggered at
        :param float [params.takeProfitPrice]: *margin only* the price that a take profit order is triggered at
        :param str [params.trailingAmount]: *margin only* the quote amount to trail away from the current market price
        :param str [params.trailingPercent]: *margin only* the percent to trail away from the current market price
        :param str [params.trailingLimitAmount]: *margin only* the quote amount away from the trailingAmount
        :param str [params.trailingLimitPercent]: *margin only* the percent away from the trailingAmount
        :param str [params.offset]: *margin only* '+' or '-' whether you want the trailingLimitAmount value to be positive or negative, default is negative '-'
        :param str [params.trigger]: *margin only* the activation price type, 'last' or 'index', default is 'last'
        :returns dict: an `order structure <https://docs.ccxt.com/#/?id=order-structure>`
        r6   )rp  r  r  volumerQ   r   oflags viqcr   r  	usingCost)
rq  r8  amount_to_precisionorder_requestr,  r.  privatePostAddOrderrM  rY  parse_order)r  r  r  r  r  r  r5  r8  rt  orderRequestflagsisUsingCostr6  r  s                 r  r(  zkraken.create_order2  s    0 	V$4L..vv>	
 ))-wPVX]_ef  a(B?jj(2-++DKKQVW,YZ (3){ ''r  c                 p    | j                  | j                  di       }||v r||   S | j                  |      S )Nr  )r'  r   r  )r  r6   r  s      r  r
  z#kraken.find_market_by_altname_or_idf  s?    ??4<<9KRP!!#B''##B''r  c                 R   ||S | j                  | j                  d   |      }||S d}d}d}d}t        |      dk(  rd}d}d}nt        |      dk(  rd}d}d}||| }||| }| j                  |      }	| j                  |      }
|	dz   |
z   }||	|
||d	}|| j                  d   |<   |S )
Nr  r   r   r      r     r
  )r  r  r  r  r  )r'  r   r+  r-  )r  r6   r8  baseIdStart	baseIdEndquoteIdStart
quoteIdEndr  r  r  r  r  s               r  r  z kraken.get_delisted_market_by_idm  s    :I.C!DbIM	
r7a<ILJW\ILJK	*\*-&&v.''0e#
 39*+B/r  r  c                 8    dddddd}| j                  |||      S )Nr  closedcanceledexpired)pendingr  rD  rE  rF  r  r  r  statusess      r  parse_order_statuszkraken.parse_order_status  s/    " 
 &&99r  c                 8    dddddd}| j                  |||      S )Nr8  r  )take-profit	stop-lossstop-loss-limittake-profit-limittrailing-stop-limitr  rH  s      r  parse_order_typezkraken.parse_order_type  s1     $!&!(#*
 &&99r  r  c                 
   | j                  |dd      }| j                  |d      }| j                  |di       }| j                  |d      }d }|| j                  |d      }n| j                  |d      }d }d }d }	d }
d }d }d }||j	                  d      }| j                  |d      }|s| j                  |d      }n| j                  |d      }| j                  |d      }	| j                  |d	      }| j                  |d
      }|dk(  s|dk(  r|}n|dz   |z   }|dk(  s|dk(  r%| j                  |d      }| j                  |d      }
n|dk(  r| j                  |d
      }
| j                  |d|      }| j                  |d|      }| j                  |d|	      }	| j                  |	      }d }||}n|	| j                  |	      }| j                  |d      }| j                  |d|      }| j                  |d      }d }| j                  |d|
      }
|
?|
j                  d      s,t        j                  |
d      st        j                  |
d      rd }
|
&| j                  |d      }
| j                  |dd|
      }
| j                  |dd      }|j                  d      d kD  }| j                  |d      }|Y|d!   }d"|v rP| j                  |d"      }|d d#}|j                  d$      dk\  r	|d%   |d&<   n|j                  d'      dk\  r|d(   |d&<   | j                  | j                  |d)            }| j                  |g d*      }||j!                  d+      r$| j#                  |d,      }| j                  |d      }| j                  |d-      }| j                  |d.|      }| j%                  |d/g       }g } t'        dt)        |            D ]N  }!||!   }"t+        |"t,              r&| j/                  | j1                  |"||i d0             >| j/                  |"       P d }#d }$||j!                  d1      r4| j                  |d      }$| j3                  | j                  |d            }
nT|j!                  d2      r4| j                  |d      }#| j3                  | j                  |d            }
n|dk(  r|}$n|dk(  r|}#| j5                  |      }%| j7                  |%ddg      r|
dnd}%| j                  |d3      }&|&d }| j9                  i d4|d5|d6|d7|d8| j;                  |      d9d d)|d!|d|%d:d d;|d<|d|
d=|d>|$d?|#d@||||d | j=                  |dAdB      || dC|      S )DNr3  Fdescrr   r   r   r}  r  r   r  r8  z	stop lossztake profitr   	   r  r  rp  opentmr  vol_execr  %z0.00000r<   price2
limitpricer/  r0  r   r2  r  r  )r  ratefciqr  rD  fcibr  r  )r6   txidorder_idamend_id[r^  userref	cl_ord_idr  )r6   r  r  r$  rL  rM  r`  r6   clientOrderIdr$  r  r  lastTradeTimestampr  postOnlyr  r  r  r  r  
reduceOnlyreduce_only)r  filledr  	remainingrg  r  r  )r  r  rY  r,  rk  r
  r  r  endswithr1   string_equalsr  r.  r2  rJ  r  rd  r  r'  r*  r+  r  r	  r1  r  	omit_zerorQ  in_array
safe_orderr  safe_bool_2)'r  r  r8  r:  descriptionorderDescriptionObjorderDescriptionr  rawTyper  r  r  r  r  rl  part4part5r  r  r  ri  r  r9  
isPostOnlyr  feeCostr  r6   r^  rb  rd  	rawTradesr  r7  rawTrader  r  	finalTypeamendIds'                                          r  r7  zkraken.parse_order  sx   F nnUK?		%-nnUGR8"nnUG<*#//0CWM#//w?'$**3/E##E1-D))%3''q1''q1H$$UA.E$$UA.E5H#4#+-+%M)A#//q9((2G#((2VT:"";WE##KB77A" F!33H=F''x8	!!%7!!%4   gu=ENN3$77;P;PQVXa;bfmf{f{  }B  DG  gHE=$$[(;E&&ulGUKE  "5ZZ'",
""5'2H%F~**5%8#  ::f%*&,WoC
OZZ'1,&,VnC
O(()9)9%)JK'MNJBMM#.>>%0D!!$*B""5)4((WEOOE8R8	q#i.) 	(A |H(C(dooX"X^hj.klmh'	(  !!-0"&"2"2;"Ht'7'7X'NO##K0 $ 0 0g Ft'7'7X'NOM)".K' ,))'2	 ==[-$@A%*]I""5*5J  
" 
] 
 E 
 	 

 Y/ 
 !$ 
 f 
 f 
 I 
 4 
 
 
 D 
 U 
 L 
  
  ]! 
" D# 
$ **5,N1 
2 3 	r  methodrt  c                 v   | j                  |d      }| j                  |dg      }|||d<   | j                  |d      }	| j                  |d      }
|	d u}|
d u}|xs |}| j                  |d      }| j                  |d      }| j                  |d      }| j                  |d      }|d u}|d u}|j                  d	      }|d
k(  }| j                  |d      }| j                  |d      }| j                  |ddg      }|d uxr |j                  d      dkD  }|rQ||rM|'|%| j	                  || j                  |            |d<   n| j	                  ||      |d<   ||dz   nd}||d<   n|r|s|s| j                  ||      |d<   | j                  |dd      }|ra|r#| j                  ||	      |d<   |rd|d<   n*d|d<   n$|r"| j                  ||
      |d<   |rd|d<   nd|d<   |r| j                  ||      |d<   n|s|rd }||j                  d      rd|z   nd|z   dz   }|d|z   nd }| j                  |dd      }||| j                  |      z   nd }| j                  |dd      }||d<   |s||=d |d<   |)|j                  d      r||z   n||z   dz   } ||d<   | |d<   n|||d<   ||d<   nd!|d<   |||d<   n||d<   |r|d"k(  rd#|d<   nd$|d<   | j                  |d%      }!|!i| j                  i |!      }!| j                  |!d      }"|"| j                  ||"      |!d<   | j                  |!d      }#|#| j                  ||#      |!d<   |!|d%<   | j                  |d&d'      }$|$|$|d'<   |d
k(  }%d }&| j                  |%d(|      \  }&}|&r||d)z   nd*}'|'|d<   |	d|vr||d<   | j                  |g d+      }||gS ),Nrd  rc  r  r  trailingAmounttrailingPercenttrailingLimitAmounttrailingLimitPercentr  r8  r  r/  r1  r2  r.  z,viqcr  rg  rh  rN  r  rM  rO  rL  rY  rX  +offset-r  r  rP  ztrailing-stopcreateOrderWsTtruer  r  timeinforceFz,postr   )	r  rg  r  r  r  r  r  r  r  )r,  r  rk  r.  cost_to_precisionr  price_to_precisionrp  rY  rM  r'  r  handle_post_only)(r  r}  r  r  rt  r  r  r5  rd  stopLossTriggerPricetakeProfitTriggerPriceisStopLossTriggerOrderisTakeProfitTriggerOrderisStopLossOrTakeProfitTriggerr  r  r  r  isTrailingAmountOrderisTrailingPercentOrderisLimitOrderisMarketOrderr  r9  isViqcOrderextendedOflagsrg  trailingPercentStringtrailingAmountStringr  trailingLimitAmountStringtrailingActivationPriceTypetrailingLimitPercentStringr  
closePriceclosePrice2r  isMarketrf  extendedPostFlagss(                                           r  r5  zkraken.order_request  s   ((A6O#45$#0GK #//H!%!1!1&:K!L!5T!A#9#E (>(ZBZ%))&2BC**63DE"..v7LM#//8NO .d :!0!<}}W-(/  26FH#56D(Guzz&/AB/Fd.+|!3$($:$:64CXCXY_C`$a!$($:$:64$H!161BUW_N .GH"7@V#66vuEGG%%flMJ
(%#'#:#:6CW#X +<GK(+6GK()#'#:#:6CY#Z +>GK(+8GK($($;$;FE$J!"&<$(!*DSD\D\]`Da)>ilo~i~  BE  jE%<J<V3#7]a %%fh<F`s`1F1FGZ1[([  GK%*.*:*:69f*U'!<GI 3 ?EYEe'<$'3UiUrUrsvUw&;O2O  @F  I]  @]  `c  @c.'<GG$(BGH%(4';GG$(AGH%'6$".'<GG$';GG$()-&)/&vw/KKE*E8J%!%!8!8!Lg//%:K&"&"9"9&+"Nh$GG((N"%0GM"H$005&I&494EF 1GHG(; %GH6  $C  D  r  c                    | j                          | j                  |      }|d   s!t        | j                  dz   |d   z   dz         d|i}	| j	                  |dd      }
|
+|
|	d<   | j                  |ddg      }| j                  |	d      }	|d	k(  }d}| j                  |d
|      \  }}|rd|	d<   || j                  ||      |	d<   || j                  ||      |	d<   | j                  |g d      }|H| j                  |d      }| j                  |g d      }|||z   }||	d<   n| j                  ||      |	d<   | j                  | j                  |	|            }| j                  |di       }| j                  ||      S )aN  
        edit a trade order

        https://docs.kraken.com/api/docs/rest-api/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
        :param float [params.stopLossPrice]: the price that a stop loss order is triggered at
        :param float [params.takeProfitPrice]: the price that a take profit order is triggered at
        :param str [params.trailingAmount]: the quote amount to trail away from the current market price
        :param str [params.trailingPercent]: the percent to trail away from the current market price
        :param str [params.trailingLimitAmount]: the quote amount away from the trailingAmount
        :param str [params.trailingLimitPercent]: the percent away from the trailingAmount
        :param str [params.offset]: '+' or '-' whether you want the trailingLimitAmount value to be positive or negative
        :param boolean [params.postOnly]: if True, the order will only be posted to the order book and not executed immediately
        :param str [params.clientOrderId]: the orders client order id
        :returns dict: an `order structure <https://docs.ccxt.com/#/?id=order-structure>`
        rC   z editOrder() does not support r  z& orders, only spot orders are acceptedr^  rd  rc  Nr8  Fr  	post_only	order_qtylimit_price)r  r  r  r  r  r  r  )r  r  r  r  r  r  r  trigger_pricer  )rq  r8  r(   r6   r  r  r  r4  r  r  r,  privatePostAmendOrderrM  rY  r7  )r  r6   r  r  r  r  r  r5  r8  rt  rd  r  rf  allTriggerPricesr  r6  r  s                    r  
edit_orderzkraken.edit_order  s   0 	V$f~tww)IIFSYNZ  ^F   F  G  GB
 **6?KP$#0GK YYv'EFFii0GH$005&I&#)GK #'#;#;FF#KGK %)%<%<VU%KGM"--f  7o  p'%%fh7FYYv  (j  kF!#),<#< +;(+/+B+B6K[+\(--dkk'6.JK (B7//r  c                 ~   | j                          | j                  |dd      }d|d}|}|||d<   | j                  |ddg      }| j                  | j	                  ||            }| j                  |dg       }||vrt        | j                  dz   |z         | j                  | j	                  d|i||               S )a  
        fetches information on an order made by the user

        https://docs.kraken.com/rest/#tag/Account-Data/operation/getOrdersInfo

        :param str id: order id
        :param str symbol: not used by kraken fetchOrder
        :param dict [params]: extra parameters specific to the exchange API endpoint
        :returns dict: An `order structure <https://docs.ccxt.com/#/?id=order-structure>`
        rb  rd  Tr  r^  r  z& fetchOrder() could not find order id r6   )	rq  safe_value_2r  privatePostQueryOrdersrM  r'  r'   r6   r7  )	r  r6   r  r5  rd  rt  queryr6  r  s	            r  fetch_orderzkraken.fetch_order9  s     	))&)_M

 $!.GIIIfy/&BCE..t{{7E/JKL 8R8f*R RUW WXXT2Jr
 CDDr  c                    | j                  |d      }g }|t        | j                  dz         t        dt	        |            D ]=  }||   }	t        |	t              r|j                  |	       *|j                  |	d          ? | j                          || j                  |      }| j                  | j                  di       }
| j                  |
dd      }t	        |      }| j                  ||z        }| j                  |d	      }g }t        d|      D ]  }g }t        d|      D ]1  }| j                  ||z  |      }||k  s|j                  ||          3 d
dj                  |      i}| j                  |      }| j                  |d      }t!        |j#                               }t        dt	        |            D ]  }||   |||      d<    | j%                  |d||      }| j'                  ||      }| j)                  ||      } |S )a'  
        fetch all the trades made from a single order

        https://docs.kraken.com/rest/#tag/Account-Data/operation/getTradesInfo

        :param str id: order id
        :param str symbol: unified market symbol
        :param int [since]: the earliest time in ms to fetch trades for
        :param int [limit]: the maximum number of trades 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>`
        r  Nz fetchOrderTrades() requires a unified order structure in the params argument or a 'trades' param(an array of trade id strings)r   r6   rv   	batchSize   r   r^  r  r  )r'  r!   r6   r*  r+  r  r	  r1  rq  r  r   r~  r  sumr  privatePostQueryTradesr(  r)  r  filter_by_symbolarray_concat)r  r6   r  r  r  r5  orderTradestradeIdsr7  
orderTrader   r  numTradeIds
numBatchesr  j
requestIdskindexrt  r6  ry  rf  r  tradesFilteredBySymbols                            r  fetch_order_tradeszkraken.fetch_order_tradesz  s.    oofh7#DGG  /p  %p  q  q1c+./ 6(^
j#.OOJ/OOJt$456 	[[(F//$,,0BBG%%g{B?	(m&&{Y'>?
XXj!,
q*% %	GAJ1i( 7Y2;&%%huo67
 ,G 227;H, (;Iy~~'(C1c#h' 1*-a&	#a&!$'1&&y$uEF%)%:%:66%J"&&v/EFFK%	GL r  c                    | j                          | j                  | j                  ddj                  |      d|            }| j	                  |di       }g }t        |j                               }t        dt        |            D ]@  }||   }	||	   }
| j                  | j                  d|	i|
            }|j                  |       B |S )a  
        fetch orders by the list of order id

        https://docs.kraken.com/rest/#tag/Account-Data/operation/getClosedOrders

        :param str[] [ids]: list of order id
        :param str [symbol]: unified ccxt market symbol
        :param dict [params]: extra parameters specific to the kraken api endpoint
        :returns dict[]: a list of `order structure <https://docs.ccxt.com/#/?id=order-structure>`
        Tr  r  r  r   r6   )rq  r  rM  r  r'  r(  r)  r*  r+  r7  r1  )r  rf  r  r5  r6  r  ordersorderIdsr7  r6   r  r  s               r  fetch_orders_by_idszkraken.fetch_orders_by_ids  s     	..t{{HHSM<
 0  8R8&q#h-( 	!A!B":D$$T[[$T%BCEMM% 		!
 r  c                 N   | j                          i }|| j                  |dz        |d<   | j                  |ddg      }|R| j                  |ddg      }t	        j
                  |d      }| j                  t	        j                  |d            |d<   | j                  | j                  ||            }|d	   d
   }	t        |	j                               }
t        dt        |
            D ]  }|
|   |	|
|      d<    d}|| j                  |      }| j                  |	|||      S )a  
        fetch all trades made by the user

        https://docs.kraken.com/api/docs/rest-api/get-trade-history

        :param str symbol: unified market symbol
        :param int [since]: the earliest time in ms to fetch trades for
        :param int [limit]: the maximum number of trades structures to retrieve
        :param dict [params]: extra parameters specific to the exchange API endpoint
        :param int [params.until]: timestamp in ms of the latest trade entry
        :param int [params.end]: timestamp in seconds of the latest trade entry
        :returns Trade[]: a list of `trade structures <https://docs.ccxt.com/#/?id=trade-structure>`
        Nr>   r  r  r  r  r  r  r  r  r   r6   )rq  r  r  r  r1   r/  r  privatePostTradesHistoryrM  r(  r)  r*  r+  r8  r  )r  r  r  r  r5  rt  r  r  r6  r  rf  r7  r8  s                r  fetch_my_tradeszkraken.fetch_my_trades  s:    	
 #00>GG""6GV+<=YYv'89F"--eV<L!..w/A/A,PS/TUGEN00Wf1MN: (#H-6;;=!q#c(# 	*A#&q6F3q6N4 	*[[(F  >>r  c                 &   | j                          d}| j                  |d|      }| j                  |d      }d|i}| j                  |dd      }|+||d<   | j                  |ddg      }| j                  |d      }	 | j	                  | j                  ||            }| j                  d	|i      S # t        $ rV}| j                  rC| j                  j                  d      dk\  r%t        | j                  dz   | j                  z         |d}~ww xY w)
a  
        cancels an open order

        https://docs.kraken.com/api/docs/rest-api/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
        :param str [params.clientOrderId]: the orders client order id
        :param int [params.userref]: the orders user reference id
        :returns dict: an `order structure <https://docs.ccxt.com/#/?id=order-structure>`
        Nrb  r^  rd  rc  r  r   z cancelOrder() error r$  )rq  r'  r  r  privatePostCancelOrderrM  	Exceptionlast_http_responser.  r'   r6   ro  )	r  r6   r  r5  r6  	requestIdrt  rd  es	            r  cancel_orderzkraken.cancel_order 	  s%    	OOFIr:	69-I
 **6?KP$#0GK YYv'EFFii0G	224;;w3OPH H 
  	  	&&**//0FG1L'2I(IDLcLc(cddG		s   =!B1 1	D:ADDc                 t    d|i}| j                  | j                  ||            }| j                  d|i      gS )a  
        cancel multiple orders

        https://docs.kraken.com/rest/#tag/Spot-Trading/operation/cancelOrderBatch

        :param str[] ids: open orders transaction ID(txid) or user reference(userref)
        :param str symbol: unified market symbol
        :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>`
        r  r$  )privatePostCancelOrderBatchrM  ro  )r  rf  r  r5  rt  r6  s         r  cancel_orderszkraken.cancel_ordersL	  sO     c
 33DKK4PQ OO 
 	
r  c                 l    | j                          | j                  |      }| j                  d|i      gS )a  
        cancel all open orders

        https://docs.kraken.com/rest/#tag/Spot-Trading/operation/cancelAllOrders

        :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>`
        r$  )rq  privatePostCancelAllro  )r  r  r5  r6  s       r  cancel_all_orderszkraken.cancel_all_ordersi	  sB     	,,V4 OO 
 	
r  timeoutc                     |dkD  rt        | j                  dz         | j                          d|dkD  r| j                  |dz        ndi}| j	                  | j                  ||            }|S )at  
        dead man's switch, cancel all orders after the given timeout

        https://docs.kraken.com/rest/#tag/Spot-Trading/operation/cancelAllOrdersAfter

        :param number timeout: time in milliseconds, 0 represents cancel the timer
        :param dict [params]: extra parameters specific to the exchange API endpoint
        :returns dict: the api result
        i \&zG cancelAllOrdersAfter timeout should be less than 86400000 millisecondsr  r   r>   )r"   r6   rq  r  privatePostCancelAllOrdersAfterrM  )r  r  r5  rt  r6  s        r  cancel_all_orders_afterzkraken.cancel_all_orders_after	  su     XTWW'ppqqw{))'D.9QR
 77GV8TU r  c                    | j                          i }|| j                  |dz        |d<   | j                  |d      }|||d<   | j                  |d      }| j	                  |d      }|||d<   | j                  |d      }| j                  | j                  ||            }d}	|| j                  |      }	| j                  |di       }
| j                  |
di       }g }t        |j                               }t        d	t        |            D ]/  }||   }||   }|j                  | j                  d
|i|             1 | j                  ||	||      S )a  
        fetch all unfilled currently open orders

        https://docs.kraken.com/api/docs/rest-api/get-open-orders

        :param str [symbol]: unified market symbol
        :param int [since]: the earliest time in ms to fetch open orders for
        :param int [limit]: the maximum number of  open orders structures to retrieve
        :param dict [params]: extra parameters specific to the exchange API endpoint
        :param str [params.clientOrderId]: the orders client order id
        :param int [params.userref]: the orders user reference id
        :returns Order[]: a list of `order structures <https://docs.ccxt.com/#/?id=order-structure>`
        Nr>   r  rb  rd  rc  r  r  r   r6   )rq  r  r~  r  r,  privatePostOpenOrdersrM  r8  rY  r(  r)  r*  r+  r1  parse_orders)r  r  r  r  r5  rt  rb  rd  r6  r8  r  r  r  r  r7  r6   r  s                    r  fetch_open_orderszkraken.fetch_open_orders	  sh    	#00>GG##FI6!(GIYYvy1F((A$#0GK YYv7F--dkk'6.JKL [[(F(B7~~ffb1		$q#h-( 	9A!B8DMM$++tRj$78	9   >>r  c                    | j                          i }|| j                  |dz        |d<   | j                  |d      }|||d<   | j                  |d      }| j	                  |d      }|||d<   | j                  |d      }| j                  d||      \  }}| j                  | j                  ||            }d}	|| j                  |      }	| j                  |di       }
| j                  |
d	i       }g }t        |j                               }t        d
t        |            D ]/  }||   }||   }|j                  | j                  d|i|             1 | j                  ||	||      S )a  
        fetches information on multiple closed orders made by the user

        https://docs.kraken.com/api/docs/rest-api/get-closed-orders

        :param str [symbol]: unified market symbol of the market orders were made in
        :param int [since]: the earliest time in ms to fetch orders for
        :param int [limit]: the maximum number of order structures to retrieve
        :param dict [params]: extra parameters specific to the exchange API endpoint
        :param int [params.until]: timestamp in ms of the latest entry
        :param str [params.clientOrderId]: the orders client order id
        :param int [params.userref]: the orders user reference id
        :returns Order[]: a list of `order structures <https://docs.ccxt.com/#/?id=order-structure>`
        Nr>   r  rb  rd  rc  r  r  rD  r   r6   )rq  r  r~  r  r,  handle_until_optionprivatePostClosedOrdersrM  r8  rY  r(  r)  r*  r+  r1  r  )r  r  r  r  r5  rt  rb  rd  r6  r8  r  rD  r  r  r7  r6   r  s                    r  fetch_closed_orderszkraken.fetch_closed_orders	  s    	#00>GG##FI6!(GIYYvy1F((A$#0GK YYv7F225'6J//GV0LMP [[(F(B7"5&q#h-( 	9A!B":DMM$++tRj$78	9   >>r  c                 :    ddddddd}| j                  |||      S )NrG  rS  failed)InitialPendingSuccessSettledFailurePartialr  rH  s      r  parse_transaction_statuszkraken.parse_transaction_status=
  s4     !  
 &&99r  c                 b    | j                  | j                  di       }| j                  |||      S )Nr  )r'  r   r,  )r  networkr  s      r  parse_networkzkraken.parse_networkI
  s.    //$,,8I2N'BBr  r  c                    | j                  |d      }| j                  |d      }| j                  |d      }| j                  |d      }| j                  ||      }| j                  |d      }| j                  |d      }	| j	                  | j                  |d            }
| j                  |d      }|d	k(  }|d
k(  }|dk(  }|s|s|rd}
| j                  |d      }| j                  |d      }||dk(  rd}i d|d|d|d|	d| j                  | j                  |d            d|dd dd dd dd dd d|
d|dd d|d|d| j                  |      d d ||ddS )Nr  r^  r  r  r$  r  r  zstatus-propzon-holdzcancel-pendingonholdrG  r  r  rb  r   r6   rD  r  address	addressToaddressFromtagtagTotagFromrU  r  r  )rD  r  )commentinternalr  )r,  r  r-  r2  r  r  r  )r  r  rD  r6   r^  r  rK  ra  r  r  r  
statusPropisOnHoldDepositisCancellationRequestisOnHoldWithdrawalr  rx  s                    r  parse_transactionzkraken.parse_transactionM
  s"   z k73V4''V<	%%k7;
&&z8<"";7!!+x8..t/?/?X/VW%%k=A
$	1 *.> >'8337IFV4"";6?y 
K
"
 
 f	

 t))$*:*:;	*RS
 w
 
 4
 4
 T
 t
 f
 D
 t
 D
  !
" Y/#
$  )
 	
r  c                     g }t        dt        |            D ]9  }| j                  | j                  d|i||               }|j	                  |       ; | j                  ||||      S )Nr   r  )r*  r+  r  rM  r1  filter_by_currency_since_limit)	r  r  transactionsra  r  r  r  r7  r  s	            r  parse_transactions_by_typez!kraken.parse_transactions_by_type
  su    q#l+, 	'A00>A2  !K MM+&		'
 2264NNr  c                    | j                          i }|| j                  |      }|d   |d<   |*| j                  |      }t        j                  |d      |d<   | j                  |ddg      }|C| j                  |ddg      }t        j                  |d      }	t        j                  |	d      |d<   | j                  | j                  ||            }
| j                  d	|
d
   |||      S )a  
        fetch all deposits made to an account

        https://docs.kraken.com/rest/#tag/Funding/operation/getStatusRecentDeposits

        :param str code: unified currency code
        :param int [since]: the earliest time in ms to fetch deposits for
        :param int [limit]: the maximum number of deposits structures to retrieve
        :param dict [params]: extra parameters specific to the exchange API endpoint
        :param int [params.until]: timestamp in ms of the latest transaction entry
        :param int [params.end]: timestamp in seconds of the latest transaction entry
        :returns dict[]: a list of `transaction structures <https://docs.ccxt.com/#/?id=transaction-structure>`
        r6   r  r  r  r  r  r  r  rb  r  )rq  rD  r  r1   r/  r  r  r  privatePostDepositStatusrM  r  )r  ra  r  r  r5  rt  rD  sinceStringr  r  r6  s              r  fetch_depositszkraken.fetch_deposits
  s     	}}T*H'~GG//6K&11+vFGG""6GV+<=YYv'89F"--eV<L$//cBGEN00Wf1MN ..y(8:LdTY[`aar  c                 n    | j                  |      }| j                  |di       }| j                  |d      S )ag  
        fetches the current integer timestamp in milliseconds from the exchange server

        https://docs.kraken.com/rest/#tag/Spot-Market-Data/operation/getServerTime

        :param dict [params]: extra parameters specific to the exchange API endpoint
        :returns int: the current integer timestamp in milliseconds from the exchange server
        r  unixtime)publicGetTimer'  r  )r  r5  r6  r  s       r  
fetch_timezkraken.fetch_time
  s;     %%f- 8R8""6:66r  c           	         | j                          d}| j                  |dd      \  }}|rd|d<   | j                  d||||dd      S i }|| j                  |      }|d   |d	<   |*| j	                  |      }t        j                  |d
      |d<   | j                  |ddg      }	|	C| j                  |ddg      }t        j                  |	d
      }
t        j                  |
d      |d<   | j                  | j                  ||            }d}| j                  |d      }t        |t              s| j                  |      }n|}| j!                  d||||      S )a[  
        fetch all withdrawals made from an account

        https://docs.kraken.com/rest/#tag/Funding/operation/getStatusRecentWithdrawals

        :param str code: unified currency code
        :param int [since]: the earliest time in ms to fetch withdrawals for
        :param int [limit]: the maximum number of withdrawals structures to retrieve
        :param dict [params]: extra parameters specific to the exchange API endpoint
        :param int [params.until]: timestamp in ms of the latest transaction entry
        :param int [params.end]: timestamp in seconds of the latest transaction entry
        :param boolean [params.paginate]: default False, when True will automatically paginate by calling self endpoint multiple times
        :returns dict[]: a list of `transaction structures <https://docs.ccxt.com/#/?id=transaction-structure>`
        Fr   r  Tcursornext_cursorNr6   r  r  r  r  r  r  r  r  r  )rq  r  fetch_paginated_call_cursorrD  r  r1   r/  r  r  r  privatePostWithdrawStatusrM  r'  r  r(  add_pagination_cursor_to_resultr  )r  ra  r  r  r5  r  rt  rD  r  r  r  r6  rawWithdrawalsr  s                 r  fetch_withdrawalszkraken.fetch_withdrawals  sz    	88ASU_`&#F8334FeUZ\bdqs{||}}T*H'~GG//6K&11+vFGG""6GV+<=YYv'89F"--eV<L$//cBGEN11$++gv2NON 84&$'!AA&IN#N..|^TSXZ_``r  c                     | j                  |d      }| j                  |d      }t        |      }||dkD  r||dz
     }||d<   |||dz
  <   |S )Nr	  withdrawalsr   r   )r,  r'  r+  )r  r  r  data
dataLengthr  s         r  r  z&kraken.add_pagination_cursor_to_resultS  sd    !!&-8v}5Y
*q.
Q'D"(D#'Da r  c                 N    ddi}| j                  || j                  ||            S )a  
        create a currency deposit address

        https://docs.kraken.com/rest/#tag/Funding/operation/getDepositAddresses

        :param str code: unified currency code of the currency for the deposit address
        :param dict [params]: extra parameters specific to the exchange API endpoint
        :returns dict: an `address structure <https://docs.ccxt.com/#/?id=address-structure>`
        newr  )fetch_deposit_addressrM  )r  ra  r5  rt  s       r  create_deposit_addresszkraken.create_deposit_address]  s0     6
 ))$GV0LMMr  c                     | j                          | j                  |      }d|d   i}| j                  | j                  ||            }| j	                  |d      S )aO  
        fetch deposit methods for a currency associated with self account

        https://docs.kraken.com/rest/#tag/Funding/operation/getDepositMethods

        :param str code: unified currency code
        :param dict [params]: extra parameters specific to the kraken api endpoint
        :returns dict: of deposit methods
        r  r6   r  )rq  rD  privatePostDepositMethodsrM  r'  )r  ra  r5  rD  rt  r6  s         r  fetch_deposit_methodszkraken.fetch_deposit_methodsl  s^     	==&Xd^
 11$++gv2NO0 x22r  c                    | j                          | j                  |      }| j                  |d      }| j                  | j                  di       }| j                  |||      }| j                  |d      }|dk(  r|dk(  r|dz   |z   }| j                  | j                  di       }| j                  ||      }| j                  |d|      }|| j                  |      }	|Gt        dt        |	            D ]/  }
| j                  |	|
   d      }|j                  |      dk\  s-|} n |%| j                  |	di       }| j                  |d      }|d	   |d
}| j                  | j                  ||            }| j                  |dg       }| j                  |di       }|t        | j                  dz   |z         | j                  ||      S )a  
        fetch the deposit address for a currency associated with self account

        https://docs.kraken.com/rest/#tag/Funding/operation/getDepositAddresses

        :param str code: unified currency code
        :param dict [params]: extra parameters specific to the exchange API endpoint
        :returns dict: an `address structure <https://docs.ccxt.com/#/?id=address-structure>`
        r  r  r[  r   r  r  r}  r   r6   )r  r}  r  z9 privatePostDepositAddresses() returned no addresses for )rq  rD  safe_string_upperr'  r   r,  r  r  r*  r+  r.  privatePostDepositAddressesrM  r%   r6   parse_deposit_address)r  ra  r5  rD  r  r  defaultDepositMethodsdefaultDepositMethoddepositMethodr  r7  entryfirstDepositMethodrt  r6  r  firstResults                    r  r  zkraken.fetch_deposit_address  s    	==&((;??4<<R@""8Wg>69-FNG!3#:'D $>NPR S#//0EtL((;OP  !77=N"q#n"56 A ,,^A->IEzz'*a/(-	 $%)__^Q%K" $ 0 01CX Nd^#
 33DKK4PQ 8R8oofa4 +f!fim!mnn))+x@@r  c                     | j                  |d      }| j                  |d      }| j                  d |      }|d   }| j                  |       ||d ||dS )Nr  r  ra  )r$  rD  r  r  r  )r,  rJ  check_address)r  depositAddressrD  r  r  ra  s         r  r  zkraken.parse_deposit_address  sk     "">9=~u5%%dH57#"
 	
r  r  c                 f   | j                  ||      \  }}| j                  |       d|v rp| j                          | j                  |      }|d   ||d}| j	                  | j                  ||            }| j                  |di       }	| j                  |	|      S t        | j                  dz         )a  
        make a withdrawal

        https://docs.kraken.com/rest/#tag/Funding/operation/withdrawFunds

        :param str code: unified currency code
        :param float amount: the amount to withdraw
        :param str address: the address to withdraw to
        :param str tag:
        :param dict [params]: extra parameters specific to the exchange API endpoint
        :returns dict: a `transaction structure <https://docs.ccxt.com/#/?id=transaction-structure>`
        r  r6   )r  r  r  r  zO withdraw() requires a 'key' parameter(withdrawal key name, up on your account))
handle_withdraw_tag_and_paramsr%  rq  rD  privatePostWithdrawrM  rY  r  r   r6   )
r  ra  r  r  r  r5  rD  rt  r6  r  s
             r  r   zkraken.withdraw  s     99#vFV7#F?}}T*H!$ "G
 //GV0LMH ^^Hh;F))&(;;DGG&wwxxr  c                     | j                          ddd}| j                  | j                  ||            }| j                  |      }| j	                  |d      }| j                  ||      }| j                  |d|d      S )a  
        fetch all open positions

        https://docs.kraken.com/rest/#tag/Account-Data/operation/getOpenPositions

        :param str[] [symbols]: not used by kraken fetchPositions()
        :param dict [params]: extra parameters specific to the exchange API endpoint
        :returns dict[]: a list of `position structure <https://docs.ccxt.com/#/?id=position-structure>`
        r  r8  )docalcsconsolidationr  r  F)rq  privatePostOpenPositionsrM  r  r  parse_positionsfilter_by_array_positions)r  r  r5  rt  r6  r  resultss          r  fetch_positionszkraken.fetch_positions  s     	 %

 00Wf1MN\ %%g.(3&&vw7--gx%PPr  positionc                    | j                  |d      }| j                  |d      }|dk(  rdnd}| j                  i d|dd d| j                  ||      d	d d
d dd dd d| j                  |d      dd dd d| j                  |d      dd dd dd d|dd dd d d d d d | j                  |d      d | j                  |d      d d d d      S )Nrp  r  r   longshortr$  r6   r  notionalr  liquidationPrice
entryPriceunrealizedPnlnetrealizedPnlr   	contractsr  r  	markPrice	lastPricer  r  r  rD   r  )r  lastUpdateTimestampmaintenanceMarginmaintenanceMarginPercentage
collateralinitialMargininitialMarginPercentager  marginRatior  r  )r,  safe_positionr  r2  )r  r2  r8  r  rawSider  s         r  parse_positionzkraken.parse_positionG  s    ##Hf5""8V4!U*v!! #
H#
$#
 d&&x8#
 	#

 $#
 #
 $#
 T--h>#
 4#
 $#
 ))(E:#
 D#
 #
 #
 D#
  d!#
" ##
$ #'!%+/!--hA'+((:>!#9#
  	r  c                 4    dddd}| j                  |||      S )NSpot WalletzFutures Walletr  r  )r  r  accountByTypes      r  parse_account_typezkraken.parse_account_typew  s)    !$&

 w@@r  c                 ,    | j                  ||dd|      S )a  
        transfer from spot wallet to futures wallet

        https://docs.kraken.com/rest/#tag/User-Funding/operation/walletTransfer

        :param str code: Unified currency code
        :param float amount: Size of the transfer
        :param dict [params]: Exchange specific parameters
        :returns: a `transfer structure <https://docs.ccxt.com/#/?id=transfer-structure>`
        rC   rE   )r   )r  ra  r  r5  s       r  transfer_outzkraken.transfer_out  s     }}T6666BBr  fromAccount	toAccountc                    | j                          | j                  |      }| j                  |      }| j                  |      }| j                  ||      |||d   d}|dk7  r$t	        | j
                  dz   |z   dz   |z   dz         | j                  | j                  ||            }| j                  ||      }	| j                  |	|||d      S )a  

        https://docs.kraken.com/rest/#tag/User-Funding/operation/walletTransfer

        transfers currencies between sub-accounts(only spot->swap direction is supported)
        :param str code: Unified currency code
        :param float amount: Size of the transfer
        :param str fromAccount: 'spot' or 'Spot Wallet'
        :param str toAccount: 'swap' or 'Futures Wallet'
        :param dict [params]: Exchange specific parameters
        :returns: a `transfer structure <https://docs.ccxt.com/#/?id=transfer-structure>`
        r6   )r  fromtor  rJ  z transfer cannot transfer from z to zA. Use krakenfutures instead to transfer from the futures account.)r  rO  rP  )	rq  rD  rL  currency_to_precisionr"   r6   privatePostWalletTransferrM  parse_transfer)
r  ra  r  rO  rP  r5  rD  rt  r6  r   s
             r  r   zkraken.transfer  s     	==&--k:++I6	00v>d^	
 -'TWW'HH;VY__bkk  or  r  s  s11$++gv2NO &&x:{{8&"&
  	r  r   c           
          | j                  |di       }| j                  |d      }||d d | j                  |d      d d d dd	S )Nr  r  ra  sucess)	r$  r6   r  r  rD  r  rO  rP  r  )r'  r,  )r  r   rD  r  r  s        r  rV  zkraken.parse_transfer  sZ     8R8  1((6:

 
	
r  r   GETc                 \   d| j                   z   dz   |z   dz   |z   }|dk(  r|rn|d| j                  |      z   z  }nU|dk(  rJ| j                  |d      }d}	||j                  d      rdnd}	|d	k(  }
| j	                          t        | j                               }|
s|	r$| j                  | j                  d
|i|            }n#| j                  | j                  d
|i|            }| j                  ||z         }| j                  |dd      }| j                  |      }| j                  ||      }| j                  | j                        }| j                  ||t        j                   d      }| j"                  |d}|
s|	rd|d<   nd|d<   nd|z   }| j$                  d   |   |z   }||||dS )Nr
  r   ?r   r  FrX  Tr   noncesha256binarybase64)zAPI-KeyzAPI-Signzapplication/jsonzContent-Typez!application/x-www-form-urlencodedr   )rW  r}  bodyheaders)r;   urlencode_nestedr,  rk  check_required_credentialsr	  r\  jsonrM  encodehashbinary_concatbase64_to_binarysecrethmachashlibsha512apiKeyr   )r  pathr   r}  r5  ra  r`  rW  r  isTriggerPercentisCancelOrderBatchr\  authrf  r^  binhashri  	signatures                     r  signzkraken.sign  s   DLL 3&,s2T9(?sT226:::I$$VW5E$ ,1NN3,?4e "&*<"<++-

%E!%5yygu-=v!FG,,T[['59I6-RS;;ut|,D99T8X6D[[%F((6G**4;;7F		'67>>8LI;;%G "%5*<'*M'*Ciis#c)fdwOOr  c                 B    | j                         | j                  d   z
  S )Nr  )millisecondsr   )r  s    r  r\  zkraken.nonce  s       "T\\2B%CCCr  reasonrW  ra  r`  c
                    |dk(  r*t        | j                  dz   t        |      z   dz   |z         |y |d   dk(  rt        |t              sd|v rt	        |d         }
|
r| j                  dz   |z   }t        dt	        |d               D ]J  }|d   |   }| j                  | j                  d   ||       | j                  | j                  d   ||       L t        |      y )Ni  rT  r   {errorr  r  )	r+   r6   r	  r  r+  r*  throw_exactly_matched_exceptionr  r   )r  ra  rw  rW  r}  ra  r`  r6  requestHeadersrequestBody	numErrorsmessager7  rz  s                 r  handle_errorszkraken.handle_errors  s    3;&tww}s4y'@3'F'OPP7c>h,h& #HW$5 6I "&''C-$"6!&q#hw.?*@!A kA$,W$5a$8E @@QXAY[`bij @@QXAY[`bijk ,G44r  )N)r   r   r}  )NNN)e__name__
__module____qualname__r   r  r  r   r   rC  r   rJ  r3  r[  r   ri  r   r-  r	  r   ru  rs  r
   r  r   r   r  dictr   r  r   r   r  r  r(  r  r  r  r   r  r  r  r  r   r  r  r   r#  r&  r   floatr*  r,  r   r   r(  r
  r  rJ  rQ  r   r7  r5  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   r1  rH  rL  rN  r   r   rV  rt  r\  intr  __classcell__)r  s   @r  r3   r3   "   so   J# JXy $& P$v, PdG( G4 #% 
4 ') zZ zx	LS 	LH 	LPS 	L 57 /6 /6;N /6b
*i *	 *en * :>b 08s 083 08Y 08d/4 / /6 /b 04B GW G7 GB 02 13 1f 1,
 
4 
, 26DW[df 0J# 0Jc 0JQT 0Jkoptku 0Jd33t 3x 3; 3j (,$TZ\ /@ /@C /@s /@aefqar /@b <@ (S (6 7;2 S  + s sv s sj 6:UW .?3 .?s .?# .?\`af\g .?`) )$ $& ,( ,8 _a _C _y _PU _& RT O O5 O gksu 2(3 2(i 2(y 2(RW 2(`c 2(h(B: :	:n nv n n` kowy b!C b! b!C b!$ b!X[ b!dg b!H `drv  @B @0S @0# @0Y @0i @0Y\ @0lo @0D 26b ?Ec ?E3 ?EB 9=4^bkm GS G# GS GX[ GR 6:" s 4 -1tRV_a A?c A? A?C A?F 37r *s *C *X 04B 
 
: /32 
 
4 <> s 8 /3TXac K? K?3 K?c K?hlmrhs K?Z 154VZce O?# O?S O?PS O?jnotju O?b
:s 
:Ch
T h
X h
Q\ h
TO3 OVY Oil O *.Dt\^ *b3 *bc *b *bcghsct *bX !# 7s 7. -1tRV_a Nac Na NaC Nafjkvfw Na` 8: N3 Nn N 79 '3# '3R 79 5A# 5A^ 5An
h 
R` 
( DHPR "yS "y% "y# "yWb "yH 26b AQw AQT(^ AQF.t .V .`A 68 C C [] (S (% (c (c (an (T
t 
x 
= 
4 &eBSW $PLD# s  c TX `c r  r3   )8ccxt.base.exchanger   ccxt.abstract.krakenr   rk  ccxt.base.typesr   r   r   r   r	   r
   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   typingr   ccxt.base.errorsr   r   r   r    r!   r"   r#   r$   r%   r&   r'   r(   r)   r*   r+   r,   r-   r.   ccxt.base.decimal_to_precisionr/   r0   ccxt.base.preciser1   r3    r  r  <module>r     s    ( ,  C  C  C  C  C  C  C  * 0 - - . ' & . + ) * ) + . 1 * ) * 3 4 %g3X{ g3r  