
    eiV                       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          Z4dS )    )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                       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dSd
ededefdZdddi fdedede	de	dee         f
dZdSdedefdZddi fdede	de	dee         fdZdSd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i fdede!fd'Z)dddi fde!de	de	dee&         fd(Z*dddi fde!de	de	dee&         fd)Z+d* Z,g fd+Z-d,e!fd-Z.dSd.edede&fd/Z/dddi fde!de	de	fd0Z0i fde1fd1Z2de1fd2Z3di fdede4fd3Z5dSdede6fd4Z7dddi fde!de	de	fd5Z8di fdedee9         fd6Z:di fdefd7Z;dSd8edefd9Z<di fdede=fd:Z>dSdedee?         fd;Z@dSd<ed=eAdeBfd>ZCd? ZDi fd@efdAZEi fd@ededBedCedeBf
dDZFdi fdEeGde!fdFZHdi fdedeIfdGZJi fdedeKfdHZLdSdEededeKfdIZMd@eGdJedKedLedMedNefdOZNdPdQi ddfdRZO xZPS )Tkrakenfuturesreturnc                 p
   |                      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/d0d1dd2di d3dd4dd5dd6dd7dd8dd9dd:d0d;dd<dd=dd>dd?dd@ddAddBddCdd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|                     db          |                     dc          |                     dd          |                     db          g|                     de          |                     df          g|                     dg          |                     dh          g|                     di          |                     dj          g|                     dk          |                     dc          g|                     dl          |                     dm          g|                     dn          |                     do          g|                     dp          |                     dq          gg|                     dd          |                     dc          g|                     de          |                     dr          g|                     dg          |                     do          g|                     di          |                     dq          g|                     dk          |                     ds          g|                     dl          |                     dt          g|                     dn          |                     du          g|                     dp          |                     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          ddddddddd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fetchCurrencies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/)r{   r|   feeschedulesry   rz   zhttps://futures.kraken.com/zAhttps://docs.kraken.com/api/docs/futures-api/trading/market-data/zihttps://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/historyzorders/status)
	sendorder	editordercancelorderrw   
batchordercancelallorderscancelallordersafter
withdrawalzassignmentprogram/addzassignmentprogram/deleter   r   )r   postputz {price_type}/{symbol}/{interval})orders
executionstriggersaccountlogcsvaccount-logzmarket/{symbol}/orderszmarket/{symbol}/executions)ry   rz   r{   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|   GETrz   )r   r   r   r   r   flex)USDTBTCUSDGBPEURUSDCr   XBT)quoteIdsreversedr   v4v1v2)r   r   r   r   )ry   r{   r|   method historyGetMarketSymbolExecutions)accesssettlementCurrenciessymbolversionsrs   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     )	rt   rH   createOrdersrj   rm   rl   ro   rT   rk   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    ^/var/www/html/volatility/venv/lib/python3.11/site-packages/ccxt/async_support/krakenfutures.pyr	  zkrakenfutures.describe    sq
   mT : : C C E E XH
/XH
$XH
 $XH
 t	XH

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

        https://docs.kraken.com/api/docs/futures-api/trading/get-instruments

        :param dict [params]: exchange specific params
        :returns: An array of market structures
        Nr   r   r   typez index_vanillalastTradingTimer@   rA   r   _      usdcontractValueTradePrecisiontickSizefutures_inverseTF/:-r3   basequotesettlebaseIdquoteIdsettleIdr>   r?   rB   active	tradeable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coder1  )publicGetInstruments
safe_valuerangelensafe_stringfind	parse8601splitsafe_currency_coder
  integer_precision_to_amountsafe_numberyymmddappend	safe_booliso8601r   lowermap_to_safe_mapr  
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   rH  r6  s#                                      r  fetch_marketszkrakenfutures.fetch_markets{  s      226::::::::Z oohrBBq#k**++ b	 b	A ^F!!&(33B))&&99JD__X..!3EFGF $//*55:$*!--f6GHH
","4vv8
33FNDh&FFHHSMME**5!44K 3{#3#3a#7!78FG**622D++G44EFH##F,IJJD"//0P0PQU0V0VWWO!--fjAAN//%H!^VM @#//??#444!F%H"GG"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 H)- "&,,v"6"6"-+   $#! !
  $# 
  $# 
  $#  $  >>$*:*:6=*Q*QRRc2 2 2 2 2 2 2f  $|,BCFK
q#23344 	 	A'*Djjll!!	      ..t/?/?
DO/\/\]]r  Nr   r   c                 F  K   |                                   d{V  |                     |          }d|d         i}|                     |                     ||                     d{V }|                     |d                   }|                     |d         ||          S )a  

        https://docs.kraken.com/api/docs/futures-api/trading/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>`
        Nr   r3   
serverTime	orderBook)load_marketsrM  publicGetOrderbookextendr=  parse_order_book)r  r   r   rI  rM  requestrJ  	timestamps           r  fetch_order_bookzkrakenfutures.fetch_order_book#  s       !!!!!!!!!V$$fTl
 00Wf1M1MNNNNNNNN> NN8L#9::	$$Xk%:FINNNr  symbolsc                    K   |                                   d{V  |                     |           d{V }|                     |d          }|                     ||          S )a  
        fetches price tickers for multiple markets, statistical information calculated over the past 24 hours for each market

        https://docs.kraken.com/api/docs/futures-api/trading/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>`
        Nr   )rZ  publicGetTickers	safe_listparse_tickers)r  ra  rI  rJ  r   s        r  fetch_tickerszkrakenfutures.fetch_tickersU  s}       !!!!!!!!!..v66666666B ..955!!'7333r  tickerrM  c           
      $   |                      |d          }|                     ||          }|d         }|                     |                      |d                    }|                      |d          }|                      |d          }t          j        ||          }t          j        t          j        ||          d          }	t          j        t          j        ||          d          }
|                      |d          }d }d }|                     |dd	          }|s|d
         r|}n
|d         r|}| 	                    i d|d|d| 
                    |          dd dd d|                      |d          d|                      |d          d|                      |d          d|                      |d          dd d|d|d|dd d|d|	d|
