
    !:h                    |   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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l0m1Z1 d dl2m3Z3  G d dee      Z4y)    )Exchange)ImplicitAPIN)AnyBalancesCurrencyIntLeverage	LeveragesLeverageTierLeverageTiersMarketNumOrder	OrderBookOrderRequest	OrderSide	OrderTypePositionStrStringsTickerTickersFundingRateFundingRatesTradeTransferEntry)List)ExchangeError)AuthenticationError)ArgumentsRequired)
BadRequest)InsufficientFunds)InvalidOrder)OrderNotFound)OrderImmediatelyFillable)OrderNotFillable)DuplicateOrderId)ContractUnavailable)DDoSProtection)RateLimitExceeded)ExchangeNotAvailable)InvalidNonce)	TICK_SIZE)Precisec                   8    e Zd Zdef fdZi fdee   fdZdi fdede	de
fdZdi fdedefd	ZdPd
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dPdedefdZddi fdede	de	dee   fdZdPdededefdZdi fdededededef
dZdi fdededededef
dZi fdee   fdZddi fdedededededefdZ di fdede!fdZ"di fdee   de!fd Z#di fde!fd!Z$i fd"e	fd#Z%dddi fde!de	de	dee&   fd$Z'dddi fde!de	de	dee&   fd%Z(dddi fde!de	de	dee&   fd&Z)d' Z*g fd(Z+d)e!fd*Z,dPd+edede&fd,Z-dddi fde!de	de	fd-Z.i fde/fd.Z0de/fd/Z1di fdede2fd0Z3dPdede4fd1Z5dddi fde!de	de	fd2Z6di fdedee7   fd3Z8di fdefd4Z9dPd5edefd6Z:di fdede;fd7Z<dPdedee=   fd8Z>dPd9ed:e?de@fd;ZAd< ZBi fd=efd>ZCi fd=eded?ed@ede@f
dAZDdi fdBe	de!fdCZEdi fdedeFfdDZGi fdedeHfdEZIdPdBededeHfdFZJd=eKdGedHedIedJedKefdLZLdMdNi ddfdOZM xZNS )Qkrakenfutures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/d0dd1dd2di d3dd4dd5dd6dd7dd8dd9d/d:dd;dd<dd=dd>dd?dd@ddAddBddCddddddddDdEdFdFdGdHdIdJdKdLdMdNdOdOdPdQdRgdSd dTdUdVg dWig dXg dYdZd[gd\dVd]gidVg d^id_d`dadd| j	                  db      | j	                  dc      | j	                  dd      | j	                  db      g| j	                  de      | j	                  df      g| j	                  dg      | j	                  dh      g| j	                  di      | j	                  dj      g| j	                  dk      | j	                  dc      g| j	                  dl      | j	                  dm      g| j	                  dn      | j	                  do      g| j	                  dp      | j	                  dq      gg| j	                  dd      | j	                  dc      g| j	                  de      | j	                  dr      g| j	                  dg      | j	                  do      g| j	                  di      | j	                  dq      g| j	                  dk      | j	                  ds      g| j	                  dl      | j	                  dt      g| j	                  dn      | j	                  du      g| j	                  dp      | j	                  dd      ggdvdwidxi dyt
        dzt        d{t        d|t        d}t        d~t        dt        dt        dt        dt        dt        dt        dt        dt        dt        dt        dt        dt        it        t        t        dddt        ddddddddiidg diddgdddddiidd]diiddddddidddi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ddidd d dddd dd ddddd dd d d d ddddddid	d ddiddidddiddiddddddddddddd	      S )Nidr0   namezKraken Futures	countriesUSversionv3	userAgent	rateLimitiX  proThasCORSspotFmarginswapfutureoptioncancelAllOrderscancelAllOrdersAftercancelOrdercancelOrderscreateMarketOrdercreateOrdercreatePostOnlyOrdercreateReduceOnlyOrdercreateStopLimitOrdercreateStopMarketOrdercreateStopOrdercreateTriggerOrder	editOrderfetchBalancefetchBorrowRateHistoriesfetchBorrowRateHistoryfetchCanceledOrdersfetchClosedOrdersfetchCrossBorrowRatefetchCrossBorrowRatesfetchDepositAddressfetchDepositAddressesfetchDepositAddressesByNetworkfetchFundingHistoryfetchFundingRateemulatedfetchFundingRateHistoryfetchFundingRatesfetchIndexOHLCVfetchIsolatedBorrowRatefetchIsolatedBorrowRatesfetchIsolatedPositionsfetchLeveragefetchLeveragesfetchLeverageTiersfetchMarketLeverageTiersfetchMarketsfetchMarkOHLCVfetchMyTrades
fetchOHLCVfetchOpenOrders
fetchOrderfetchOrderBookfetchOrdersfetchPositionsfetchPremiumIndexOHLCV)fetchTickersfetchTradessandboxsetLeveragesetMarginModetransferurlsz0https://demo-futures.kraken.com/derivatives/api/z+https://demo-futures.kraken.com/api/charts/z,https://demo-futures.kraken.com/api/history/zhttps://demo-futures.kraken.com)publicprivatechartshistorywwwzdhttps://user-images.githubusercontent.com/24300605/81436764-b22fd580-9172-11ea-9703-742783e6376d.jpgz&https://futures.kraken.com/api/charts/z'https://futures.kraken.com/api/history/z,https://futures.kraken.com/api/feeschedules/z+https://futures.kraken.com/derivatives/api/)rz   r{   feeschedulesrx   ry   zhttps://futures.kraken.com/z-https://docs.futures.kraken.com/#introductionzihttps://support.kraken.com/hc/en-us/articles/360022835771-Transaction-fees-and-rebates-for-Kraken-Futures)testlogoapir|   docfeesreferralr   get)r}   instruments	orderbooktickersr{   historicalfundingrates)zfeeschedules/volumesopenpositionsnotificationsaccounts
openordersrecentordersfills	transfersleveragepreferencespnlpreferenceszassignmentprogram/currentzassignmentprogram/history)
	sendorder	editordercancelorderrv   
batchordercancelallorderscancelallordersafter
withdrawalzassignmentprogram/addzassignmentprogram/deleter   r   )r   postputz {price_type}/{symbol}/{interval})orders
executionstriggersaccountlogcsvzaccount-logzmarket/{symbol}/orderszmarket/{symbol}/executions)rx   ry   rz   r{   r   tradingz0.0005z0.00020100000z0.00041000000z0.00035000000z0.000251000000020000000z0.0001550000000z0.000125	100000000z0.0001z0.0015z0.000075z0.00005z0.000025)takermaker)	tierBased
percentager   r   tiers
exceptionsapiLimitExceededmarketUnavailablerequiredArgumentMissingunavailableauthenticationErroraccountInactiveinvalidAccountinvalidAmountinsufficientFundszBad RequestUnavailableinvalidUnitzJson Parse ErrornonceBelowThresholdnonceDuplicatenotFoundzServer ErrorunknownError)invalidArgumentr   r   )exactbroadprecisionModeoptionsr{   GETry   )r   r   r   r   flex)USDTBTCUSDGBPEURUSDCr   XBT)quoteIdsreversedr   v4v1v2)rx   rz   r{   method historyGetMarketSymbolExecutions)accesssettlementCurrenciessymbolversionsrr   features)lastmarkindex)IOCFOKPOGTD)
marginModetriggerPricetriggerPriceTypetriggerDirectionstopLossPricetakeProfitPriceattachedStopLossTakeProfittimeInForcehedgedtrailingleveragemarketBuyByCostmarketBuyRequiresPriceselfTradePreventionicebergmaxd   i )r   limitdaysBack	untilDayssymbolRequired)r   r   triggerr   r   )r   r   r   daysBackCanceledr   r   r   r   r     )	rs   rH   createOrdersri   rl   rk   rn   rT   rj   extendsdefault)linearinverse)r   r>   r@   rA   
timeframes1m5m15m30m1h4h12h1d1w)	r   r   r   r   r   r  r  r  r  )deep_extendsuperr0   describeparse_numberr*   r(   r!   r+   r   r   r"   r,   r-   )self	__class__s    L/var/www/html/turnos/venv/lib/python3.12/site-packages/ccxt/krakenfutures.pyr  zkrakenfutures.describe    s$	   mT C E UH
/UH
$UH
 $UH
 t	UH

 UH
 UH
 4UH
  ::: %: 	:
 $: %: "4: ': t: : $U: t: &t: (: ':  (!:" "4#:$ %d%:& T':( ):* +E+:, )%-:. &t/:0 $T1:2 '3:4 (5:6 &u7:8 (9:: 1%;:< &t=:> #J?:@ *4A:B $TC:D "5E:F *5G:H +EI:J )%K:L  M:N !$O:P %dQ:R +JS:T U:V !$W:X  Y:Z d[:\ "4]:^ e_:` !$a:b uc:d !$e:f )%g:h !%##!& s:UH