|||                      |d          |                      |d          |d          S ) Nr   lastTimeopen24hr   1002vol24hr   Fr   r   r_  datetimehighlowbid	bidVolumebidSizeask	askVolumeaskSizevwapopenclosepreviousClosechanger   average	markPrice
indexPrice)
baseVolumequoteVolumer}  r~  r4  )r;  safe_marketr=  r.   
string_sub
string_mul
string_div
string_addrD  safe_tickerrE  )r  rg  rM  marketIdr   r_  rx  r   r{  r   r|  volumer  r  isIndexs                  r  parse_tickerzkrakenfutures.parse_ticker  s   6 ##FH55!!(F33!NN4#3#3FJ#G#GHH		22//#D$//'(:64(H(H%PP
$W%7d%C%CSII!!&(33
..%88 	%h %#

	" %$ !
f!
!
 Y//!
 D	!

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

        https://docs.kraken.com/api/docs/futures-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
        NFrk   paginater   r3   r(  trade)r   
price_typeinterval  fromr  tocandles)rZ  rM  handle_option_and_params"fetch_paginated_call_deterministicr;  r   omitparse_timeframeparse_to_intr)  sumseconds chartsGetPriceTypeSymbolIntervalr\  rd  parse_ohlcvs)r  r   r  r  r   rI  rM  r  r^  durationtoTimestampcurrentTimestamprJ  r  s                 r  fetch_ohlcvzkrakenfutures.fetch_ohlcv  sG      !!!!!!!!!V$$88zZZ& 	~@@vW\^cenpvx|}}}}}}}}}Tl**67GDD(()YOO
 

 67++++I66H"//==GFO}t$$E((76?EH4Dq4HIIK#||~~-=>>GDMMt$$E++I66H LLNNGDM"//EAQ0RSSGFO>>t{{7TZ?[?[\\\\\\\\  ..955  &)UEJJJr  c           	         |                      |d          |                     |d          |                     |d          |                     |d          |                     |d          |                     |d          gS )Ntimerx  ro  rp  ry  r  )safe_integerrA  )r  ohlcvrM  s      r  parse_ohlcvzkrakenfutures.parse_ohlcv  s     eV,,UF++UF++UE**UG,,UH--
 	
r  c                 6  K   |                                   d{V  d}|                     |dd          \  }}|r|                     d||||           d{V S |                     |          }d|d         i}d}|                     |ddd          \  }}d}	|dk    }
|
r|                     d	||          \  }}|
||d
<   d|d<   |||d<   |                     |                     ||                     d{V }|                     |dg           }g }	t          |          }t          d|          D ]l}|dz
  |z
  }||         }| 
                    |di           }| 
                    |di           }| 
                    |di           }|	                    |           mn`|                     d||          \  }}|                     |                     ||                     d{V }|                     |dg           }	|                     |	|||          S )al  

        https://docs.kraken.com/api/docs/futures-api/trading/get-history
        https://docs.kraken.com/api/docs/futures-api/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>`
        NFrs   r  r   r3   r   r   beforer  ascsortcountelementsr   r  event	Execution	executionri  r|   )rZ  r  fetch_paginated_call_dynamicrM  handle_until_optionr   r\  rd  r:  r9  	safe_dictrC  publicGetHistoryparse_trades)r  r   r  r   rI  r  rM  r^  r   	rawTradesisFullHistoryEndpointrJ  r  lengthrL  r   elementr  executionContainerrawTrades                       r  fetch_tradeszkrakenfutures.fetch_trades  s       !!!!!!!!!88PZ[[& 	h::=&RWY^`fgggggggggV$$fTl
 66v}hXz{{	!'+M!M  Y	@"66x&QQOGV #( "' #( !BB4;;wX^C_C_````````Hd ~~h
B??HI]]F1f%% + +
Q"5/w<<%)^^E;%K%K">>*<k2NN  ****+ #66z7FSSOGV!224;;w3O3OPPPPPPPPH& xB??I  FE5AAAr  r  c                    |                      |                     |dd                    }|                     |d          }|                     |g dd          }|                     |dd          }||                     |d          }|                     |d	          }|                     |d
          }|                     |d          }	d }
|                     |d          }|                     |d          }|Y|                     |d          }|                     |d
          }|                     |d          }	|                     |d          }
nZ|X|                     |d          }|                     |d
          }|                     |d          }	|                     |d          }
|
|                     |
          }
|                     ||          }d }|                     |d          }|\|Z|X|rt          j	        ||          }nt          j
        ||          }|                     |d          }t          j	        ||          }d }|                     |d          }|7|                    d          dk    rd}n|                    d          dk    rd}d|v }|rG|                     |d          }|                     |di           }||                     |d          }	d}d }|E|C|                     ||          }t          j	        ||          |                     |d          |d}|                     |||                     |d
          ||                     |          ||
|	|||r|nd ||d          S )Nr  fillTimer(  )sizer'  quantity0.0uidfill_idexecutionIdorder_idr   sideorderPriorEditorderPriorExecutionorderIdr  r   r&  fillTyper   r   r   
takerOrderr_  	directionr  )r*  currencyrate)r4  r3   r   r_  rn  orderr  r  takerOrMakerr(  r'  r*  fee)r=  safe_string_2r;  safe_string_nr8  parse_order_typer  rD  r.   r  r  r<  r  r  safe_string_lower
safe_traderE  )r  r  rM  r_  r(  r'  r3   r  r  r  r  	priorEditpriorExecutionr*  r   r&  r  r  isHistoricalExecutionr   r  feeRates                         r  parse_tradezkrakenfutures.parse_trade  s   D NN4#5#5eVZ#P#PQQ	  00##E+I+I+I5QQui88:!!%77B  
33##E844v..OOE+;<<	0EFF%$$^Y??E''AAH##NF;;D##NF;;DD"$$Y	::E''	8<<H##Iv66D##Iv66D((..D!!(F3311U%6V=O 9)&%88)&%88++FNCCL%dL99D##E:66}}W%%**&w''1,,&!-!6  	'))%==INN5,;;E --e[AA&$4+;&&v|<<G*499 ,,VW== C
 &&vx88"Y//( &0ffD 
  
   	r  r  r  r'  r(  c                    |                      |          }|d         }|                     |d|          }|                     |d          }d}	|                     |dk    |dk    |          \  }	}|	rd}n|dk    rd}n|dk    rd	}n|dk    rd
}|d         ||                     ||          d}
|                     |dd          }|||
d<   |                     |dd          }|d u}|                     |d          }|                     |d          }|d u}|d u}|p|}|                     |dd          }|                     |d          }|s|r||
d<   |rd}|                     ||          |
d<   n?|r=d}|rd}|                     ||          |
d<   n|rd}|                     ||          |
d<   |rd|
d<   ||
d<   ||                     ||          |
d<   |                     |g d          }|                     |
|          S )Nr   	orderTyper   FrM  r   iocr   lmtmktr3   )r   r  r  clientOrderIdcliOrdIdr   	stopPricer   r   triggerSignalr   
reduceOnlystpTtake_profit
limitPrice)r  r   r   r   r   )	rM  r;  handle_post_onlyamount_to_precisionr  r8  price_to_precisionr  r\  )r  r   r  r  r'  r(  rI  rM  r   postOnlyr^  r  r   isTriggerOrderstopLossTriggerPricetakeProfitTriggerPriceisStopLossTriggerOrderisTakeProfitTriggerOrderisStopLossOrTakeProfitTriggerr  r  s                        r  create_order_requestz"krakenfutures.create_order_request  s   V$$!T::&&v}==001A46>SYZZ& 	DDE!!DDW__DDXDTl,,VV<<
 

 **6?JOO$"/GJ))&.+NN%T1#//HH!%!1!1&:K!L!L!5T!A#9#E (>(ZBZ%((&II__V\::
( 	5N 	5'4GO$ 
	_D#'#:#:6<#P#PGK  * 	_J% _'+'>'>vG['\'\$$) _$'+'>'>vG]'^'^$ 	)$(GL!#$($;$;FE$J$JGL!6#w#w#wxx{{7F+++r  c                   K   |                                   d{V  |                     |          }|                     ||||||          }|                     |           d{V }	|                     |	d          }
|                     |
d          }|                     |ddg           |                     |
|          S )ao  
        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>`
        N
sendStatusstatusrH   filled)rZ  rM  r  privatePostSendorderr8  r;  verify_order_action_successparse_order)r  r   r  r  r'  r(  rI  rM  orderRequestrJ  r  r  s               r  create_orderzkrakenfutures.create_orderQ  s      * !!!!!!!!!V$$00tVUTZ[[22<@@@@@@@@D __X|<<
!!*h77((
KKK
F333r  r   c           	      B  K   |                                   d{V  g }t          dt          |                    D ]}||         }|                     |d          }|                     |d          }|                     |d          }|                     |d          }	|                     |d          }
|                     |di           }|                     ||          }d	|vr&|                     |t          d
                    |d	<   d|d<   |                     ||||	|
|          }|	                    |           d|i}| 
                    |                     ||                     d{V }|                     |dg           }|                     |          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>`
        Nr   r   r  r  r'  r(  rI  	order_tagr  sendr  
batchOrderbatchStatus)rZ  r9  r:  r;  r8  r\  r  strr  rC  privatePostBatchorderrd  parse_orders)r  r   rI  ordersRequestsrL  rawOrderr  r  r  r'  r(  orderParamsextendedParamsr  r^  rJ  datas                    r  create_orderszkrakenfutures.create_orders  s      !!!!!!!!!q#f++&& 	0 	0AayH''(;;H##Hf55D##Hf55D__Xx88FOOHg66E//(HbAAK![[f==N>11.2hhq#a&&.A.A{+&,N7#44XtT6SXZhiiL!!,////.
 33DKK4P4PQQQQQQQQ" ~~hr::  &&&r  r3   c                 h  K   |                                   d{V  d|i}|||d<   |||d<   |                     |                     ||                     d{V }	|                     |	d         d          }
|                     |
ddg           |                     |	d                   }|	|d	<   |S )
a'  

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

        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>`
        Nr  r  r  
editStatusr  rO   r  r4  )rZ  privatePostEditorderr\  r;  r  r  )r  r3   r   r  r  r'  r(  rI  r^  rJ  r  r  s               r  
edit_orderzkrakenfutures.edit_order  s       !!!!!!!!!r
 $GFO$)GL!224;;w3O3OPPPPPPPP!!(<"8(CC((xjIII  ,!788 fr  c                   K   |                                   d{V  |                     |                     d|i|                     d{V }|                     |                     |di           d          }|                     |d           i }d|v r|                     |d                   }|                     d|i|          S )aa  

        https://docs.kraken.com/api/docs/futures-api/trading/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>`
        Nr  cancelStatusr  rE   r4  )rZ  privatePostCancelorderr\  r;  r8  r  r  )r  r3   r   rI  rJ  r  r  s          r  cancel_orderzkrakenfutures.cancel_order   s       !!!!!!!!!44T[[*bAQSY5Z5Z[[[[[[[[!!$//(NB"O"OQYZZ((???X%%$$Xn%=>>E{{FH-u555r  idsc                 N  K   |                                   d{V  g }|                     |dg           }t          |          }|dk    r?t          dt          |                    D ] }|                    d||         d           !n>t          dt          |                    D ] }|                    d||         d           !d|i}|                     |                     ||                     d{V }	|                     |	dg           }
|                     |
          S )	a  
        cancel multiple orders

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

        :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>`
        NclientOrderIdsr   cancel)r  r  )r  r  r   r  )	rZ  r8  r:  r9  rC  r  r\  rd  r  )r  r  r   rI  r   r  clientOrderIdsLengthrL  r^  rJ  r  s              r  cancel_orderszkrakenfutures.cancel_orders  s[      !!!!!!!!!1A2FF">22!##1c.1122 R RnQ>OPPQQQQR 1c#hh'' G Gc!fEEFFFF&
 33DKK4P4PQQQQQQQQ< nnX}bAA  ---r  c                   K   i }||                      |          |d<   |                     |                     ||                     d{V }|                     |d          }|                     |dg           }g }t          dt          |                    D ]D}|                     |d          }	|                     |	di           }
|                    |
           E|                     |          S )a4  

        https://docs.kraken.com/api/docs/futures-api/trading/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
        Nr   r  orderEventsr   r  )		market_idprivatePostCancelallordersr\  r  rd  r9  r:  rC  r  )r  r   rI  r^  rJ  r  r  r   rL  
orderEventr  s              r  cancel_all_orderszkrakenfutures.cancel_all_ordersP  s        $v 6 6GH88Wf9U9UVVVVVVVV@ ~~h??nn\="EEq#k**++ 	! 	!AQ77JNN:w;;EMM%      (((r  timeoutc                    K   |                                   d{V  d|dk    r|                     |dz            ndi}|                     |                     ||                     d{V }|S )as  
        dead man's switch, cancel all orders after the given timeout

        https://docs.kraken.com/api/docs/futures-api/trading/cancel-all-orders-after

        :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
        Nr  r   r  )rZ  r  privatePostCancelallordersafterr\  )r  r  rI  r^  rJ  s        r  cancel_all_orders_afterz%krakenfutures.cancel_all_orders_after  s       !!!!!!!!!w{{))'D.999QR
 ==dkk'SY>Z>Z[[[[[[[[ r  c                    K   |                                   d{V  d}||                     |          }|                     |           d{V }|                     |dg           }|                     ||||          S )ab  

        https://docs.kraken.com/api/docs/futures-api/trading/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)rZ  rM  privateGetOpenordersrd  r  r  r   r  r   rI  rM  rJ  r   s           r  fetch_open_orderszkrakenfutures.fetch_open_orders  s       !!!!!!!!![[((F226::::::::,;;  >>>r  c                    K   |                                   d{V  d}||                     |          }|                     |           d{V }|                     |dg           }|                     ||||          S )aD  
        Gets all orders for an account from the exchange api

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

        :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>`
        Nr   )rZ  rM  privateGetOrdersStatusrd  r  r&  s           r  fetch_orderszkrakenfutures.fetch_orders  s       !!!!!!!!![[((F44V<<<<<<<<(B77  >>>r  c           	        K   |                                   d{V  d|gi}|                     ddd|                     ||                     d{V }|                     |d          }|t	          | j        dz   |z             |S )a  
        fetches information on an order made by the user

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

        :param str id: the order id
        :param str symbol: unified market symbol that the order was made in
        :param dict [params]: extra parameters specific to the exchange API endpoint
        :returns dict: An `order structure <https://docs.ccxt.com/?id=order-structure>`
        NorderIdsr   z$ fetchOrder could not find order id )rZ  r*  r\  r  r$   r3   )r  r3   r   rI  r^  r   r  s          r  fetch_orderzkrakenfutures.fetch_order  s       !!!!!!!!!
 ((tT4;;wPV;W;WXXXXXXXXvq))=*P PSU UVVVr  c                 ^  K   |                                   d{V  d}||                     |          }i }|||d<   |||d<   |                     |ddd          }d}|rH|                     |ddg          }|                     |                     ||                     d{V }n/|                     |                     ||                     d{V }|                     |dg           }	g }
t          dt          |	                    D ]}|	|         }| 
                    |d	i           }|                     |d