F PQKM< FH$RKL 5C D +GUH
t  	 .(7B :  
a;uUH
l !%"&!..x8!..x8 "..s3T5F5Fx5PQ!..x8$:K:KH:UV!..y94;L;LX;VW!..y94;L;LY;WX!..z:D<M<Mh<WX!..z:D<M<Mi<XY!..z:D<M<Mj<YZ!..{;T=N=Nx=XY	" "..s3T5F5Fx5PQ!..x8$:K:KH:UV!..y94;L;LZ;XY!..y94;L;LX;VW!..z:D<M<Mj<YZ!..z:D<M<Mi<XY!..z:D<M<Mj<YZ!..{;T=N=Ns=ST	"mUH
h &(9')< .z "#7	
 *+> &} %j $Z (): ": "#7 ": ' *< %l  
!" #M#$ #M%* (2+7&2+iUH
^ Y_UH
` &/*3(1-6	  	 H) "' % 4d  >  &**.(,-1	  * @ M)aUH
t #&+(,$($(%)-
 -2)-+/6:#'#'"&#(	( #($)$)+027/4#(1$6 s% ',!%$(%+*/& #'&+!%#($)*/( $(&+!%$(,0%)#($)*/	*  #s<z  "9 "9 	 "9 "9 	OOuUH
T
 
U
UH
 U U	    c                    | j                  |      }| j                  |dg       }g }t        dt        |            D ]>  }||   }| j	                  |d      }| j	                  |d      }d}	|j                  d      dk\  }
d}d}d}|
sA|j                  d      dk\  }| }| j	                  |d      }|d	nd
}	| j                  |      }nd}	|	d	k(  }|	d
k(  }|}|j                  d      }| j	                  |d      }|dt        |      dz
   }d}| j                  |      }| j                  |      }d}d}| j	                  |d      }| j                  | j                  |            }| j                  |d      }|xs |xs |
}|xs |}|rN| j	                  |d      }|dk(  r|}|}d}n|}|}d}| }|dz   |z   dz   |z   }|r|dz   | j                  |      z   }|j                  i d|d|d|d|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d&ddd&ddd&ddd&d'| j                  | j	                  |d(            |d)       A | j                  d*   d+   } g }!t        dt        |             D ]+  }| |   }"|!j                  |"j!                         d|"dd,       - | j#                  |!| j$                        | _        |S )-ap  
        Fetches the available trading markets from the exchange, Multi-collateral markets are returned markets, but can be settled in multiple currencies

        https://docs.futures.kraken.com/#http-api-trading-v3-api-instrument-details-get-instruments

        :param dict [params]: exchange specific params
        :returns: An array of market structures
        r   r   r   typeNz index_vanillalastTradingTimer@   rA   r   _      usdcontractValueTradePrecisiontickSizefutures_inverseTF/:-r3   basequotesettlebaseIdquoteIdsettleIdr>   r?   rB   activecontractcontractSize)amountprice)minr   )r   r$  r%  costopeningDate)r   r   r#  maintenanceMarginRateexpiryexpiryDatetimestrike
optionType	precisionlimitscreatedinfor   r   )r3   	numericIdcoder.  )publicGetInstruments
safe_valuerangelensafe_stringfind	parse8601splitsafe_currency_coder  integer_precision_to_amountsafe_numberyymmddappendiso8601r   lowerr  
currencies)#r	  paramsresponser   resultimarketr3   
marketTyper  r   r   r   r*  
settleTimer@   rA   r   r;  splitMarketr  r  r  r  r  r   cvtpamountPrecisionpricePrecisionr"  swapOrFuturesexchangeTyper   rC  r3  s#                                      r  fetch_marketszkrakenfutures.fetch_marketsx  s1    ,,V4Z oohrBq#k*+ b	A ^F!!&(3B))&&9JD__X.!3EFGF$//*5:$*!--f6GH
","4v8
3FNDh&FFHHSME**5!4K 3{#3a#78FG**62D++G4EFH##F,IJD"//0P0PQU0VWO!--fjAN//%H!^VM#//?#44!F%H"G"F&H#G$e+c1F:#c\DKK,??FMM 2b2&2 2 	2
 &2 &2 72 H2 2 2 %2 2 &2 %2 2  $!2" H#2$ !" $ 0 0 H)- "&,,v"6"-+  $#!
  $#
  $#
  $#$  >>$*:*:6=*QRc2 2ab	F  $||,BCFK
q#234 	A'*Djjl!!	 	 **:tGr  Nr   r   c                     | j                          | j                  |      }d|d   i}| j                  | j                  ||            }| j	                  |d         }| j                  |d   ||      S )a  

        https://docs.futures.kraken.com/#http-api-trading-v3-api-market-data-get-orderbook

        Fetches a list of open orders in a market
        :param str symbol: Unified market symbol
        :param int [limit]: Not used by krakenfutures
        :param dict [params]: exchange specific params
        :returns: An `order book structure <https://docs.ccxt.com/#/?id=order-book-structure>`
        r   r3   
serverTime	orderBook)load_marketsrH  publicGetOrderbookextendr:  parse_order_book)r	  r   r   rD  rH  requestrE  	timestamps           r  fetch_order_bookzkrakenfutures.fetch_order_book   sz     	V$fTl
 **4;;w+GH> NN8L#9:	$$Xk%:FINNr  symbolsc                     | j                          | j                  |      }| j                  |d      }| j                  ||      S )a#  
        fetches price tickers for multiple markets, statistical information calculated over the past 24 hours for each market

        https://docs.futures.kraken.com/#http-api-trading-v3-api-market-data-get-tickers

        :param str[] 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: an array of `ticker structures <https://docs.ccxt.com/#/?id=ticker-structure>`
        r   )rU  publicGetTickers	safe_listparse_tickers)r	  r\  rD  rE  r   s        r  fetch_tickerszkrakenfutures.fetch_tickersR  sF     	((0B ..95!!'733r  tickerrH  c           
         | j                  |d      }| j                  ||      }|d   }| j                  | j                  |d            }| j                  |d      }| j                  |d      }t        j                  ||      }t        j
                  t        j                  ||      d      }	t        j                  t        j                  ||      d      }
| j                  |d      }d }d }| j                  |dd	      }|s|d
   r|}n|d   r|}| j                  i d|d|d| j                  |      dd dd d| j                  |d      d| j                  |d      d| j                  |d      d| j                  |d      dd d|d|d|dd d|d|	d|
||| j                  |d      | j                  |d      |d      S ) Nr   lastTimeopen24hr   1002vol24hr   Fr   r   rZ  datetimehighlowbid	bidVolumebidSizeask	askVolumeaskSizevwapopenclosepreviousClosechanger   average	markPrice
indexPrice)
baseVolumequoteVolumerx  ry  r1  )r8  safe_marketr:  r.   
string_sub
string_mul
string_div
string_add	safe_boolsafe_tickerrA  )r	  rb  rH  marketIdr   rZ  rs  r   rv  r   rw  volumerz  r{  isIndexs                  r  parse_tickerzkrakenfutures.parse_ticker  sY   6 ##FH5!!(F3!NN4#3#3FJ#GH		2/##D$/''(:(:64(H%P
$$W%7%7d%CSI!!&(3
..%8h#
	"$ !
f!
!
 Y/!
 D	!

 4!
 4##FE2!
 ))&)<!
 4##FE2!
 ))&)<!
 D!
 D!
 T!
 D!
 T!
 f!
  *!!