d          }|M| 
                    |di           }|                     |d          }|dk    rd|d<   |
                    |           |                     |
|||          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
        :param bool [params.trigger]: set to True if you wish to fetch only trigger orders
        :returns: An array of `order structures <https://docs.ccxt.com/?id=order-structure>`
        Nr  r  r   stopFr  r   r  OrderPlacedOrderTriggerActivatedr  r  r   closedr  rZ  rM  safe_bool_2r  historyGetTriggersr\  historyGetOrdersrd  r9  r:  r  safe_dict_2r;  rC  r  )r  r   r  r   rI  rM  r^  	isTriggerrJ  	allOrdersclosedOrdersrL  r  r  orderPlaced
innerOrderr  s                    r  fetch_closed_ordersz!krakenfutures.fetch_closed_orders  s      !!!!!!!!![[((F$GG#GFO$$VYFF	 	QYYv	6':;;F!44T[[&5Q5QRRRRRRRRHH!224;;w3O3OPPPPPPPPHNN8Z<<	q#i..)) 		4 		4AaLENN5'266E**5-AXYYK&!^^K"EE
))*h??S==+3Jx( ''
333  vueDDDr  c                   K   |                                   d{V  d}||                     |          }i }|||d<   |||d<   d}|                     |ddd          }|rH|                     |ddg          }|                     |                     ||                     d{V }n/|                     |                     ||                     d{V }|                     |dg           }	g }
t          dt          |	                    D ] }|	|         }| 
                    |d	i           }d
|v }|                     |dd
          }|O| 
                    |di           }|                     |d          }|dk    s|rd|d<   |
                    |           | 
                    |d          }|1| 
                    |di           }d|d<   |
                    |           | 
                    |d          }|1| 
                    |di           }d|d<   |
                    |           "|                     |
|||          S )aR  

        https://docs.kraken.com/api/docs/futures-api/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
        :param bool [params.trigger]: set to True if you wish to fetch only trigger orders
        :returns: An array of `order structures <https://docs.ccxt.com/?id=order-structure>`
        Nr  r  r   r/  Fr  r   r  OrderTriggerCancelledr0  r  r  r   canceledr  OrderCancelledOrderRejectedrejectedr3  )r  r   r  r   rI  rM  r^  rJ  r8  r9  canceledAndRejectedrL  r  r  isCancelledTriggerOrderr;  r<  r  orderCanceledorderRejecteds                       r  fetch_canceled_ordersz#krakenfutures.fetch_canceled_orders	  s      !!!!!!!!![[((F$GG#GFO$$VYFF	 	QYYv	6':;;F!44T[[&5Q5QRRRRRRRRHH!224;;w3O3OPPPPPPPPHNN8Z<<	 q#i..)) 	7 	7AaLENN5'266E'>%'G#**5-AXYYK&!^^K"EE
))*h??S==$;=+5Jx('..z::: NN52BCCM(!^^M7BGG
'1
8$#**:666 NN5/BBM(!^^M7BGG
'1
8$#**:666  !4feUKKKr  c                 >    ddddd}|                      |||          S )Nr   rM  )r  r  r   r  r;  )r  r  typesMaps      r  r  zkrakenfutures.parse_order_type?  s4    	
 
 )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 r8| 	                    ||          s$ ||         | j
        dz   |z   dz   |z             d S d S )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_successH  sI   

<
 <
 L	

 )*;
 
 !-
 #J
 3
 2
 ()9
 #J
 !,
  8
 !"2
  %m!
" #M#
$ %1#%)
 
 
, fdmmFD&A&A &.4&!8;L!Lv!UVVV 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dddddd}|                      |||          S )Nplacedrx  	cancelledr@  rM  rC  rN  rO  rP  rQ  rR  rS  rT  rU  rV  rW  rX  rY  rZ  r[  r2  )r\  editedr]  r^  r  r   	untouchedpartiallyFilledENTERED_BOOKFULLY_EXECUTED	CANCELLEDTRIGGER_PLACEDPARTIALLY_FILLED	UNTOUCHEDrJ  )r  r  statusess      r  parse_order_statusz krakenfutures.parse_order_statusb  s(   !
f!
!
 
!
 :	!

 :!
 J!
 )*!
 
!
 !*!
 #J!
 z!
 j!
 (!
 #J!
 !*!
" 
#!
$ !*%!
& '1$.$."%"&#$ &A!
 !
 !
D &&999r  r  c                 
   |                      |d          }||                     |d          }|                     |d          }|                      |di           }|                     |d          }|                     i d|d|                     |d          d	|                     |d
g          d|                     |          d|dd d|                     |                     |d                    d|                     |                     |d          |          dd dd dd d|                     |d          d|                     |d          dd d|d|d|                     |d          d d |                     |d          d |                     |          d d d d          S |                     |dg           }|                     |d          }	t          |          }
d|v r |	|
dk    r|                     |dd          S d }d}d}d }d }g }|
rg }t          dt          |                    D ]}||         }|                     |d          dk    r|                    |           |                     |d           }||                     |d!d|          }|d}d"}p|sb|                     |d          }|                     |d#          }|                     |d#d$          }||                     |d%          }n|}|d"}|                     |          }|                     |d          }||}||                     |d          }|                     |          }|                     |g d&          }|                     |dd'          }|                     ||          }|                     |d          }|                     |                     |dd(                    }|                     |                     |d)                    }|                     |d          }|                     |d*dd+          }|                     |d,          }d } d+}!t          |          }"|"dk    rd+}#t          dt          |                    D ]s}||         }$|                     |$d          }%|                     |$d          }&t#          j        |!|%          }!t#          j        |#t#          j        |%|&                    }#tt#          j        |#|!          } ||s|rt#          j        |!|          rd-}d"}|rt#          j        ||!          }nt#          j        ||!          }||r|t#          j        ||!          }n|}||s|t#          j        ||          }d }'|=|;| | n|}(|(3|d.         rt#          j        ||(          }'nt#          j        ||(          }'|                     |d/d          })|)|                     |dd0          })|                     |dd1          }*d2}+|*d3k    s|                     |*          d4k    rd3}+|                     |d|          },|                      |di           }-|                     |dd          }.|.|                     |-d          }.|                     i d|d|)d	|                     |g d5          d|,d|                     |,          dd d|                     |d|          d|d|                     |*          d|+d|*d6k    d|                     |dd7          d|                     |dd8          d|d|.d|.d||'| |||d d |d          S )9Nr  r_  r  priceTriggerOptionsr   r4  r3   r  r  r  rn  lastTradeTimestamplastUpdateTimestampr   r  r   r  r  r  r(  r  r'  r  r  )r*  r|  r  	remainingr  r  r   tradesr  r   rC  )r4  r  F	EXECUTIONorderTriggernewTr  r  r  )r@  rC  r2  r$  receivedTimelastUpdateTime
filledSizer  unfilledSizer2  r   r  r  r  gtcr  rM  )r  clientIdr  r   reduce_onlyr  )r  r;  
safe_orderr  r=  safe_symbolrD  rn  r8  r:  r9  rC  safe_value_2r  r_  r  r  r.   r  r  r  	string_ge
string_maxr  safe_string_lower_2r  r  rE  r4  )/r  r  rM  orderDictFromFetchOrderrn  innerStatusfetchOrderPriceTriggerOptionsfetchOrderTriggerPricer  errorStatusorderEventsLengthdetailsisPriorfixedstatusIdr(  rt  r   rL  itemrv  executedPricer  r  isClosedr  r   r_  rr  r'  r  rs  r|  filled2tradesLengthvwapSumr  tradeAmount
tradePricer*  
whichPricer3   r  r   tsrp  r   s/                                                  r  r  zkrakenfutures.parse_order  sQ	   x #'.."@"@".$ ''(?MMH**5(;;K,0NN;RTikm,n,n)%)%5%56SUc%d%d"?? $$d&&'>	JJ$  !3!34Kj\!Z!Z$ T^^H55	$
 H$ %d$ &t~~d6F6FG^`u6v6v'w'w$ $**4+;+;<SU]+^+^`fgg$ $ t$ D$ dnn-DlSS$ (()@&II$ $  6$  3!$" $**+BJOO#$$ **+BHMM!11+>>3$ $ $   6 ooe]B??&&uh77,,U"")@GX\]G]G]??EZ#H#HIII 	9J1c+..// + +"1~##D&11[@@%%d+++#t^DD?"//eWlSSG*"' $" 	+(,(8(8w(G(G.2oodDY.Z.Z+"&"3"3D:OQa"b"b(0$($4$45H,$W$WEE$1E".&*G&&z22F''x88H?G''::H ((22==)K)K)KLL%%gxEE!!(F33!!&(33NN4#5#5g{N#[#[\\	"nnT-=-=gGW-X-XYY!!':66##G\8UKK$$Wn==	6{{!G1c&kk** c cq	"..uh??!--eW==
!,WkBB!,Wg6HV`6a6abb('::G"X"7"wGXY`bhGiGi"! = +FG<< +FG<< #% ' 267 C CI"	NWN93H'	::FV%7%,%8uJ%(# B"-fjAADD"-fjAADz9==:##GY>>B''EE5==D11$778CCKwY??"nnW6KRPP))'>;OO++,?PPL  
E 
" 
 T//9b9b9bcc 
 	 

 R(( 
 !$ 
 "4#4#4W>SUh#i#i 
 f 
 D))$// 
 ; 
  
 $**7L-PP 
 D,,WfkJJ 
 U 
 L 
  ! 
" f# 
$ "3 
  
  
   	r  c                    K   |                                   d{V  d}||                     |          }|                     |           d{V }|                     |d         |||          S )ab  
        fetch all trades made by the user

        https://docs.kraken.com/api/docs/futures-api/trading/get-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   )rZ  rM  privateGetFillsr  )r  r   r  r   rI  rM  rJ  s          r  fetch_my_tradeszkrakenfutures.fetch_my_tradesW  s       !!!!!!!!![[((F--f55555555*   '!2FE5IIIr  c                   K   |                                   d{V  |                     |dd          }|                     |d          }|                     |g d          }|                     |           d{V }|                     |d          }|dk    s|dk    r|t          | j        d	z             |}||d