" w#!
$ %&))&+>**6<@-!
  	r  r   sincec           	      0   | j                          | j                  |      }d}| j                  |dd      \  }}|r| j                  d|||||d      S |d   | j	                  |dd      | j
                  |   d}| j                  |d      }|s| j                  |      }	| j                  |d	z        |d
<   |d}t        |d      }| j                  |d
   ||	z  dz
        }
| j                         }t        |
|      |d<   nO|Mt        |d      }| j                  |      }	| j                         |d<   | j                  |d   |	|z  z
        |d
<   | j                  | j                  ||            }| j                  |d      }| j                  |||||      S )a  

        https://docs.futures.kraken.com/#http-api-charts-candles

        fetches historical candlestick data containing the open, high, low, and close price, and the volume of a market
        :param str symbol: unified symbol of the market to fetch OHLCV data for
        :param str timeframe: the length of time each candle represents
        :param int [since]: timestamp in ms of the earliest candle to fetch
        :param int [limit]: the maximum amount of candles to fetch
        :param dict [params]: extra parameters specific to the exchange API endpoint
        :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
        Frj   paginater   r3   r%  trade)r   
price_typeinterval  fromr  tocandles)rU  rH  handle_option_and_params"fetch_paginated_call_deterministicr8  r   omitparse_timeframeparse_to_intr&  sumseconds chartsGetPriceTypeSymbolIntervalrW  r_  parse_ohlcvs)r	  r   	timeframer  r   rD  rH  r  rY  durationtoTimestampcurrentTimestamprE  r  s                 r  fetch_ohlcvzkrakenfutures.fetch_ohlcv  s    	V$88zZ&::<QVX]_hjprvwwTl**67GD	2

 67+++I6H"//=GFO}t$E((76?EH4Dq4HIK#||~-=>GDMt$E++I6H LLNGDM"//EAQ0RSGFO88Wf9UV  ..95  &)UEJJr  c           	          | j                  |d      | j                  |d      | j                  |d      | j                  |d      | j                  |d      | j                  |d      gS )Ntimers  rj  rk  rt  r  )safe_integerr>  )r	  ohlcvrH  s      r  parse_ohlcvzkrakenfutures.parse_ohlcv  sn     eV,UF+UF+UE*UG,UH-
 	
r  c                 V   | j                          d}| j                  |dd      \  }}|r| j                  d||||      S | j                  |      }d|d   i}d}| j                  |ddd      \  }}d}	|dk(  }
|
r| j	                  d	||      \  }}|
||d
<   d|d<   |||d<   | j                  | j                  ||            }| j                  |dg       }g }	t        |      }t        d|      D ]Y  }|dz
  |z
  }||   }| j                  |di       }| j                  |di       }| j                  |di       }|	j                  |       [ nJ| j	                  d||      \  }}| j                  | j                  ||            }| j                  |dg       }	| j                  |	|||      S )a  

        https://docs.futures.kraken.com/#http-api-trading-v3-api-market-data-get-trade-history
        https://docs.futures.kraken.com/#http-api-history-market-history-get-public-execution-events

        Fetch a history of filled trades that self account has made
        :param str symbol: Unified CCXT market symbol
        :param int [since]: Timestamp in ms of earliest trade. Not used by krakenfutures except in combination with params.until
        :param int [limit]: Total number of trades, cannot exceed 100
        :param dict [params]: Exchange specific params
        :param int [params.until]: Timestamp in ms of latest trade
        :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)
        :param str [params.method]: The method to use to fetch trades. Can be 'historyGetMarketSymbolExecutions' or 'publicGetHistory' default is 'historyGetMarketSymbolExecutions'
        :returns: An array of `trade structures <https://docs.ccxt.com/#/?id=trade-structure>`
        Frr   r  r   r3   Nr   r   beforer  ascsortcountelementsr   r  event	Execution	executionrd  r{   )rU  r  fetch_paginated_call_dynamicrH  handle_until_optionr   rW  r_  r7  r6  	safe_dictr@  publicGetHistoryparse_trades)r	  r   r  r   rD  r  rH  rY  r   	rawTradesisFullHistoryEndpointrE  r  lengthrG  r   elementr  executionContainerrawTrades                       r  fetch_tradeszkrakenfutures.fetch_trades  s     	88PZ[&44]FESXZ`aaV$fTl
 66v}hXz{	!'+M!M "66x&QOGV #( "' #( <<T[[RX=YZHd ~~h
B?HI]F1f% +
Q"5/w<%)^^E;%K">>*<k2N  *+ #66z7FSOGV,,T[[&-IJH& xB?I  FE5AAr  r  c                 |   | j                  | j                  |dd            }| j                  |d      }| j                  |g dd      }| j                  |dd      }|| j                  |d      }| j                  |d	      }| j                  |d
      }| j                  |d      }	d }
| j	                  |d      }| j	                  |d      }|I| j                  |d      }| j                  |d
      }| j                  |d      }	| j                  |d      }
nJ|H| j                  |d      }| j                  |d
      }| j                  |d      }	| j                  |d      }
|
| j                  |
      }
| j                  ||      }d }| j                  |d      }|[|Y|W|rt        j                  ||      }nt        j                  ||      }| j                  |d      }t        j                  ||      }d }| j                  |d      }|-|j                  d      dk\  rd}n|j                  d      dk\  rd}d|v }|r;| j                  |d      }| j                  |di       }|| j                  |d      }	d}| j                  ||| j                  |d
      || j!                  |      ||
|	|||r|nd |d d      S )Nr  fillTimer%  )sizer$  quantity0.0uidfill_idexecutionIdorder_idr   sideorderPriorEditorderPriorExecutionorderIdr  r   r#  fillTyper   r   r   
takerOrderrZ  	direction)r1  r3   r   rZ  ri  orderr  r  takerOrMakerr%  r$  r'  fee)r:  safe_string_2r8  safe_string_nr5  parse_order_typer|  r  r.   r~  r  r9  r  r  safe_string_lower
safe_traderA  )r	  r  rH  rZ  r%  r$  r3   r  r  r  r  	priorEditpriorExecutionr'  r   r#  r  r  isHistoricalExecutionr   s                       r  parse_tradezkrakenfutures.parse_trade  s   D NN4#5#5eVZ#PQ	  0##E+I5Qui8:!!%7B  
3##E84v.OOE+;<	0EF%$$^Y?E''AH##NF;D##NF;D"$$Y	:E''	8<H##Iv6D##Iv6D((.D!!(F31U%6V=O))&%8))&%8++FNCL%%dL9D##E:6}}W%*&w'1,&!-!6 ))%=INN5,;E --e[A&&&vx8"Y/( &fD 
  	r  r  r  r$  r%  c                 t   | j                  |      }|d   }| j                  |d|      }| j                  |d      }d}	| j                  |dk(  |dk(  |      \  }	}|	rd}n|dk(  rd}n|dk(  rd	}n|dk(  rd
}|d   || j                  ||      d}
| j	                  |dd      }|||
d<   | j	                  |dd      }|d u}| j                  |d      }| j                  |d      }|d u}|d u}|xs |}| j                  |dd      }| j                  |d      }|s|r||
d<   |rd}| j                  ||      |
d<   n7|r5d}|rd}| j                  ||      |
d<   n|rd}| j                  ||      |
d<   |rd|
d<   ||
d<   || j                  ||      |
d<   | j                  |g d      }| j                  |
|      S )Nr   	orderTyper   FrH  r   iocr   lmtmktr3   )r   r  r  clientOrderIdcliOrdIdr   	stopPricer   r   triggerSignalr   
reduceOnlystpTtake_profit
limitPrice)r  r   r   r   r   )	rH  r8  handle_post_onlyamount_to_precisionr  r5  price_to_precisionr  rW  )r	  r   r  r  r$  r%  rD  rH  r   postOnlyrY  r  r   isTriggerOrderstopLossTriggerPricetakeProfitTriggerPriceisStopLossTriggerOrderisTakeProfitTriggerOrderisStopLossOrTakeProfitTriggerr  r  s                        r  create_order_requestz"krakenfutures.create_order_request  s4   V$!T:&&v}=001A46>SYZ&DE!DW_DXDTl,,VV<

 **6?JO$"/GJ))&.+N%T1#//H!%!1!1&:K!L!5T!A#9#E (>(ZBZ%((&I__V\:
(N'4GO$D#'#:#:6<#PGK *J%'+'>'>vG['\$)$'+'>'>vG]'^$$(GL!#$($;$;FE$JGL!6#wx{{7F++r  c                 &   | j                          | j                  |      }| j                  ||||||      }| j                  |      }	| j	                  |	d      }
| j                  |
d      }| j                  |ddg       | j                  |
|      S )aq  
        Create an order on the exchange

        https://docs.kraken.com/api/docs/futures-api/trading/send-order

        :param str symbol: unified market symbol
        :param str type: 'limit' or 'market'
        :param str side: 'buy' or 'sell'
        :param float amount: number of contracts
        :param float [price]: limit order price
        :param dict [params]: extra parameters specific to the exchange API endpoint
        :param bool [params.reduceOnly]: set if you wish the order to only reduce an existing position, any order which increases an existing position will be rejected, default is False
        :param bool [params.postOnly]: set if you wish to make a postOnly order, default is False
        :param str [params.clientOrderId]: UUID The order identity that is specified from the user, It must be globally unique
        :param float [params.triggerPrice]: the price that a stop order is triggered at
        :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.triggerSignal]: for triggerPrice, stopLossPrice and takeProfitPrice orders, the trigger price type, 'last', 'mark' or 'index', default is 'last'
        :returns dict: an `order structure <https://docs.ccxt.com/#/?id=order-structure>`
        