n|}|                     |          }|                     |d          }|                     ||          }|&|dn|}|dn|}t          | j        dz   |z             | 
                    |          }	||	d<   |                     |          |	d<   ||	d<   |	S )a  

        https://docs.kraken.com/api/docs/futures-api/trading/get-accounts

        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>`
        Nr  accountr   )r  r  r   rX  marginAccountr?   z: fetchBalance requires symbol argument for margin accountsr   r    z! fetchBalance has no account for r4  r_  rn  )rZ  r  r;  r  privateGetAccountsr    r3   parse_accountr8  r!   parse_balancer=  )
r  rI  r  r   rJ  rn  accountNamer   r  balances
             r  fetch_balancezkrakenfutures.fetch_balance  s      !!!!!!!!!!!&&)<<!!&(336#@#@#@AA0088888888p ##Hl;;?""dh&6&6~'2n(noooD<$n666D((..??8Z88//(K88?,22TD"NRRFTW'JJTQRRR$$W--"#~~h77&
r  c                    |                      |dd          }|dk    }|dk    }|                     |ddi           }i }t          |                                          }t	          dt          |                    D ]}||         }	||	         }
|                     |	          }|                    d          }t          |          }|d	k    rR|                                 }|r3| 	                    |
d
          |d<   | 	                    |
d          |d<   nU|rd|d<   |
|d<   nH| 
                    |d          }| 	                    |d          |d<   | 	                    |d          |d<   |||<   |                     |          S )NaccountTyper  multiCollateralMarginAccountcashAccountbalancesrH  r   r  r  r  total	availablefreer  used	auxiliaryafpv)r  r  listkeysr9  r:  r?  r>  r  r;  r8  safe_balance)r  rJ  r  isFlexisCashr  rK  currencyIdsrL  
currencyIdr  r6  	splitCode
codeLengthr  r  s                   r  r  zkrakenfutures.parse_balance  s   ~ ((=&II!??.$$Xz<LL8==??++q#k**++ 	# 	#A$QJz*G**:66D

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

        https://docs.kraken.com/api/docs/futures-api/trading/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>`
        Nr   r   r   )rZ  
market_idsrc  rd  r9  r:  r8  r_  r  parse_funding_raterC  index_by)r  ra  rI  	marketIdsrJ  r   fundingRatesrL  entryentry_symbolrM  parseds               r  fetch_funding_ratesz!krakenfutures.fetch_funding_ratesV	  s)      !!!!!!!!!OOG,,	..v66666666..9b99q#g,,'' 	( 	(AAJE??5(;;L$}}\9== %%l33F,,UF;;F''''}}\8444r  c                 p   |                      |d          }|                     |          }|                     |                      |d                    }|                      |d          }|                      |d          }t          j        ||          }|                      |d          }	t          j        |	|          }
t          j        |d          rd}nt          j        |d          rd}t          j        |
d          rd}
nt          j        |
d          r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iS )Nr   ri  r}  fundingRatefundingRatePredictionz0.25z-0.25r4  r~  interestRateestimatedSettlePricer_  rn  fundingTimestampfundingDatetimenextFundingRatenextFundingTimestampnextFundingDatetimepreviousFundingRatepreviousFundingTimestamppreviousFundingDatetimer  r  )
r;  r   r=  r.   r  	string_gt	string_ltr
  rA  rE  )r  rg  rM  r  r   r_  markPriceStringfundingRateStringfundingRateResultnextFundingRateStringnextFundingRateResults              r  r  z krakenfutures.parse_funding_ratep	  sV   8 ##FH55X&&NN4#3#3FJ#G#GHH	**6;?? ,,V]CC#./@/RR $ 0 09P Q Q ' 23H/ Z Z.77 	( &0':: 	( '2F;; 	,$*!!4g>> 	,$+!
F
f
 **?;;
 $**6<@@	

 D
 #D
 
 Y//
 4,,->??
 
 t
 t001FGG
 #D
 "4
 "4
  '!
" &t#
$ %
 
 	
r  c           	        K   |t          | j        dz             |                                  d{V  |                     |          }|d         st	          | j        dz             d|d                                         i}|                     |                     ||                     d{V }|                     |d          }g }	t          dt          |                    D ]b}
||
         }|                     |d	          }|	                    |||                     |d
          |                     |          |d           c|                     |	d	          }|                     ||||          S )a  
        fetches historical funding rate prices

        https://docs.kraken.com/api/docs/futures-api/trading/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>`
        Nz5 fetchFundingRateHistory() requires a symbol argumentr@   z7 fetchFundingRateHistory() supports swap contracts onlyr   r3   ratesr   r_  relativeFundingRate)r4  r   r  r_  rn  )r    r3   rZ  rM  r!   upperpublicGetHistoricalfundingratesr\  r8  r9  r:  r;  rC  rA  r=  sort_byfilter_by_symbol_since_limit)r  r   r  r   rI  rM  r^  rJ  r  rK  rL  r  rn  sorteds                 r  fetch_funding_rate_historyz(krakenfutures.fetch_funding_rate_history	  s      >#DG.e$efff!!!!!!!!!V$$f~ 	bTW'``aaafTl((**
 ==dkk'SY>Z>Z[[[[[[[[ '22q#e**%% 		 		A8D''k::HMM #//6KLL!^^H55$      fk2200NNNr  c                    K   |                                   d{V  i }|                     |           d{V }|                     |          }|                     |d|d          S )a5  

        https://docs.kraken.com/api/docs/futures-api/trading/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
        Nr   F)rZ  privateGetOpenpositionsparse_positionsfilter_by_array_positions)r  ra  rI  r^  rJ  rK  s         r  fetch_positionszkrakenfutures.fetch_positions	  s       !!!!!!!!!55g>>>>>>>>" %%h//--fhOOOr  c                     g }|                      |d          }t          dt          |                    D ]2}|                     ||                   }|                    |           3|S )NopenPositionsr   )r8  r9  r:  parse_positionrC  )r  rJ  ra  rI  rK  	positionsrL  positions           r  r  zkrakenfutures.parse_positions
  sj    OOHo>>	q#i..)) 	$ 	$A**9Q<88HMM(####r  r  c                    |                      |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S )NmaxFixedLeveragecrossisolatedr  r   r4  r_  rn  initialMargininitialMarginPercentagemaintenanceMarginmaintenanceMarginPercentage
entryPricer(  notionalr   unrealizedPnl	contractsr  r&  marginRatioliquidationPricer}  r  )
collateral
marginTyper  r   )rA  r;  r  r=  )r  r  rM  r   r  rn  r  s          r  r  zkrakenfutures.parse_position

  s   . ##H.@AA