sendStatusstatusrH   filled)rU  rH  r  privatePostSendorderr5  r8  verify_order_action_successparse_order)r	  r   r  r  r$  r%  rD  rH  orderRequestrE  r  r  s               r  create_orderzkrakenfutures.create_orderF  s    * 	V$00tVUTZ[,,\:> __X|<
!!*h7((
K
F33r  r   c           	         | j                          g }t        dt        |            D ]  }||   }| j                  |d      }| j                  |d      }| j                  |d      }| j	                  |d      }	| j	                  |d      }
| j	                  |di       }| j                  ||      }d|vr| j                  |t        d	            |d<   d
|d<   | j                  ||||	|
|      }|j                  |        d|i}| j                  | j                  ||            }| j                  |dg       }| j                  |      S )a  
        create a list of trade orders

        https://docs.kraken.com/api/docs/futures-api/trading/send-batch-order

        :param Array orders: list of orders to create, each object should contain the parameters required by createOrder, namely symbol, type, side, amount, price and params
        :param dict [params]: extra parameters specific to the exchange API endpoint
        :returns dict: an `order structure <https://docs.ccxt.com/#/?id=order-structure>`
        r   r   r  r  r$  r%  rD  	order_tagr  sendr  
batchOrderbatchStatus)rU  r6  r7  r8  r5  rW  r  strr  r@  privatePostBatchorderr_  parse_orders)r	  r   rD  ordersRequestsrG  rawOrderr  r  r  r$  r%  orderParamsextendedParamsr  rY  rE  datas                    r  create_orderszkrakenfutures.create_orders  sU    	q#f+& 	0AayH''(;H##Hf5D##Hf5D__Xx8FOOHg6E//(HbAK![[f=N>1.2hhq#a&.A{+&,N7#44XtT6SXZhiL!!,/	0  .
 --dkk'6.JK" ~~hr:  &&r  r3   c                    | j                          d|i}|||d<   |||d<   | j                  | j                  ||            }	| j                  |	d   d      }
| j	                  |
ddg       | j                  |	d         }|	|d<   |S )	a7  

        https://docs.futures.kraken.com/#http-api-trading-v3-api-order-management-edit-order

        Edit an open order on the exchange
        :param str id: order id
        :param str symbol: Not used by Krakenfutures
        :param str type: Not used by Krakenfutures
        :param str side: Not used by Krakenfutures
        :param float amount: Order size
        :param float [price]: Price to fill order at
        :param dict [params]: Exchange specific params
        :returns: An `order structure <https://docs.ccxt.com/#/?id=order-structure>`
        r  r  r  
editStatusr  rO   r  r1  )rU  privatePostEditorderrW  r8  r  r  )r	  r3   r   r  r  r$  r%  rD  rY  rE  r  r  s               r  
edit_orderzkrakenfutures.edit_order  s     	r
 $GFO$)GL!,,T[[&-IJ!!(<"8(C((xjI  ,!78 fr  c                 .   | j                          | j                  | j                  d|i|            }| j                  | j	                  |di       d      }| j                  |d       i }d|v r| j                  |d         }| j                  d|i|      S )ax  

        https://docs.futures.kraken.com/#http-api-trading-v3-api-order-management-cancel-order

        Cancel an open order on the exchange
        :param str id: Order id
        :param str symbol: Not used by Krakenfutures
        :param dict [params]: Exchange specific params
        :returns: An `order structure <https://docs.ccxt.com/#/?id=order-structure>`
        r  cancelStatusr  rE   r1  )rU  privatePostCancelorderrW  r8  r5  r  r  )r	  r3   r   rD  rE  r  r  s          r  cancel_orderzkrakenfutures.cancel_order  s     	..t{{J;KV/TU!!$//(NB"OQYZ((?X%$$Xn%=>E{{FH-u55r  idsc                    | j                          g }| j                  |dg       }t        |      }|dkD  r2t        dt        |            D ]  }|j	                  d||   d        n1t        dt        |            D ]  }|j	                  d||   d        d|i}| j                  | j                  ||            }	| j                  |	dg       }
| j                  |
      S )a  
        cancel multiple orders

        https://docs.futures.kraken.com/#http-api-trading-v3-api-order-management-batch-order-management

        :param str[] ids: order ids
        :param str [symbol]: unified market symbol
        :param dict [params]: extra parameters specific to the exchange API endpoint

 EXCHANGE SPECIFIC PARAMETERS
        :param str[] [params.clientOrderIds]: max length 10 e.g. ["my_id_1","my_id_2"]
        :returns dict: an list of `order structures <https://docs.ccxt.com/#/?id=order-structure>`
        clientOrderIdsr   cancel)r  r  )r  r  r  r  )	rU  r5  r7  r6  r@  r  rW  r_  r  )r	  r  r   rD  r   r  clientOrderIdsLengthrG  rY  rE  r  s              r  cancel_orderszkrakenfutures.cancel_orders  s     	1A2F">2!#1c.12 RnQ>OPQR 1c#h' Gc!fEFG &
 --dkk'6.JK< nnX}bA  --r  c                    i }|| j                  |      |d<   | j                  | j                  ||            }| j                  |d      }| j	                  |dg       }g }t        dt        |            D ]8  }| j                  |d      }	| j                  |	di       }
|j                  |
       : | j                  |      S )aI  

        https://docs.futures.kraken.com/#http-api-trading-v3-api-order-management-cancel-all-orders

        Cancels all orders on the exchange, including trigger orders
        :param str symbol: Unified market symbol
        :param dict [params]: Exchange specific params
        :returns: Response from exchange api
        r   r	  orderEventsr   r  )		market_idprivatePostCancelallordersrW  r  r_  r6  r7  r@  r  )r	  r   rD  rY  rE  r	  r  r   rG  