#J##Hj99##Hh77!!(F33
H
fX&
 11
 	

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

        https://docs.kraken.com/api/docs/futures-api/trading/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
        Nr   r   )rZ  r7  rd  parse_leverage_tiers)r  ra  rI  rJ  r	  s        r  fetch_leverage_tiersz"krakenfutures.fetch_leverage_tiers@
  s       !!!!!!!!!226::::::::Z ~~h66((wAAAr  c                    |                      |d          }|                     |d          }|                     ||          }g }||S t          dt	          |                    D ]}||         }|                     |d          }|                     |dd          }	|dk    rt	          |          }
||
dz
           }|	|d	<   |                    |                     |d          |                     ||          |d
         |	d| 	                    |d          | 
                    t          j        d|                    |d           |S )z`
 @ignore
 @param info Exchange market response for 1 market
 @param market CCXT market
        marginLevelsr   Nr   r  numNonContractUnitsr  r  maxNotionalr  r  1)tierr   r  minNotionalr  r,  maxLeverager4  )r8  r;  r  r9  r:  safe_number_2rC  r  r  rA  r
  r.   r  )r  r4  rM  r   r  r   rL  r  r  r  tiersLengthpreviousTiers               r  parse_market_leverage_tiersz)krakenfutures.parse_market_leverage_tiers{
  se   N t^<<##D(33!!(F33Lq#l++,, 	 	A?D ,,T?CCM,,T3H+VVKAvv!%jj$[1_5.9]+LLA**8V<<"7O*#)-)9)9$@S)T)T#001CC1W1WXX	 	 	 	 	 	 r  rw   r  c                     |                      |d          }|d |                     |          ||                      |d          d d d |                      |d          d	S )NrX  r6  rK  )	r4  r3   r_  rn  r  r'  fromAccount	toAccountr  )r;  r=  )r  rw   r  rn  s       r  parse_transferzkrakenfutures.parse_transfer
  so     ##Hl;;11 ((6::&&x::

 

 
	
r  c           	         ddddddddd}||v r||         S || j         v rl|                     |          }|d         }|                    d          }|d         rd|                     |d          z   S d	|                     |d          z   S |S )
Ncashr   )mainfundingrA   futuresr  r  multiCollateralmultiCollateralMarginr3   r  r   fi_r  fv_)marketsrM  r>  r;  )r  r  accountByTyperM  r  splitIds         r  r  zkrakenfutures.parse_account
  s    !,2%%+	
 	
 m## ))$$[[))Fd|HnnS))Gi  <t//;;;;t//;;;;Nr  r6  c                 D   K   |                      ||dd|           d{V S )a1  
        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>   N)rw   )r  r6  r'  rI  s       r  transfer_outzkrakenfutures.transfer_out
  s4       ]]466JJJJJJJJJr  r  r  c                   K   |                                   d{V  |                     |          }|dk    rt          | j        dz             d|i}d}|dk    rt|                     |          dk    r t          | j        dz   |z   dz   |z             |d         |d	<   |                     |                     ||                     d{V }nj|                     |          |d
<   |                     |          |d<   |d         |d<   |                     |                     ||                     d{V }|                     ||          }	|                     |	|||d          S )a  

        https://docs.kraken.com/api/docs/futures-api/trading/transfer
        https://docs.kraken.com/api/docs/futures-api/trading/sub-account-transfer

        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>`
        Nr>   z2 transfer does not yet support transfers from spotr'  r  z transfer cannot transfer from z to r3   r  r  r  unit)r'  r  r  )	rZ  r  r!   r3   r  privatePostWithdrawalr\  privatePostTransferr  )
r  r6  r'  r  r  rI  r  r^  rJ  rw   s
             r  rw   zkrakenfutures.transfer
  s      !!!!!!!!!==&&&  TW'[[\\\f
 !!+..&88 +L!L{!Z]c!cfo!oppp"*4.GJ!77GV8T8TUUUUUUUUHH%)%7%7%D%DGM"#'#5#5i#@#@GK &tnGFO!55dkk'66R6RSSSSSSSSH &&x::{{8&"&
 &
   	r  r   c                   K   |t          | j        dz             |                                  d{V  ||                     |                                          d}|                     |                     ||                     d{V S )ax  
        set the level of leverage for a market

        https://docs.kraken.com/api/docs/futures-api/trading/set-leverage-setting

        :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
        Nz) setLeverage() requires a symbol argument)r  r   )r    r3   rZ  r  r  privatePutLeveragepreferencesr\  )r  r   r   rI  r^  s        r  set_leveragezkrakenfutures.set_leverage!  s       >#DG.Y$YZZZ!!!!!!!!!#nnV,,2244
 
 77GV8T8TUUUUUUUUUr  c                    K   |                                   d{V  |                     |           d{V }|                     |dg           }|                     ||d          S )a  
        fetch the set leverage for all contract and margin markets

        https://docs.kraken.com/api/docs/futures-api/trading/get-leverage-setting

        :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>`
        NleveragePreferencesr   )rZ  privateGetLeveragepreferencesrd  parse_leverages)r  ra  rI  rJ  r%  s        r  fetch_leverageszkrakenfutures.fetch_leverages8  s       !!!!!!!!!;;FCCCCCCCC #nnX7LbQQ##$7(KKKr  c                   K   |t          | j        dz             |                                  d{V  |                     |          }d|                     |                                          i}|                     |                     ||                     d{V }|                     |dg           }| 	                    |di           }| 
                    ||          S )al  
        fetch the set leverage for a market

        https://docs.kraken.com/api/docs/futures-api/trading/get-leverage-setting

        :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>`
        Nz+ fetchLeverage() requires a symbol argumentr   r%  r   )r    r3   rZ  rM  r  r  r&  r\  rd  r  parse_leverage)r  r   rI  rM  r^  rJ  r%  r	  s           r  fetch_leveragezkrakenfutures.fetch_leverageS  s       >#DG.[$[\\\!!!!!!!!!V$$dnnV,,2244
 ;;DKKQW<X<XYYYYYYYY #nnX7LbQQ~~11b99""4000r  c                     |                      |d          }|                     |d          }||                     ||          d ||dS )Nr   r  )r4  r   r   longLeverageshortLeverage)r;  r  r  )r  r   rM  r  leverageValues        r  r*  zkrakenfutures.parse_leveragep  sZ    ##Hh77))(MBB&&x88)*
 
 	
r  reasonurlr   headersbodyc
                    |d S |dk    rt          | j        dz   |z             |                     |d          }
|                     |
d          }|                     |d          }|                     |d|          }|d S | j        dz   |z   }|                     | j        d         ||           |                     | j        d         ||           |d	k    rt          |          t          |          )
Ni   r`  r   messageerrorr   r   i  )	r)   r3   r8  r;  throw_exactly_matched_exceptionr   throw_broadly_matched_exceptionr!   r   )r  r6  r0  r1  r   r2  r3  rJ  requestHeadersrequestBodyr`  
firstErrorfirtErrorMessager6  feedbacks                  r  handle_errorszkrakenfutures.handle_errors{  s   43;; 3!5666844__VQ//
++J	BB""8W6FGG?47S=4',,T_W-EwPXYYY,,T_W-EwPXYYY3;;X&&&H%%%r  ry   r   c                 z   |                      | j        d         |i           }|                      ||i           }|                     ||| j                  }	|                     |d|	          }
|                     |d          }|                      | j        d         |i           }|                      ||i           }|                     ||d          }|
dz   |                     ||          z   }|                     ||                     |                    }|}d}|dk    rd|                     |          z   }|}n9|r7d	|v r|                     |          }n| 	                    |          }|d
|z   z  }| j
        d         |         |z   }|dk    s|dk    r|                                  |dz   }|dk    r||dz   z  }||z  }|                     |                     |          dd          }|                     | j                  }|                     ||t"          j        d          }dd| j        |d}||||dS )Nr   r7   r   ry   r  r  r   zjson=r,  ?r   rz   z/api/sha256binarybase64z!application/x-www-form-urlencodedzapplication/json)zContent-TypeAcceptAPIKeyAuthent)r1  r   r3  r2  )r8  r   r;  r7   r  implode_paramsextract_paramsjsonurlencode_with_array_repeat	urlencoderx   check_required_credentialshashencodebase64_to_binarysecrethmachashlibsha512apiKey)r  pathr   r   rI  r2  r3  apiVersionsmethodVersionsdefaultVersionr7   	apiAccessmethodAccessr   endpointquerypostDatar1  authrN  rQ  	signatures                         r  signzkrakenfutures.sign  s]   oodl:&>RHHfbAA)).$MM""69nEE69--OODL$:CDD	y&"==!!,h??S=4#6#6tV#D#DD64#6#6t#<#<==<6!2!22HDD 	$V##;;FCC>>&11S8^#Eis#e+)v22++---g%Dic	!HD99T[[..(CCD**4;77F		$III C,+$	 G fdwOOOr  )N)Q__name__
__module____qualname__r   r	  r   r   rV  r  r   r   r`  r   r   rf  dictr   r  r  r  r  r   r  r  r   r   floatr   r  r  r   r
  r  r   r  r  r  r"  r   r'  r*  r-  r=  rH  r  r  rn  r  r  r   r  r  r   r  r   r  r  r   r  r  r  r   r  r   r
  r   r   r  r  r  rw   intr#  r
   r(  r	   r+  r*  r?  ra  __classcell__)r  s   @r  r0   r0      s	       Y# Y Y Y Y Y Yv
 *, f fV f f f fP @DB 0O 0OS 0O 0OS\ 0O 0O 0O 0Od 6:" -4 -47 -4 -4 -4 -4 -4^D D4 D D6 D D D DL ?CQUdhqs 9K 9K 9K 9K3 9K^a 9Kx|  ~B  yC 9K 9K 9K 9Kv
 
 
4 
 
 
 
( <@d[] wB wB wBS wB wBbfglbm wB wB wB wBrH H Hv H H H H HT os{} 3, 3,3 3,i 3,y 3,Z_ 3,hk 3, 3, 3, 3,j mqy{ ]4 ]4 ]4I ]4Y ]4X] ]4fi ]4 ]4 ]4 ]4~ FH 0' 0'$|*< 0' 0' 0' 0'd fjx|  FH  3  9 I _b ru    < 9=R 6 6S 6# 6 6 6 6( AER :. :.tCy :.# :. :. :. :.x 59 4) 4)c 4) 4) 4) 4)l BD  S    6 59tZ^gi ? ?c ? ?TW ?nrsxny ? ? ? ?( 04$UYbd ? ? ?C ?s ?imnsit ? ? ? ?( 8<B  C     * 7;\`ik )E )E )E3 )EVY )Eptuzp{ )E )E )E )EV 9=4^bkm 4L 4L# 4LS 4LX[ 4Lrvw|r} 4L 4L 4L 4Ll@ @ @ @B W W W W4#: #: #: #: #:JN N Nv N N N N N` 37TX\eg 'J 'JC 'Js 'JRU 'J 'J 'J 'JR *, y y y y y yvY) Y) Y) Y) Y)v <@ 5 5 5| 5 5 5 54?
 ?
 ?
; ?
 ?
 ?
 ?
B >BPTcgpr /O /Os /O# /O]` /O /O /O /Ob 8<B P PW P4PX> P P P P@ <@      4
 4
t 4
V 4
 4
 4
 4
l =A 9B 9B' 9BP] 9B 9B 9B 9Bv? ? ?$|J\ ? ? ? ?B
 
t 
x 
= 
 
 
 
,  0 <> K Ks K K K K ac + +3 + +C +TW +gt + + + +Z ?C2 V V3 V V V V V. 8<B L LW L9 L L L L6 8: 1 13 1h 1 1 1 1:	
 	
t 	
V 	
x 	
 	
 	
 	
&# &s & &c &TX &`c & & & &$ &eBSW &P &P &P &P &P &P &P &Pr  r0   )5 ccxt.async_support.base.exchanger   ccxt.abstract.krakenfuturesr   rS  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>rq     s   6 5 5 5 5 5 3 3 3 3 3 3  H  H  H  H  H  H  H  H  H  H  H  H  H  H  H  H  H  H  H  H  H  H  H  H  H  H  H  H  H  H  H  H  H  H  H  H  H  H  H  H  H  H  H  H  H  H  H  H  H  H  H  H       * * * * * * 0 0 0 0 0 0 . . . . . . ' ' ' ' ' ' . . . . . . ) ) ) ) ) ) * * * * * * 5 5 5 5 5 5 - - - - - - - - - - - - 0 0 0 0 0 0 + + + + + + . . . . . . 1 1 1 1 1 1 ) ) ) ) ) ) 4 4 4 4 4 4 % % % % % %U.P U.P U.P U.P U.PHk U.P U.P U.P U.P U.Pr  