orderEventr  s              r  cancel_all_orderszkrakenfutures.cancel_all_orders"  s      $v 6GH224;;w3OP@ ~~h?nn\="Eq#k*+ 	!AQ7JNN:w;EMM% 	!   ((r  timeoutc                     | j                          d|dkD  r| j                  |dz        ndi}| j                  | j                  ||            }|S )a  
        dead man's switch, cancel all orders after the given timeout

        https://docs.futures.kraken.com/#http-api-trading-v3-api-order-management-dead-man-39-s-switch

        :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
        r  r   r  )rU  r  privatePostCancelallordersafterrW  )r	  r  rD  rY  rE  s        r  cancel_all_orders_afterz%krakenfutures.cancel_all_orders_afterX  sX     	w{))'D.9QR
 77GV8TU r  c                     | j                          d}|| j                  |      }| j                  |      }| j                  |dg       }| j	                  ||||      S )ay  

        https://docs.futures.kraken.com/#http-api-trading-v3-api-order-management-get-open-orders

        Gets all open orders, including trigger orders, for an account from the exchange api
        :param str symbol: Unified market symbol
        :param int [since]: Timestamp(ms) of earliest order.(Not used by kraken api but filtered internally by CCXT)
        :param int [limit]: How many orders to return.(Not used by kraken api but filtered internally by CCXT)
        :param dict [params]: Exchange specific parameters
        :returns: An array of `order structures <https://docs.ccxt.com/#/?id=order-structure>`
        N
openOrders)rU  rH  privateGetOpenordersr_  r  )r	  r   r  r   rD  rH  rE  r   s           r  fetch_open_orderszkrakenfutures.fetch_open_orderss  sb     	[[(F,,V4,;  >>r  c                    | j                          d}|| j                  |      }i }|||d<   |||d<   | j                  | j                  ||            }| j	                  |dg       }g }	t        dt        |            D ]p  }
||
   }| j                  |di       }| j                  |d      }|0| j                  |di       }| j                  |d	      }|d
k7  s[d|d<   |	j                  |       r | j                  |	|||      S )a  

        https://docs.futures.kraken.com/#http-api-history-account-history-get-order-events

        Gets all closed orders, including trigger orders, for an account from the exchange api
        :param str symbol: Unified market symbol
        :param int [since]: Timestamp(ms) of earliest order.
        :param int [limit]: How many orders to return.
        :param dict [params]: Exchange specific parameters
        :returns: An array of `order structures <https://docs.ccxt.com/#/?id=order-structure>`
        Nr  r  r  r   r  OrderPlacedr  r  r   closedr  rU  rH  historyGetOrdersrW  r_  r6  r7  r  r8  r@  r  )r	  r   r  r   rD  rH  rY  rE  	allOrdersclosedOrdersrG  r  r  orderPlaced
innerOrderr  s                   r  fetch_closed_ordersz!krakenfutures.fetch_closed_orders  s&    	[[(F$GG#GFO((Wf)EFNN8Z<	q#i.) 		4AaLENN5'26E..>K&!^^K"E
))*h?S=+3Jx( ''
3		4   vueDDr  c                    | j                          d}|| j                  |      }i }|||d<   |||d<   | j                  | j                  ||            }| j	                  |dg       }g }	t        dt        |            D ]  }
||
   }| j                  |di       }| j                  |d      }|@| j                  |di       }| j                  |d	      }|d
k(  rd|d<   |	j                  |       | j                  |d      }|)| j                  |di       }d|d<   |	j                  |       | j                  |d      }|| j                  |di       }d|d<   |	j                  |        | j                  |	|||      S )a  

        https://docs.futures.kraken.com/#http-api-history-account-history-get-order-events

        Gets all canceled orders, including trigger orders, for an account from the exchange api
        :param str symbol: Unified market symbol
        :param int [since]: Timestamp(ms) of earliest order.
        :param int [limit]: How many orders to return.
        :param dict [params]: Exchange specific parameters
        :returns: An array of `order structures <https://docs.ccxt.com/#/?id=order-structure>`
        Nr  r  r  r   r  r!  r  r  r   canceledr  OrderCancelledOrderRejectedrejectedr#  )r	  r   r  r   rD  rH  rY  rE  r%  canceledAndRejectedrG  r  r  r'  r(  r  orderCanceledorderRejecteds                     r  fetch_canceled_ordersz#krakenfutures.fetch_canceled_orders  s    	[[(F$GG#GFO((Wf)EFNN8Z<	 q#i.) 	7AaLENN5'26E..>K&!^^K"E
))*h?S=+5Jx('..z: NN52BCM(!^^M7BG
'1
8$#**:6 NN5/BM(!^^M7BG
'1
8$#**:6'	7(   !4feUKKr  c                 6    ddddd}| j                  |||      S )Nr   rH  )r  r  r   r  r8  )r	  r  typesMaps      r  r  zkrakenfutures.parse_order_type  s,    	
 )Y??r  c                    i dt         dt         dt         dt         dt        dt        dt        dt        d	t        d
t        dt
        dt        dt         dt        dt        dt        dt        t         t        t        d}||v r4| j                  ||      s! ||   | j                  dz   |z   dz   |z         y y )NinvalidOrderTypeinvalidSideinvalidSizeinvalidPriceinsufficientAvailableFundsselfFilltooManySmallOrdersmaxPositionViolationmarketSuspendedmarketInactiveclientOrderIdAlreadyExistclientOrderIdTooLongoutsidePriceCollarpostWouldExecuteiocWouldNotExecutewouldNotReducePositionorderForEditNotFound)orderForEditNotAStopr  r   z: z failed due to )r#   r"   r   r!   r+   r'   r%   r&   r$   in_arrayr3   )r	  r  r   r  errorss        r  r  z)krakenfutures.verify_order_action_success  s0   

<
 <
 L	

 )*;
 
 !-
 #J
 3
 2
 ()9
 #J
 !,
  8
 !"2
  %m!
" #M#
$ %1#%)
, fdmmFD&A &.4&!8;L!Lv!UVV 'Br  r  c           
          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}| j                  |||      S )Nplacedrs  	cancelledr+  r7  r.  r8  r9  r:  r;  r<  r=  r>  r?  r@  rA  rB  rC  rD  rE  r"  )rF  editedrG  rH  r  r   	untouchedpartiallyFilledr4  )r	  r  statusess      r  parse_order_statusz krakenfutures.parse_order_status  s   
f

 

 :	

 :
 J
 )*
 

 !*
 #J
 z
 j
 (
 #J
 !*
" 
#
$ !*%
& '1$.$."%5
8 &&99r  r  c                 t	   | j                  |dg       }| j                  |d      }t        |      }d|v r||dk(  r| j                  |dd      S d }d}d}d }	d }
g }|rg }t	        dt        |            D ]  }||   }| j                  |d      dk(  r|j                  |       | j                  |d	      }|C| j                  |d
d|      }|d}d}^|ra| j                  |d      }| j                  |dd      }| j                  |d      }
|d} | j                  |      }| j                  |d      }	||}|	| j                  |d      }	| j                  |	      }| j                  |g d      }| j                  |d      }| j                  ||      }| j                  | j                  |dd            }| j                  | j                  |d            }|
| j                  |d      }
| j                  |d      }| j                  |ddd      }| j                  |d      }d }d}t        |      }|dkD  rd}t	        dt        |            D ]k  }||   }| j                  |d      }| j                  |d      }t        j                  ||      }t        j                  |t        j                  ||            }m t        j                   ||      }||s|rt        j"                  ||      rd}d}|rt        j                  ||      }nt        j$                  ||      }||r|t        j&                  ||      }n|}||s|t        j                  ||      }d } |<|:||n|
}!|!2|d   rt        j                  ||!      } nt        j                   ||!      } | j                  |dd      }"|"| j                  |dd       }"| j)                  |dd!      }#d"}$|#d#k(  s| j+                  |#      d$k(  rd#}$| j                  i d%|d&|"d'| j-                  |g d(      d|d)| j/                  |      d*d d+|d| j                  |d      d| j+                  |#      d,|$d-|#d.k(  d/| j1                  |d/d0      d1| j                  |d1      d|
d2| j                  |d2      d|d3| ||||d d |d4      S )5Nr  r  r   r.  )r1  r  Fr  	EXECUTIONorderTriggernewr  Tr  r  r  )r+  r.  r"  r   rZ  receivedTimelastUpdateTimer  
filledSizer  r  unfilledSizer$  r%  r"  r   r  r  r  r  gtcr  rH  r1  r3   r  )r  clientIdr  ri  lastTradeTimestamplastUpdateTimestampr   r  r   r  reduce_onlyr  r   r'  )rw  r  	remainingr  r  r   trades)r5  r8  r7  
safe_orderr6  r@  safe_value_2r  rR  rI  r|  r:  r  r.   r  r~  r  	string_ge
string_maxr}  safe_string_lower_2r  r  rA  safe_bool_2)%r	  r  rH  r  errorStatusorderEventsLengthdetailsisPriorfixedstatusIdr%  ra  r   rG  itemrU  r  r  isClosedr  rZ  r^  r$  r  r`  rw  filled2tradesLengthvwapSumr  tradeAmount
tradePricer'  
whichPricer3   r  r   s%                                        r  r  zkrakenfutures.parse_order  s   v ooe]B?&&uh7,U")@GX\]G]??EZ#HIIJ1c+./ +"1~##D&1[@%%d+#t^D?"//eWlSG*"' $".2oodDY.Z+"&"3"3D:OQa"b $ 0 01Dl S".&*G!+" &&z2F''x8H?G'':H ((2==)KL##GX6!!(F3NN4#5#5g{N#[\	"nnT-=-=gGW-XY=$$Wl;E!!':6##G\8UK$$Wn=	6{!G1c&k* cq	"..uh?!--eW=
!,,WkB!,,Wg6H6HV`6abc ((':G"X7wGXGXY`bhGi! ++FG< ++FG<% ' 2 267 CI"	NW93H''	:FV%7%,%8uJ%(#"--fjAD"--fjADz9=:##GY>B''E5=D11$78CK  
E 
" 
 T//9bc 
 	 

 Y/ 
 !$ 
 "#6 
 d&&vx8 
 D))$/ 
 ; 
  
 $**7L-P 
 D$$Wf5 
 U 
 D,,WnE 
  f! 
" D# 
$ "1 
  	r  c                     | j                          d}|| j                  |      }| j                  |      }| j                  |d   |||      S )a}  
        fetch all trades made by the user

        https://docs.futures.kraken.com/#http-api-trading-v3-api-historical-data-get-your-fills

        :param str symbol: unified market symbol
        :param int [since]: *not used by the  api* 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]: the latest time in ms to fetch entries for
        :returns Trade[]: a list of `trade structures <https://docs.ccxt.com/#/?id=trade-structure>`
        Nr   )rU  rH  privateGetFillsr  )r	  r   r  r   rD  rH  rE  s          r  fetch_my_tradeszkrakenfutures.fetch_my_tradeso  sW     	[[(F''/*   '!2FE5IIr  c                 T   | j                          | j                  |dd      }| j                  |d      }| j                  |g d      }| j	                  |      }| j                  |d      }|dk(  s|dk(  r|t        | j                  dz         |}||d	n|}| j                  |      }| j                  |d
      }| j                  ||      }|'|dn|}|dn|}t        | j                  dz   |z         | j                  |      }	||	d<   | j                  |      |	d<   ||	d<   |	S )a  

        https://docs.futures.kraken.com/#http-api-trading-v3-api-account-information-get-wallets

        Fetch the balance for a sub-account, all sub-account balances are inside 'info' in the response
        :param dict [params]: Exchange specific parameters
        :param str [params.type]: The sub-account type to query the balance of, possible values include 'flex', 'cash'/'main'/'funding', or a market symbol * defaults to 'flex' *
        :param str [params.symbol]: A unified market symbol, when assigned the balance for a trading market that matches the symbol is returned
        :returns: A `balance structure <https://docs.ccxt.com/#/?id=balance-structure>`
        r  accountr   )r  rz  r   rS  marginAccountr?   z: fetchBalance requires symbol argument for margin accountsr   r    z! fetchBalance has no account for r1  rZ  ri  )rU  r  r8  r  privateGetAccountsr    r3   parse_accountr5  r!   parse_balancer:  )
r	  rD  r  r   rE  ri  accountNamer   rz  balances
             r  fetch_balancezkrakenfutures.fetch_balance  sJ    	!!&&)<!!&(36#@A**62p ##Hl;?"dh&6~'2n(nooD<$n66D((.??8Z8//(K8?,2TD"NRFTWW'JJTQRR$$W-"#~~h7&
r  c                    | j                  |dd      }|dk(  }|dk(  }| j                  |ddi       }i }t        |j                               }t	        dt        |            D ]  }||   }	||	   }
| j                  |	      }|j                  d      }t        |      }|d	kD  r@| j                         }|r+| j                  |
d
      |d<   | j                  |
d      |d<   nI|rd|d<   |
|d<   n<| j                  |d      }| j                  |d      |d<   | j                  |d      |d<   |||<    | j                  |      S )NaccountTyper  multiCollateralMarginAccountcashAccountbalancesrC  r   r  r  r  total	availablefreer  used	auxiliaryafpv)r  rc  listkeysr6  r7  r<  r;  rz  r8  r5  safe_balance)r	  rE  r  isFlexisCashr  rF  currencyIdsrG  
currencyIdr  r3  	splitCode
codeLengthrz  r  s                   r  r  zkrakenfutures.parse_balance  sa   ~ ((=&I!??.$$Xz<L8==?+q#k*+ 	#A$QJz*G**:6D

3IYJA~llnG#'#3#3GZ#H "&"2"27K"H"'#*  OOHkB	"&"2"29d"C#'#3#3It#D "F4L'	#(   ((r  c                    | j                          | j                  |      }| j                  |      }| j                  |dg       }g }t	        dt        |            D ]b  }||   }| j                  |d      }	|| j                  |	|      s/| j                  |	      }
| j                  ||
      }|j                  |       d | j                  |d      S )a  
        fetch the current funding rates for multiple markets

        https://docs.futures.kraken.com/#http-api-trading-v3-api-market-data-get-tickers

        :param str[] symbols: unified market symbols
        :param dict [params]: extra parameters specific to the exchange API endpoint
        :returns Order[]: an array of `funding rate structures <https://docs.ccxt.com/#/?id=funding-rate-structure>`
        r   r   r   )rU  
market_idsr^  r_  r6  r7  r5  rI  r|  parse_funding_rater@  index_by)r	  r\  rD  	marketIdsrE  r   fundingRatesrG  entryentry_symbolrH  parseds               r  fetch_funding_ratesz!krakenfutures.fetch_funding_ratesn  s     	OOG,	((0..9b9q#g,' 	(AAJE??5(;L$}}\9=%%l3F,,UF;F'	( }}\844r  c                    d}| j                  |d      }| j                  |      }| j                  | j                  |d            }| j                  |d      }| j                  |d      }| j	                  |      }	| j                  |d      }
t        j                  t        j                  |
|      |      }| j	                  |      }| j                  |d      }t        j                  t        j                  ||      |      }| j	                  |      }i d|d|d|	d|d	d d
d d|d| j                  |      d|dd dd d|dd dd dd dd dd dd iS )N8r   rd  ry  rx  fundingRatefundingRatePredictionr1  interestRateestimatedSettlePricerZ  ri  fundingTimestampfundingDatetimenextFundingRatenextFundingTimestampnextFundingDatetimepreviousFundingRatepreviousFundingTimestamppreviousFundingDatetimer  )	r8  r   r:  r>  r  r.   r  r~  rA  )r	  rb  rH  fundingRateMultiplierr  r   rZ  ry  markPriceStringrx  fundingRateStringfundingRateResultr  nextFundingRateStringnextFundingRateResultr  s                   r  r  z krakenfutures.parse_funding_rate  s   . !$##FH5X&NN4#3#3FJ#GH	%%fl;
**6;?%%o6	 ,,V]C#..w/A/ABSUj/km|}''(9: $ 0 09P Q ' 2 273E3EF[]r3s  vE  !F++,AB
F
f
 
 *	

 D
 #D
 
 Y/
 ;
 
 t
 
 #D
 "4
 "4
  '!
" &t#
$ %
 	
r  c           	      `   |t        | j                  dz         | j                          | j                  |      }|d   st	        | j                  dz         d|d   j                         i}| j                  | j                  ||            }| j                  |d      }g }	t        dt        |            D ]O  }
||
   }| j                  |d      }|	j                  ||| j                  |d	      | j                  |      |d
       Q | j                  |	d      }| j!                  ||||      S )a  
        fetches historical funding rate prices

        https://docs.futures.kraken.com/#http-api-trading-v3-api-historical-funding-rates-historical-funding-rates

        :param str symbol: unified symbol of the market to fetch the funding rate history for
        :param int [since]: timestamp in ms of the earliest funding rate to fetch
        :param int [limit]: the maximum amount of `funding rate structures <https://docs.ccxt.com/#/?id=funding-rate-history-structure>` to fetch
        :param dict [params]: extra parameters specific to the api endpoint
        :returns dict[]: a list of `funding rate structures <https://docs.ccxt.com/#/?id=funding-rate-history-structure>`
        z5 fetchFundingRateHistory() requires a symbol argumentr@   z7 fetchFundingRateHistory() supports swap contracts onlyr   r3   ratesr   rZ  relativeFundingRate)r1  r   r  rZ  ri  )r    r3   rU  rH  r!   upperpublicGetHistoricalfundingratesrW  r5  r6  r7  r8  r@  r>  r:  sort_byfilter_by_symbol_since_limit)r	  r   r  r   rD  rH  rY  rE  r  rF  rG  rn  ri  sorteds                 r  fetch_funding_rate_historyz(krakenfutures.fetch_funding_rate_history  s6    >#DGG.e$effV$f~TWW'``aafTl((*
 77GV8TU '2q#e*% 		A8D''k:HMM #//6KL!^^H5$ 		 fk200NNr  c                     | j                          i }| j                  |      }| j                  |      }| j                  |d|d      S )aM  

        https://docs.futures.kraken.com/#http-api-trading-v3-api-account-information-get-open-positions

        Fetches current contract trading positions
        :param str[] symbols: List of unified symbols
        :param dict [params]: Not used by krakenfutures
        :returns: Parsed exchange response for positions
        r   F)rU  privateGetOpenpositionsparse_positionsfilter_by_array_positions)r	  r\  rD  rY  rE  rF  s         r  fetch_positionszkrakenfutures.fetch_positions  sN     	//8" %%h/--fhOOr  c                     g }| j                  |d      }t        dt        |            D ]'  }| j                  ||         }|j	                  |       ) |S )NopenPositionsr   )r5  r6  r7  parse_positionr@  )r	  rE  r\  rD  rF  	positionsrG  positions           r  r  zkrakenfutures.parse_positions	  sX    OOHo>	q#i.) 	$A**9Q<8HMM(#	$ r  r  c                    | j                  |d      }d}|d}| j                  |d      }| j                  |d      }| j                  ||      }i d|d|d   d| j                  |      d|d	d d
d dd dd d| j                  |d      dd d|dd d| j                  |d      d| j                  |d      dd dd dd d || j                  |d      d dS )NmaxFixedLeveragecrossisolatedr  r   r1  rZ  ri  initialMargininitialMarginPercentagemaintenanceMarginmaintenanceMarginPercentage
entryPricer%  notionalr   unrealizedPnl	contractsr  r#  marginRatioliquidationPricerx  r  )
collateral
marginTyper  r   )r>  r8  r|  r:  )r	  r  rH  r   r  ri  r  s          r  r  zkrakenfutures.parse_position	  s   . ##H.@A
#J##Hj9##Hh7!!(F3
H
fX&
 1
 	

 T
 &t
  
 *4
 $**8W=
 
 
 T
 ))(F;
 D,,V^D
 4
  !
" #
$ $$$Xv6+
 	
r  c                     | j                          | j                  |      }| j                  |d      }| j                  ||d      S )a
  
        retrieve information on the maximum leverage, and maintenance margin for trades of varying trade sizes

        https://docs.futures.kraken.com/#http-api-trading-v3-api-instrument-details-get-instruments

        :param str[]|None symbols: list of unified market symbols
        :param dict [params]: extra parameters specific to the exchange API endpoint
        :returns dict: a dictionary of `leverage tiers structures <https://docs.ccxt.com/#/?id=leverage-tiers-structure>`, indexed by market symbols
        r   r   )rU  r4  r_  parse_leverage_tiers)r	  r\  rD  rE  r  s        r  fetch_leverage_tiersz"krakenfutures.fetch_leverage_tiersP	  sH     	,,V4Z ~~h6((wAAr  c                    | j                  |d      }| j                  |d      }| j                  ||      }g }||S t        dt	        |            D ]  }||   }| j                  |d      }| j                  |d      }	|dk7  rt	        |      }
||
dz
     }|	|d<   |j                  | j                  |d      | j                  ||      |d	   |	d| j                  |d
      | j                  t        j                  d|            |d        |S )z`
 @ignore
 @param info Exchange market response for 1 market
 @param market CCXT market
        marginLevelsr   Nr   r  numNonContractUnitsr  maxNotionalr  r  1)tierr   currencyminNotionalr  r)  maxLeverager1  )r5  r8  r|  r6  r7  r>  r@  r  safe_symbolr  r.   r  )r	  r1  rH  r  r  r   rG  r  r  r  tiersLengthpreviousTiers               r  parse_market_leverage_tiersz)krakenfutures.parse_market_leverage_tiers	  s+   N t^<##D(3!!(F3Lq#l+, 	A?D ,,T?CM**41FGKAv!%j$[1_5.9]+LLA**8V<"7O*#)-)9)9$@S)T#001C1CC1WX	 		$ r  rv   r  c                     | j                  |d      }|d | j                  |      || j                  |d      d d d | j                  |d      d	S )NrS  r3  rF  )	r1  r3   rZ  ri  r  r$  fromAccount	toAccountr  )r8  r:  )r	  rv   r  ri  s       r  parse_transferzkrakenfutures.parse_transfer	  s^     ##Hl;1 ((6:&&x:

 
	
r  c           	          ddddddddd}||v r||   S || j                   v rV| j                  |      }|d   }|j                  d      }|d   rd| j                  |d      z   S d	| j                  |d      z   S |S )
Ncashr   )mainfundingrA   futuresr  r  multiCollateralmultiCollateralMarginr3   r  r   fi_r  fv_)marketsrH  r;  r8  )r	  rz  accountByTyperH  r  splitIds         r  r~  zkrakenfutures.parse_account	  s    !,2%%+	
 m# ))$[[)Fd|HnnS)Gi t//;;;t//;;;Nr  r3  c                 ,    | j                  ||dd|      S )a3  
        transfer from futures wallet to spot wallet
        :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>`
        rA   r>   )rv   )r	  r3  r$  rD  s       r  transfer_outzkrakenfutures.transfer_out	  s     }}T68VVDDr  r  r  c                 D   | j                          | j                  |      }|dk(  rt        | j                  dz         d|i}d}|dk(  r_| j	                  |      dk7  r!t        | j                  dz   |z   dz   |z         |d   |d	<   | j                  | j                  ||            }nQ| j	                  |      |d
<   | j	                  |      |d<   |d   |d<   | j                  | j                  ||            }| j                  ||      }	| j                  |	|||d      S )a  

        https://docs.futures.kraken.com/#http-api-trading-v3-api-transfers-initiate-wallet-transfer
        https://docs.futures.kraken.com/#http-api-trading-v3-api-transfers-initiate-withdrawal-to-spot-wallet

        transfers currencies between sub-accounts
        :param str code: Unified currency code
        :param float amount: Size of the transfer
        :param str fromAccount: 'main'/'funding'/'future', 'flex', or a unified market symbol
        :param str toAccount: 'main'/'funding', 'flex', 'spot' or a unified market symbol
        :param dict [params]: Exchange specific parameters
        :returns: a `transfer structure <https://docs.ccxt.com/#/?id=transfer-structure>`
        r>   z2 transfer does not yet support transfers from spotr$  Nr  z transfer cannot transfer from z to r3   r  r  r  unit)r$  r  r  )	rU  r  r!   r3   r~  privatePostWithdrawalrW  privatePostTransferr  )
r	  r3  r$  r  r  rD  r  rY  rE  rv   s
             r  rv   zkrakenfutures.transfer
  s?    	==&& TWW'[[\\f
 !!+.&8 +L!L{!Z]c!cfo!opp"*4.GJ11$++gv2NOH%)%7%7%DGM"#'#5#5i#@GK &tnGFO//GV0LMH &&x:{{8&"&
  	r  r   c                     |t        | j                  dz         | j                          || j                  |      j	                         d}| j                  | j                  ||            S )a  
        set the level of leverage for a market

        https://docs.futures.kraken.com/#http-api-trading-v3-api-multi-collateral-set-the-leverage-setting-for-a-market

        :param float leverage: the rate of leverage
        :param str symbol: unified market symbol
        :param dict [params]: extra parameters specific to the exchange API endpoint
        :returns dict: response from the exchange
        z) setLeverage() requires a symbol argument)r  r   )r    r3   rU  r  r  privatePutLeveragepreferencesrW  )r	  r   r   rD  rY  s        r  set_leveragezkrakenfutures.set_leverage1
  sg     >#DGG.Y$YZZ#nnV,224
 11$++gv2NOOr  c                     | j                          | j                  |      }| j                  |dg       }| j                  ||d      S )a  
        fetch the set leverage for all contract and margin markets

        https://docs.futures.kraken.com/#http-api-trading-v3-api-multi-collateral-get-the-leverage-setting-for-a-market

        :param str[] [symbols]: a list of unified market symbols
        :param dict [params]: extra parameters specific to the exchange API endpoint
        :returns dict: a list of `leverage structures <https://docs.ccxt.com/#/?id=leverage-structure>`
        leveragePreferencesr   )rU  privateGetLeveragepreferencesr_  parse_leverages)r	  r\  rD  rE  r  s        r  fetch_leverageszkrakenfutures.fetch_leveragesH
  sL     	55f= #nnX7LbQ##$7(KKr  c                 l   |t        | j                  dz         | j                          | j                  |      }d| j	                  |      j                         i}| j                  | j                  ||            }| j                  |dg       }| j                  |di       }| j                  ||      S )a  
        fetch the set leverage for a market

        https://docs.futures.kraken.com/#http-api-trading-v3-api-multi-collateral-get-the-leverage-setting-for-a-market

        :param str symbol: unified market symbol
        :param dict [params]: extra parameters specific to the exchange API endpoint
        :returns dict: a `leverage structure <https://docs.ccxt.com/#/?id=leverage-structure>`
        z+ fetchLeverage() requires a symbol argumentr   r  r   )r    r3   rU  rH  r  r  r  rW  r_  r  parse_leverage)r	  r   rD  rH  rY  rE  r  r  s           r  fetch_leveragezkrakenfutures.fetch_leveragec
  s     >#DGG.[$[\\V$dnnV,224
 55dkk'66RS #nnX7LbQ~~11b9""400r  c                 z    | j                  |d      }| j                  |d      }|| j                  ||      d ||dS )Nr   r  )r1  r   r   longLeverageshortLeverage)r8  r  r  )r	  r   rH  r  leverageValues        r  r  zkrakenfutures.parse_leverage
  sL    ##Hh7))(MB&&x8)*
 	
r  reasonurlr   headersbodyc
                    |y |dk(  rt        | j                  dz   |z         | j                  |d      }
| j                  |
d      }| j                  |d      }| j                  |d|      }|y | j                  dz   |z   }| j	                  | j
                  d   ||       | j                  | j
                  d   ||       |d	k(  rt        |      t        |      )
Ni   rJ  r   messageerrorr   r   i  )	r)   r3   r5  r8  throw_exactly_matched_exceptionr   throw_broadly_matched_exceptionr!   r   )r	  r3  r  r  r   r  r  rE  requestHeadersrequestBodyrJ  
firstErrorfirtErrorMessager  feedbacks                  r  handle_errorszkrakenfutures.handle_errors
  s    3; 3!56684__VQ/
++J	B""8W6FG?77S=4',,T__W-EwPXY,,T__W-EwPXY3;X&&H%%r  rx   r   c                    | j                  | j                  d   |i       }| j                  ||i       }| j                  ||| j                        }	| j                  |d|	      }
| j	                  |d      }| j                  | j                  d   |i       }| j                  ||i       }| j                  ||d      }|
dz   | j                  ||      z   }| j	                  || j                  |            }|}d}|dk(  rd| j                  |      z   }|}n|r| j                  |      }|d	|z   z  }| j                  d
   |   |z   }|dk(  s|dk(  r| j                          |dz   }|dk7  r||dz   z  }||z  }| j                  | j                  |      dd      }| j                  | j                        }| j                  ||t         j"                  d      }dd| j$                  |d}||||dS )Nr   r7   r   rx   r  r|  r   zjson=?r   ry   z/api/sha256binarybase64z!application/x-www-form-urlencodedzapplication/json)zContent-TypeAcceptAPIKeyAuthent)r  r   r  r  )r5  r   r8  r7   r  implode_paramsextract_paramsjson	urlencoderw   check_required_credentialshashencodebase64_to_binarysecrethmachashlibsha512apiKey)r	  pathr   r   rD  r  r  apiVersionsmethodVersionsdefaultVersionr7   	apiAccessmethodAccessr   endpointquerypostDatar  authr+  r.  	signatures                         r  signzkrakenfutures.sign
  s   oodll:&>RHfbA)).$M""69nE69-OODLL$:CD	y&"=!!,h?S=4#6#6tV#DD64#6#6t#<=<6!22HD~~f-HS8^#Eiis#e+)v2++-g%Dic	!HD99T[[.(CD**4;;7F		$II C,++$	G fdwOOr  )N)O__name__
__module____qualname__r   r  r   r   rQ  r  r   r   r[  r   r   ra  dictr   r  r  r  r  r   r  r  r   r   floatr   r  r  r   r  r  r   r  r  r  r  r   r  r)  r2  r  r  rR  r  rx  r   r  r  r   r  r   r  r  r   r  r  r  r   r  r   r  r   r   r  r~  r  rv   r  r
   r  r	   r	  r  intr  r>  __classcell__)r
  s   @r  r0   r0      s   V# Vp
 $& f$v, fP :>b 0Os 0O3 0OY 0Od 04B -4W -47 -4^D4 D D6 DL 26DW[df 9K# 9Kc 9KQT 9Kkoptku 9Kv
 
4 
( 6:UW wB3 wBs wB# wB\`af\g wBr@ @v @ @D os{} 3,3 3,i 3,y 3,Z_ 3,hk 3,j gksu :43 :4i :4y :4RW :4`c :4x @B 0'D$6 0'd `drv  @B S # Y i Y\ lo < 37r 6s 6C 6( ;?r :.c :.C :.x /32 4) 4)l <> s 6 /3TXac ? ?3 ?c ?hlmrhs ?( 154VZce "E# "ES "EPS "Ejnotju "EH 37TX\eg ,LC ,Ls ,LRU ,Llpqvlw ,L\@ @B W4: :>R Rv R Rh
 -1tRV_a 'Jc 'J 'JC 'JR $& y( yvY) Y)v 6:" 57 5 547
 7
; 7
r 8<$]ajl /O /OC /OWZ /Ob 26b Pw PT(^ P@ <@  4
t 4
V 4
l 7;2 9BG 9B- 9Bv? ?$|J\ ?B
t 
x 
= 
,0 68 E E [] +S +% +c +c +an +Z 9=R PS P# P. 26b Lw LY L6 24 1S 1 1:	
t 	
V 	
x 	
&# &s & &c &TX &`c &$ &eBSW #Pr  r0   )5ccxt.base.exchanger   ccxt.abstract.krakenfuturesr   r0  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   r   typingr   ccxt.base.errorsr   r   r    r!   r"   r#   r$   r%   r&   r'   r(   r)   r*   r+   r,   ccxt.base.decimal_to_precisionr-   ccxt.base.preciser.   r0    r  r  <module>rN     s    ( 3  H  H  H  H  H  H  H  * 0 . ' . ) * 5 - - 0 + . 1 ) 4 %b*PHk b*Pr  