
    !:hD                       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 d dlmZ d dlmZ d dlmZ d dlmZ d d	lmZ d d
lmZ d dlmZ d dlmZ d dlmZ d dlm Z  d dlm!Z! d dl"m#Z# d dl$m%Z%  G d dee      Z&y)    )Exchange)ImplicitAPIN)AnyBalancesIntMarketNumOrder	OrderBook	OrderSide	OrderTypeStrStringsTickerTickersFundingRateTrade)List)AuthenticationError)AccountSuspended)ArgumentsRequired)
BadRequest)InvalidOrder)OrderNotFound)NotSupported)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edefdZ	d<dedede
fdZi fd	ede
fd
Zdi fdedefdZdi fd	ededefdZdi fd	edefdZd<dededefdZddi fd	ededede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efdZi f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#fdZ$di fdefd Z%d<d!edefd"Z&dddi fd	e#dedefd#Z'di fd	e#fd$Z(dddi fd	e#dedefd%Z)dddi fd	e#dededee*   fd&Z+dddi fd	e#dededee*   fd'Z,di fde#d	e#fd(Z-d<d)edede*fd*Z.i fd	ede/fd+Z0i fd	ede/fd,Z1d<dede/fd-Z2d. Z3dddi fd	e#dedefd/Z4di fd0ed	e#fd1Z5d2d3i ddfd4Z6d5e7d6ed7ed8ed9ed:efd;Z8 xZ9S )=poloniexfuturesreturnc                    | j                  t        t        |          i ddddddgddd	d
dddddi dd dd
dddddd
dd dddddddddddd
dd
dd
dd
ddd d
i d!dd"d
d#dd$dd%dd&dd'dd(dd)dd*dd+dd,dd-dd.dd/dd0dd1d2d3d4d5d6d7d8d9d:d;d<
d=d>d?d?d@dAdBdCdDdEdFi dGdHdIdHdJdHdKdHdLdMdNdMdOdMdPdMdQdHdRdHdSdHdTdHdUdHdVdHdWdHdXdHdYdHdZdHid[i d\d2d]d2d^d2d_d2d`d2dad2dbd2dcd2ddd2ded2dfd2dgd2dhd2didjdkdjdld2djdjdjdjdjd2d2dmdjdndndodpd@dqt        drd
d| j                  ds      | j                  dt      dud
d
i i dvdwdxi dyddddzd{d|d}d~dddddddiiddd
d
ddddddd
d
d dd
dd
dd
ddd
d
d
ddd d
d ddd
dd
d
d
d
ddd d
d
d
dd d
ddd2dd
d
d
dddid	d ddid dd d dddi dt        dt        dt        dt        dt        dt        dt        dt        dt        dt        dt        dt        dt        dt        dt        dt        dt        t        t        t        ddt        idi      S )Nidr"   namezPoloniex Futures	countriesUS	rateLimitgfffff@@	certifiedFproTversionv1hasCORSspotmarginswapfutureoptioncreateOrdercreateStopOrdercreateTriggerOrderfetchBalancefetchClosedOrdersfetchCurrenciesfetchDepositAddressfetchDepositAddressesfetchDepositAddressesByNetworkfetchFundingIntervalfetchFundingIntervalsfetchFundingRatefetchFundingRateHistoryfetchL3OrderBookfetchMarketsfetchMyTrades
fetchOHLCVfetchOpenOrders
fetchOrderfetchOrderBookfetchOrdersByStatusfetchPositionsfetchTickerfetchTickers	fetchTimefetchTradessetMarginMode
timeframes            <   x   i  i  i  i`'  )
1m5m15m30m1h2h4h12h1d1wurlszchttps://user-images.githubusercontent.com/1294454/27766817-e9456312-5ee6-11e7-9b3c-b628ca5626a5.jpgz https://futures-api.poloniex.com)publicprivatezhttps://www.poloniex.comz&https://api-docs.poloniex.com/futures/z!https://poloniex.com/fee-schedulez&https://poloniex.com/signup?c=UBFZJRPJ)logoapiwwwdocfeesreferralre   zcontracts/active
   zcontracts/{symbol}tickertickerszlevel2/snapshotgMbf@zlevel2/depthzlevel2/message/querylevel3/snapshotztrade/historyzinterest/queryzindex/queryzmark-price/{symbol}/currentzpremium/queryzfunding-rate/{symbol}/current	timestampstatuszkline/queryzbullet-public)getpostzaccount-overviewztransaction-historymaxActiveOrdersmaxRiskLimituserFeeRatezmarginType/queryorders
stopOrdersrecentDoneOrdersorders/{order-id}zclientOrderId/{clientOid}fillsopenOrderStatisticspositiong      ?	positionszfunding-history)ru   batchOrdersz#position/margin/auto-deposit-statuszposition/margin/deposit-marginzposition/margin/withdraw-marginzbullet-privatezmarginType/changegnb@)rx   ru   rv   )rp   rq   deleteprecisionModerh   z0.00075z0.0001)	tierBased
percentagetakermaker)r   r   withdrawdeposit)tradingfundingcommonCurrenciesrequiredCredentials)apiKeysecretpasswordoptionsomniethtrx)OMNIERC20TRC20rb   GETv2)rk   rl   rm   )networksversionsfeatures)lastmarkindex)IOCFOKPOGTD)
marginModetriggerPricetriggerPriceTypetriggerDirectionstopLossPricetakeProfitPriceattachedStopLossTakeProfittimeInForcehedgedleveragemarketBuyByCostmarketBuyRequiresPriceselfTradePreventiontrailingicebergi    )r   limitdaysBack	untilDayssymbolRequired)r   triggerr   r   )r   r   r   r   r   d   )r   r   r   daysBackCanceledr   r   r   r   r      )	sandboxr5   createOrdersrD   rG   rF   fetchOrdersr9   rE   extendsdefault)linearinverse)r   r0   r2   r3   
exceptions400401403404405415429500503400001400002400003400004400005400006400007404000)400100411100500000zPosition does not exist)exactbroad)deep_extendsuperr"   describer   parse_numberr   r   r   r   r   r   r   r   )self	__class__s    N/var/www/html/turnos/venv/lib/python3.12/site-packages/ccxt/poloniexfutures.pyr   zpoloniexfutures.describe   sI   ot E G NJ
#NJ
&NJ
 $NJ

 NJ
 NJ
 4NJ
 tNJ
  """ $" 	"
 %" $" t" "4" %d" " $T" "5" &u" (" 1%"  '!"" (#"$ #D%"& *5'"( #D)"* +",  -". d/"0 "41"2 d3"4 !$5"6 &t7"8 !$9": t;"< ="> T?"@ tA"B  C"NJ
X YNJ
p }@A 2?;D
qNJ
F *B,b !" "2	
 *7 ' / *7 ( )" &r 6r ( 8 $R  !"!" &r#( ()2*A-q *1 '	
 &q +A !! %a +A ,Q 4Q   .q #C $S  *1!& #&'*?B:=;>*+-. .1")&-9!3;GNJ
~ YNJ
@ !&"&!..y9!..x8	 "'"' "!	ANJ
\  !]NJ
` " $aNJ
j """ &*'+/3 kNJ
J $&+(, %)$(%)-
 -1).+06:#'#("&#(	( #($(+/27/4$)#'3$6 %)&+!%$*%&*/& ',#($)*/	# '+!%#($)*/( $(&+!$$*,-%+#($)*/	*  #{@B  "9  $	 ##SMKNJ
f :. < <	
 < : , / / 1 l 1 1 1 1  1!" l#$ ).2). .}/gNJ
 N N	    c                 l    | j                  |      }| j                  |dg       }| j                  |      S )a  
        retrieves data on all markets for poloniexfutures

        https://api-docs.poloniex.com/futures/api/symbol

        :param dict [params]: extra parameters specific to the exchange API endpoint
        :returns dict[]: an array of objects representing market data
        data)publicGetContractsActive
safe_valueparse_markets)r   paramsresponser   s       r   fetch_marketszpoloniexfutures.fetch_markets,  s:     008~ x4!!$''r   marketc                    | j                  |d      }| j                  |d      }| j                  |d      }| j                  |d      }| j                  |      }| j                  |      }| j                  |      }|dz   |z   dz   |z   }	| j                  |d      }
| j                  |d      }| j                  |d	      }| j                  |d
      }| j                  |d      }| j                  |d      }| j                  |d      }i d|d|	d|d|d|d|d|d|ddddddddddddd|dk(  ddd |
 |
| j                  |d!      | j                  |d"      | j	                  t        j                  |            d d d d ||d#| j	                  d$      | j                  |d%      d&||d&||d&d d d&d'| j                  |d(      |d)S )*NsymbolbaseCurrencyquoteCurrency
rootSymbol/:	isInversero   
multiplierindexPriceTickSizelotSizemaxOrderQtymaxPricer%   basequotesettlebaseIdquoteIdsettleIdtyper2   r0   Fr1   Tr3   r4   activeOpencontractr   takerFeeRatemakerFeeRate)amountprice1maxLeverage)minmax)r   r   r  costfirstOpenDate)r   r   r   contractSizeexpiryexpiryDatetimestrike
optionType	precisionlimitscreatedinfo)safe_stringsafe_currency_coder   safe_numberr   r    
string_abssafe_integer)r   r   r%   r   r   r   r   r   r   r   r   ro   r   tickSizer   limitAmountMaxlimitPriceMaxs                    r   parse_marketzpoloniexfutures.parse_marketw  s   fh/!!&.9""6?;##FL9&&v.''0((2e#c)F2//&+6!!&(3%%fl;
##F,@A""695))&-@((<2
"2
f2
 D2
 U	2

 f2
 f2
 w2
 2
 F2
 E2
 e2
 D2
 e2
 e2
 v'2
  !2
" 'k#2
$ %%fn=%%fn= --g.@.@.LM"!!  ,,S1++FMB
 #)
 $(
  $ ((Ac2
 2	
r   Nrk   c                    | j                  |d      }| j                  ||      }| j                  |d      }d }t        |      dk(  rd}n$t        |      dk(  rd}nt        |      dk(  rd}nd	}| j                  |d|      }| j	                  |d
d      }t        j                  | j                  |d      d      }	| 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 d |	d!d | j	                  |d"d#      | j                  |d$      |d%|      S )&Nr   ts   gMbP?   g-C6?   gh㈵>ư>r  	lastPricepriceChgPct100rn   datetimehighlowbidbestBidPrice	bidVolumebestBidSizeaskbestAskPrice	askVolumebestAskSizevwapopencloser   previousClosechanger   averagesizevolumeturnover)
baseVolumequoteVolumer  )	r  safe_symbollensafe_integer_productsafe_string_2r    
string_mulsafe_tickeriso8601)
r   rk   r   marketIdr   timestampStringr   rn   r   r   s
             r   parse_tickerzpoloniexfutures.parse_ticker  s   0 ##FH5!!(F3**648
2%J!R'J!R' J "J--fdJG	!!&';?''(8(8(OQVW
 !
f!
!
 Y/!
 D	!

 4!
 4##FN;!
 ))&-@!
 4##FN;!
 ))&-@!
 D!
 D!
 T!
 D!
 T!
 d!
  *!!
" t#!
$ ,,VVXF++FJ?)!
* + 	r   r   c                     | j                          | j                  |      }d|d   i}| j                  | j                  ||            }| j	                  | j                  |di       |      S )a  
        fetches a price ticker, a statistical calculation with the information calculated over the past 24 hours for a specific market

        https://api-docs.poloniex.com/futures/api/ticker#get-real-time-ticker-20

        :param str symbol: unified symbol of the market to fetch the ticker for
        :param dict [params]: extra parameters specific to the exchange API endpoint
        :returns dict: a `ticker structure <https://docs.ccxt.com/#/?id=ticker-structure>`
        r   r%   r   )load_marketsr   publicGetTickerextendrB  r   )r   r   r   r   requestr   s         r   fetch_tickerzpoloniexfutures.fetch_ticker  sm     	V$fTl
 ''GV(DE&   62!FOOr   symbolsc                     | j                          | j                  |      }| j                  |dg       }| j                  ||      S )a0  
        fetches price tickers for multiple markets, statistical information calculated over the past 24 hours for each market

        https://api-docs.poloniex.com/futures/api/ticker#get-real-time-ticker-of-all-symbols

        :param str[]|None symbols: unified symbols of the markets to fetch the ticker for, all market tickers are returned if not assigned
        :param dict [params]: extra parameters specific to the exchange API endpoint
        :returns dict: a dictionary of `ticker structures <https://docs.ccxt.com/#/?id=ticker-structure>`
        r   )rD  publicGetTickers	safe_listparse_tickersr   rI  r   r   r   s        r   fetch_tickerszpoloniexfutures.fetch_tickers   sE     	((0~~h3!!$00r   r   c           	      h   | j                          | j                  |d      }| j                  |d      }|"|dk7  r|dk7  rt        | j                  dz         | j                  |      }d|d   i}d}|dk(  r"| j                  | j                  ||            }n!| j                  | j                  ||            }| j                  |di       }| j                  |d	d
      }	d}
|dk(  r| j                  ||d   |	dddd      }
n| j                  ||d   |	dddd      }
| j                  |d      |
d<   |
S )a  
        fetches information on open orders with bid(buy) and ask(sell) prices, volumes and other data

        https://api-docs.poloniex.com/futures/api/orderbook#get-full-order-book---level-2
        https://api-docs.poloniex.com/futures/api/orderbook#get-full-order-book--level-3

        :param str symbol: unified symbol of the market to fetch the order book for
        :param int [limit]: the maximum amount of order book entries to return
        :param dict [params]: extra parameters specific to the exchange API endpoint
        :returns dict: A dictionary of `order book structures <https://docs.ccxt.com/#/?id=order-book-structure>` indexed by market symbols
        levelN      z- fetchOrderBook() can only return level 2 & 3r   r%   r   r  r  bidsasksrQ   r   sequencenonce)rD  r  omitr   r%   r   publicGetLevel3SnapshotrF  publicGetLevel2Snapshotr   r;  parse_order_bookr  )r   r   r   r   rQ  r   rG  r   r   rn   	orderbooks              r   fetch_order_bookz poloniexfutures.fetch_order_book/  sW    	  167+!
TWW'VVWWV$fTl
 A:33DKK4PQH33DKK4PQH^ x4--dD(C		A:--dF84DiQWY_abdefI--dF84DiQWY_abdefI!..tZ@	'r   c                 t    | j                          | j                  |      }| j                  |d   dddi      S )a  
        fetches level 3 information on open orders with bid(buy) and ask(sell) prices, volumes and other data

        https://api-docs.poloniex.com/futures/api/orderbook#get-full-order-book--level-3

        :param str symbol: unified market symbol
        :param int [limit]: max number of orders to return, default is None
        :param dict [params]: extra parameters specific to the exchange API endpoint
        :returns dict: an `order book structure <https://docs.ccxt.com/#/?id=order-book-structure>`
        r%   NrQ  rS  )rD  r   r]  )r   r   r   r   r   s        r   fetch_l3_order_bookz#poloniexfutures.fetch_l3_order_book  s;     	V$$$VD\4'1FFr   tradec                 *   | j                  |d      }| j                  ||d      }| j                  |d      }| j                  |d      }| j                  |d      }| j                  |d      }|| j                  |dz        }n| j                  |d      }d	|v r||d
z  }| j                  |d      }| j                  |d      }	| j                  |d      }
d }| j                  |d      }|J| j                  |d      }| j	                  |      }||
dk(  r|d   n|d   }||| j                  |d      d}| j                  |d      }|dk(  rd }| j                  |d      }| j                  ||||| j                  |      |d   |||
||	||d|      S )Nr   -tradeIdorderId	liquidityr  i@B 	createdAt	dealValue  r  r4  sidefeefeeCurrencysellr   r   feeRate)r  currencyrate	orderTypematchvalue)r  r%   orderrn   r#  r   r   takerOrMakerri  r  r   r  rj  )r  safe_marketr  parse_to_intr  
safe_trader?  )r   r`  r   r@  r%   rd  rt  rn   priceStringamountStringri  rj  feeCostStringfeeCurrencyIdrk  r   
costStrings                    r   parse_tradezpoloniexfutures.parse_trade  s   L ##E84!!(FC8eY/""5)4''{;%%eT2	 )))g*=>I))%=Iu$9+@%,	&&ug6''v6v.((6$ ,,UMBM11-@K"26&.fWovf~%'((	:C
 {37?D%%eW5
"Y/X&( " 
  	r   sincec                     | j                          | j                  |      }d|d   i}| j                  | j                  ||            }| j	                  |dg       }| j                  ||||      S )a0  
        get the list of most recent trades for a particular symbol

        https://api-docs.poloniex.com/futures/api/historical#transaction-history

        :param str symbol: unified symbol of the market to fetch trades for
        :param int [since]: timestamp in ms of the earliest trade to fetch
        :param int [limit]: the maximum amount of trades to fetch
        :param dict [params]: extra parameters specific to the exchange API endpoint
        :returns Trade[]: a list of `trade structures <https://docs.ccxt.com/#/?id=public-trades>`
        r   r%   r   )rD  r   publicGetTradeHistoryrF  rL  parse_trades)	r   r   r~  r   r   r   rG  r   tradess	            r   fetch_tradeszpoloniexfutures.fetch_trades  sv     	V$fTl
 --dkk'6.JK" &"5  >>r   c                 H    | j                  |      }| j                  |d      S )ae  
        fetches the current integer timestamp in milliseconds from the poloniexfutures server

        https://api-docs.poloniex.com/futures/api/time#server-time

        :param dict [params]: extra parameters specific to the exchange API endpoint
        :returns int: the current integer timestamp in milliseconds from the poloniexfutures server
        r   )publicGetTimestampr  )r   r   r   s      r   
fetch_timezpoloniexfutures.fetch_time  s)     **62   622r   rW   c                 "   | j                          | j                  |      }|d   }| j                  | j                  |      }d|i}	|||	d<   n||	d<   | j	                  |      dz  }
| j                         }|?||	d<   || j                  | j                  dd      }| j                  |||
z        }||	d<   n||||
z  z
  }||	d<   | j                  | j                  |	|            }| j                  |d	g       }| j                  |||||      S )
a  
        fetches historical candlestick data containing the open, high, low, and close price, and the volume of a market

        https://api-docs.poloniex.com/futures/api/kline#get-k-line-data-of-contract

        :param str symbol: unified symbol of the market to fetch OHLCV data for
        :param str timeframe: the length of time each candle represents
        :param int [since]: timestamp in ms of the earliest candle to fetch
        :param int [limit]: the maximum amount of candles to fetch
        :param dict [params]: extra parameters specific to the exchange API endpoint
        :returns int[][]: A list of candles ordered, open, high, low, close, volume
        r%   r   granularityrh  fromfetchOHLCVLimitr   tor   )rD  r   r  rP   parse_timeframemillisecondsr   sumpublicGetKlineQueryrF  rL  parse_ohlcvs)r   r   	timeframer~  r   r   r   r@  parsedTimeframerG  durationendAtr   r   s                 r   fetch_ohlcvzpoloniexfutures.fetch_ohlcv  s9    	V$$<++DOOYGh
 &%4GM"%.GM"''	2T9!!##GFO}))$,,8I3OHHUEH$45E!GDMEH,,E#GFO++DKK,HI ~~h3  vy%GGr   c                    |d d d}| j                  |d      }| j                  |d      }| j                  |      }| j                         }| j                  |d      |d<   | j                  |d      |d<   |||<   | j	                  |      S )N)r  rn   r#  r   rn  availableBalancefreeaccountEquitytotal)r   r  r  accountsafe_balance)r   r   resultr   
currencyIdcoder  s          r   parse_balancezpoloniexfutures.parse_balanceO  s    

 x0%%dJ7
&&z2,,.**41CD++D/Bt  ((r   c                     | j                          | j                  |d      }i }|| j                  |      }d|d   i}| j                  | j	                  ||            }| j                  |      S )ar  
        query for balance and get the amount of funds available for trading or funds locked in orders

        https://api-docs.poloniex.com/futures/api/account#get-account-overview

        :param dict [params]: extra parameters specific to the exchange API endpoint
        :returns dict: a `balance structure <https://docs.ccxt.com/#/?id=balance-structure>`
        rn  r%   )rD  r  rn  privateGetAccountOverviewrF  r  )r   r   r  rG  rn  r   s         r   fetch_balancezpoloniexfutures.fetch_balance^  s{     	%%fj9
!}}Z0HHTNG 11$++gv2NO  !!(++r   r   ri  r   r  c                    | j                          | j                  |      }| j                  |dd| j                               }| j	                  |ddg      }|dk  rt        | j                  dz         t        | j                  ||            }	|||d   ||	dd}
| j                  |dd      }|r9|d	k(  rd
nd|
d<   | j                  |dd      }||
d<   | j                  ||      |
d<   | j                  |d      }|dk(  r6|t        | j                  dz         | j                  ||      |
d<   |||
d<   | j                  |dd      }| j                  |d      }|r|t!        | j                  dz         | j                  |d      }|r,| j                  |d      }|t        | j                  dz         | j	                  |g d      }| j#                  | j%                  |
|            }| j                  |di       }| j'                  i d| j                  |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 )-aR  
        Create an order on the exchange

        https://api-docs.poloniex.com/futures/api/orders#place-an-order

        :param str symbol: Unified CCXT market symbol
        :param str type: 'limit' or 'market'
        :param str side: 'buy' or 'sell'
        :param float amount: the amount of currency to trade
        :param float [price]: the price at which the order is to be fulfilled, in units of the quote currency, ignored in market orders
        :param dict [params]:  extra parameters specific to the exchange API endpoint
        :param float [params.leverage]: Leverage size of the order
        :param float [params.triggerPrice]: The price at which a trigger order is triggered at
        :param bool [params.reduceOnly]: A mark to reduce the position size only. Set to False by default. Need to set the position size when reduceOnly is True.
        :param str [params.timeInForce]: GTC, GTT, IOC, or FOK, default is GTC, limit orders only
        :param str [params.postOnly]: Post only flag, invalid when timeInForce is IOC or FOK
        :param str [params.clientOid]: client order id, defaults to uuid if not passed
        :param str [params.remark]: remark for the order, length cannot exceed 100 utf8 characters
        :param str [params.stop]: 'up' or 'down', defaults to 'up' if side is sell and 'down' if side is buy, requires stopPrice
        :param str [params.stopPriceType]:  TP, IP or MP, defaults to TP
        :param bool [params.closeOrder]: set to True to close position
        :param bool [params.forceHold]: A mark to forcely hold the funds for an order, even though it's an order to reduce the position size. This helps the order stay on the order book and not get canceled when the position size changes. Set to False by default.
        :returns dict: an `order structure <https://docs.ccxt.com/#/?id=order-structure>`
        	clientOidclientOrderIdrQ   z1 createOrder() minimum contract order amount is 1r%   )r  ri  r   r   r4  r   r   	stopPricebuyupdownstopstopPriceTypeTPr   r   Nz9 createOrder() requires a price argument for limit ordersr  postOnlyFhiddenzW createOrder() does not support the postOnly parameter together with a hidden parameterr   visibleSizezB createOrder() requires a visibleSize parameter for iceberg orders)r   r  r   r   rd  rn   r#  lastTradeTimestampr   r   ri  r   r  r3  filled	remainingro   rj  r  r   r  r   r  )rD  r   r<  uuidrX  r   r%   intamount_to_precisionsafe_value_2r  price_to_precisionsafe_string_upperr   	safe_boolr   r   privatePostOrdersrF  
safe_order)r   r   r   ri  r   r  r   r   r  preciseAmountrG  r   r  r   r  r  r   r  r   r   s                       r   create_orderzpoloniexfutures.create_order  s(   2 	V$**6;QUQZQZQ\]6K#ABA:tww)\\]]D44VVDE&Tl!
 ((M'+u}d6GFO ,,V_dKM'4GO$#'#:#:6<#PGK ,,V]C7?}'2m(mnn#'#:#:65#I &)4&>>&*e<2+TWW  (A  A  B  B//&)4//&-@K"'2v(vww6#OP))$++gv*FG x4  
$""43 
T 
  
 	 

 !$ 
 d 
 D 
 D 
 T 
 d 
 D 
 t 
 d 
  
 d 
  4! 
" d# 
$   + 
, - 	r   r%   c                 &   | j                          d|i}| j                  | j                  ||            }| j                  |d      }| j                  |d      }t	        |      }|dk(  rt        | j                  dz         | j                  |      S )a  
        cancels an open order

        https://api-docs.poloniex.com/futures/api/orders#cancel-an-order

        :param str id: order id
        :param str symbol: unified symbol of the market the order was made in
        :param dict [params]: extra parameters specific to the exchange API endpoint
        :returns dict: An `order structure <https://docs.ccxt.com/#/?id=order-structure>`
        order-idr   cancelledOrderIdsr   z& cancelOrder() order already cancelled)rD  privateDeleteOrdersOrderIdrF  r   r:  r   r%   parse_order)	r   r%   r   r   rG  r   r   r  cancelledOrderIdsLengths	            r   cancel_orderzpoloniexfutures.cancel_order  s     	
 224;;w3OP" x0 OOD2EF"%&7"8"a'tww)QQRR%%r   c                     | j                          | j                  |      }| j                  |d      }| j                  ||      S )az  
        fetch all open positions

        https://api-docs.poloniex.com/futures/api/positions#get-position-list

        :param str[]|None symbols: list of unified market symbols
        :param dict [params]: extra parameters specific to the exchange API endpoint
        :returns dict[]: a list of `position structure <https://docs.ccxt.com/#/?id=position-structure>`
        r   )rD  privateGetPositionsrL  parse_positionsrN  s        r   fetch_positionszpoloniexfutures.fetch_positions  sF     	++F3^ ~~h/##D'22r   r{   c                    | j                  |d      }| j                  ||      }| j                  |d      }| j                  |d      }t        j                  |d      rd}nt        j
                  |d      rd}t        j                  | j                  |d            }| j                  |d      }t        j                  ||      }	| j                  |d	      }
| j                  |d
      }|rdnd}i d|dd d| j                  |d      d|d| j                  |      d| j                  |      d| j                  |	      d| j                  |d      d| j                  |d      d| j                  |d      d| j                  |      d| j                  |d      d| j                  |
      d| j                  t        j                  |            d| j                  |d      dd d | j                  |d       | j                  |d!      | j                  |d"      || j                  t        j                  |
|            d d d#S )$Nr   currentTimestamp
currentQty0longshortposCostposInitunrealisedPnl	crossModecrossisolatedr  r%   rn   r#  initialMargininitialMarginPercentagemaintenanceMarginposMaintmaintenanceMarginPercentagemaintMarginReq
entryPriceavgEntryPricenotionalr   realLeverageunrealizedPnl	contractsr  marginRatioliquidationPrice	markPricemaintMargin)r  
collateralr   ri  r   r   r   )r  ru  r  r    	string_gt	string_ltr  
string_divr   r?  r   r  )r   r{   r   r   rn   r4  ri  r  r  r  r  r  r   s                r   parse_positionzpoloniexfutures.parse_positionH  s   ^ !!(H5!!&&1%%h0BC	,7T3'DtS)D%%d&6&6x&KL((9=")"4"4]H"M((?COOHk:	 )Wz

H
$
 d&&vx8
 	

 Y/
 T..}=
 &t'8'89P'Q
  !1!1(J!G
 *4+;+;HFV+W
 $**8_E
 ))(3
 ((>B
 T..}=
 **7+=+=d+CD
 DOOFNC
  4!
"  0 0;M N#
$ ))(K@**8]C$++G,>,>}m,\]!#1
 	
r   c                    |t        | j                  dz         | j                          | j                  |      }d|d   i}|||d<   |||d<   | j	                  | j                  ||            }| j                  |d      }| j                  |dg       }	t        |	      }
g }t        d|
      D ]  }|	|   }| j                  |d	      }|j                  ||| j                  | j                  |d
            || j                  |      | j                  |d      | j                  |d      | j                  |d      | j                  |d      | j                  |d      | j                  |d      d        |S )aK  
        fetch the history of funding payments paid and received on self account

        https://api-docs.poloniex.com/futures/api/funding-fees#get-funding-history

        :param str symbol: unified market symbol
        :param int [since]: the earliest time in ms to fetch funding history for
        :param int [limit]: the maximum number of funding history structures to retrieve
        :param dict [params]: extra parameters specific to the exchange API endpoint
        :returns dict: a `funding history structure <https://docs.ccxt.com/#/?id=funding-history-structure>`
        z1 fetchFundingHistory() requires a symbol argumentr   r%   startAtmaxCountr   dataListr   	timePointsettleCurrencyr   fundingRater  positionQtypositionCost)r  r   r  rn   r#  r%   r   r  r  r  r  )r   r%   rD  r   privateGetFundingHistoryrF  r   r:  ranger  appendr  r  r?  r  )r   r   r~  r   r   r   rG  r   r   r  dataListLengthrh   ilistItemrn   s                  r   fetch_funding_historyz%poloniexfutures.fetch_funding_history  s    >#DGG.a$abbV$fTl
 !&GI"'GJ00Wf1MN. x0??4R8Xq.) 	A{H))(K@IKK  //0@0@K[0\]& LL3&&x6**8Y?#//-H!--hD#//-H $ 0 0> J 	  r   c                    | j                          i }|| j                  |      |d<   | j                  |dd      }| j                  |ddg      }d}|r"| j	                  | j                  ||            }n!| j                  | j                  ||            }| j                  |d      }g }| j                  |d      }t        |      }	t        d|	      D ]n  }
| j                  ||
      }|j                  | j                  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             p |S )a  
        cancel all open orders
        :param str symbol: unified market symbol, only orders in the market of self symbol are cancelled when symbol is not None
        :param dict [params]: extra parameters specific to the exchange API endpoint
        :param dict [params.trigger]: When True, all the trigger orders will be cancelled
        :returns dict[]: a list of `order structures <https://docs.ccxt.com/#/?id=order-structure>`
        Nr   r  r   r   r  r   r%   r  rn   r#  r  r   ri  r  r   r  r3  r  r  ro   rj  r  r  )rD  	market_idr  rX  privateDeleteStopOrdersrF  privateDeleteOrdersr   r:  r  r  r  r  )r   r   r   rG  r   r   r   r  r  r  r  cancelledOrderIds               r   cancel_all_ordersz!poloniexfutures.cancel_all_orders  s    	 $v 6GH##FFI>6FI#6733DKK4PQH//GV0LMH x0 OOD2EF"%&7"8q12 	A#//0A1EMM$// +&++ T+ D	+
 %d+ $+ + + + $+ + 4+ $+ T+ $+  t!+" $#+$  $  $ ++  	2 r   c                    | j                          | j                  |dd      }| j                  |d      }| j                  |g d      }|dk(  rd}i }|s|dk(  rdnd|d	<   n|dk7  rt	        | j
                  d
z         d}	|| j                  |      }	|	d   |d<   |||d<   |||d<   d}
|r"| j                  | j                  ||            }
n!| j                  | j                  ||            }
| j                  |
di       }| j                  |dg       }t        |      }g }t        d|      D ]3  }||   }| j                  |d	      }||k(  s |j                  ||          5 | j                  ||	||      S )a  
        fetches a list of orders placed on the exchange

        https://api-docs.poloniex.com/futures/api/orders#get-order-listdeprecated
        https://api-docs.poloniex.com/futures/api/orders#get-untriggered-stop-order-list

        :param str status: 'active' or 'closed', only 'active' is valid for stop orders
        :param str symbol: unified symbol for the market to retrieve orders from
        :param int [since]: timestamp in ms of the earliest order to retrieve
        :param int [limit]: The maximum number of orders to retrieve
        :param dict [params]: exchange specific parameters
        :param bool [params.stop]: set to True to retrieve untriggered stop orders
        :param int [params.until]: End time in ms
        :param str [params.side]: buy or sell
        :param str [params.type]: limit or market
        :returns: An `array of order structures <https://docs.ccxt.com/#/?id=order-structure>`
        r  r   until)r   r  r  closeddoner/  r   ro   z= fetchOrdersByStatus() can only fetch untriggered stop ordersNr%   r   r  r  r   itemsr   )rD  r  r  rX  r   r%   r   privateGetStopOrdersrF  privateGetOrdersr   r:  r  r  r  parse_orders)r   ro   r   r~  r   r   r   r  rG  r   r   responseDataru   ordersLengthr  r  rs  orderStatuss                     r   fetch_orders_by_statusz&poloniexfutures.fetch_orders_by_status$  s   $ 	##FFI>!!&'26#?@XF-3v-=FGHvTWW'ffgg[[(F &tGH!&GI$GG00Wf1MNH,,T[[&-IJH` x<w;6{q,' 	)A1IE**5(;K$fQi(		)
   >>r   c                 ,    | j                  d||||      S )a  
        fetch all unfilled currently open orders

        https://api-docs.poloniex.com/futures/api/orders#get-order-listdeprecated
        https://api-docs.poloniex.com/futures/api/orders#get-untriggered-stop-order-list

        :param str symbol: unified market symbol
        :param int [since]: the earliest time in ms to fetch open orders for
        :param int [limit]: the maximum number of  open orders structures to retrieve
        :param dict [params]: extra parameters specific to the exchange API endpoint
        :param int [params.until]: end time in ms
        :param str [params.side]: buy or sell
        :param str [params.type]: limit, or market
        :returns Order[]: a list of `order structures <https://docs.ccxt.com/#/?id=order-structure>`
        r/  r  r   r   r~  r   r   s        r   fetch_open_ordersz!poloniexfutures.fetch_open_orders  s      **665%PPr   c                 ,    | j                  d||||      S )a4  
        fetches information on multiple closed orders made by the user

        https://api-docs.poloniex.com/futures/api/orders#get-order-listdeprecated
        https://api-docs.poloniex.com/futures/api/orders#get-untriggered-stop-order-list

        :param str symbol: unified market symbol of the market orders were made in
        :param int [since]: the earliest time in ms to fetch orders for
        :param int [limit]: the maximum number of order structures to retrieve
        :param dict [params]: extra parameters specific to the exchange API endpoint
        :param int [params.until]: end time in ms
        :param str [params.side]: buy or sell
        :param str [params.type]: limit, or market
        :returns Order[]: a list of `order structures <https://docs.ccxt.com/#/?id=order-structure>`
        r  r  r  s        r   fetch_closed_ordersz#poloniexfutures.fetch_closed_orders  s      **8VUE6RRr   c                    | j                          i }d}|h| j                  |dd      }|t        | j                  dz         ||d<   | j	                  |ddg      }| j                  | j                  ||            }n&||d<   | j                  | j                  ||            }|| j                  |      nd}| j                  |d      }| j                  ||      S )a  
        fetches information on an order made by the user

        https://api-docs.poloniex.com/futures/api/orders#get-details-of-a-single-order
        https://api-docs.poloniex.com/futures/api/orders#get-single-order-by-clientoid

        :param str id: the order id
        :param str symbol: unified symbol of the market the order was made in
        :param dict [params]: extra parameters specific to the exchange API endpoint
        :returns dict: An `order structure <https://docs.ccxt.com/#/?id=order-structure>`
        Nr  r  z7 fetchOrder() requires parameter id or params.clientOidr  r   )rD  r<  r   r%   rX   privateGetClientOrderIdClientOidrF  privateGetOrdersOrderIdr   	safe_dictr  )	r   r%   r   r   rG  r   r  r   r
  s	            r   fetch_orderzpoloniexfutures.fetch_order  s     	: ..v{OTM$"477-f#fgg#0GK YYv_'EFF<<T[[RX=YZH"$GJ33DKK4PQH\ *0);V$$~~h7f55r   rs  c           	         | j                  |d      }| j                  ||      }| j                  |d      }| j                  |d      }| j                  |d      }| j                  |dd      }d }t	        j
                  |d      rl| j                  |d      }	|d	   r+t	        j                  |t	        j                  |	|            }n*t	        j                  t	        j                  |	|      |      }| j                  |d
d      }
| j                  |dd      }|
rdnd}| j                  |d      }d|v r$| j                  |d      }| j                  |d      }| j                  i d|d|d| j                  |d      d| j                  |d      d| j                  |d      d| j                  |d      d| j                  |d      d| j                  |d      d| j                  |d      d| j                  |d      d| j                  |d      d| j                  |d      d |d!d d"|d#| j                  |      d$| j                  |      | j                  |d$      d%|rd&n|d |d d'|      S )(Nr   rf  rk  dealSize	dealFundsfilledValuer  r  r   isActiveFcancelExistr/  r  r%   r  r   r  r  r  r   r   r  ri  r   r4  r  r   r  r  rg  r  r  rn   r#  rj  )rn  r  canceled)ro   r  r3  r  )r  ru  r  r<  r    r  r  r=  r  r   r  r?  r  )r   rs  r   r@  rn   r{  r  rawCostr3  r  r  r  ro   r%   r  s                  r   r  zpoloniexfutures.parse_order  s   H ##E84!!(F3%%e[9	 ((>!!%4$$UKGVS)++FNCLh!,,Wg6H6HW]6^_!,,W-?-?f-UW^_ >>%U;nnUM5A#eT*%' $7J K!!"3Q7B  
E 
" 
 T--e[A 
 d&&vx8	 

 D$$UF3 
 4++E=A 
 z: 
 D$$UF3 
 d&&uf5 
 T%%eW5 
 D,,UK@ 
 D$$UK8 
 f 
  
  
  Y/! 
"  33MB((6# 
* %0jV"&1 
2 3 	r   c                     | j                          | j                  |      }d|d   i}| j                  | j                  ||            }| j	                  |di       }| j                  ||      S )aq  
        fetch the current funding rate

        https://api-docs.poloniex.com/futures/api/futures-index#get-premium-index

        :param str symbol: unified market symbol
        :param dict [params]: extra parameters specific to the exchange API endpoint
        :returns dict: a `funding rate structure <https://docs.ccxt.com/#/?id=funding-rate-structure>`
        r   r%   r   )rD  r   !publicGetFundingRateSymbolCurrentrF  r  parse_funding_rate)r   r   r   r   rG  r   r   s          r   fetch_funding_ratez"poloniexfutures.fetch_funding_raten  sr     	V$fTl
 99$++gv:VW ~~h3&&tV44r   c                 &    | j                  ||      S )az  
        fetch the current funding rate interval

        https://api-docs.poloniex.com/futures/api/futures-index#get-premium-index

        :param str symbol: unified market symbol
        :param dict [params]: extra parameters specific to the exchange API endpoint
        :returns dict: a `funding rate structure <https://docs.ccxt.com/#/?id=funding-rate-structure>`
        )r$  )r   r   r   s      r   fetch_funding_intervalz&poloniexfutures.fetch_funding_interval  s     &&vv66r   c                 |   | j                  |d      }| j                  |d      }i d|d| j                  ||d d      dd dd dd dd d	d d
d d| j                  |d      d|d| j	                  |      d| j                  |d      dd dd dd dd dd d| j                  | j                  |d            iS )Nr  r   r  r   r  
indexPriceinterestRateestimatedSettlePricern   r#  r  rr  fundingTimestampfundingDatetimenextFundingRatepredictedValuenextFundingTimestampnextFundingDatetimepreviousFundingRatepreviousFundingTimestamppreviousFundingDatetimeintervalr  )r  r  r9  r  r?  parse_funding_interval)r   r   r   r+  r@  s        r   r#  z"poloniexfutures.parse_funding_rate  sV     ,,T;?##D(3
D
d&&xzJ
 
 $	

 D
 #D
 
 
 4++D':
  0
 t||,<=
 t//6FG
 #D
 "4
 "4
  '!
" &t#
$ 33D4D4DT=4YZ%
 	
r   c                 8    dddddd}| j                  |||      S )Nr[   r]   8h16h24h)360000014400000288000005760000086400000)r  )r   r4  	intervalss      r   r5  z&poloniexfutures.parse_funding_interval  s/    
	 	8X>>r   c                 $   | j                          i }d}|| j                  |      }|d   |d<   |||d<   | j                  | j                  ||            }| j	                  |di       }| j                  |dg       }	| j                  |	|||      S )a*  
        fetch all trades made by the user

        https://api-docs.poloniex.com/futures/api/fills#get-fillsdeprecated

        :param str symbol: unified market symbol
        :param int [since]: the earliest time in ms to fetch trades for
        :param int [limit]: the maximum number of trades structures to retrieve
        :param dict [params]: extra parameters specific to the exchange API endpoint
        :param str [params.orderIdFills]: filles for a specific order(other parameters can be ignored if specified)
        :param str [params.side]: buy or sell
        :param str [params.type]:  limit, market, limit_stop or market_stop
        :param int [params.endAt]: end time(milisecond)
        :returns Trade[]: a list of `trade structures <https://docs.ccxt.com/#/?id=trade-structure>`
        Nr%   r   r  r   r  )rD  r   privateGetFillsrF  r   rL  r  )
r   r   r~  r   r   rG  r   r   r   r  s
             r   fetch_my_tradeszpoloniexfutures.fetch_my_trades  s      	
[[(F &tGH!&GI''GV(DED x4gr2  >>r   r   c                 <   |t        | j                  dz         |dk7  r'|dk7  r"|dk7  r|dk7  rt        | j                  dz         | j                          |dk(  rd}|dk(  rd}| j                  |      }|d   | j	                  |      d}| j                  |      S )	a  
        set margin mode to 'cross' or 'isolated'

        https://api-docs.poloniex.com/futures/api/margin-mode#change-margin-mode

        :param str marginMode: "0"(isolated) or "1"(cross)
        :param str symbol: unified market symbol
        :param dict [params]: extra parameters specific to the exchange API endpoint
        :returns dict: response from the exchange
        z+ setMarginMode() requires a symbol argumentr  r  r  r  z9 setMarginMode() marginMode must be 0/isolated or 1/crossr%   )r   
marginType)r   r%   rD  r   rv  privatePostMarginTypeChange)r   r   r   r   r   rG  s         r   set_margin_modezpoloniexfutures.set_margin_mode   s     >#DGG.[$[\\#J#$5J*<T[eip[p#DGG.i$ijj#J JV$Tl++J7
 //88r   rb   r   c                    | j                   d   |   }| j                  | j                  di       }| j                  ||i       }	| j                  |	|i       }
| j                  |
|| j                        }| j                  |d|      }d|z   dz   | j                  ||      z   }||z  }| j                  || j                  |            }|}|dk(  r|r|d| j                  |      z   z  }n| j                          d| j                  ||      z   }| j                  |      }|d	k7  r|d
k7  r|}n|r|dk7  r|d|z   z  }|d|z   z  }t        | j                               }d}|| j                  |      }|}||z   |z   |z   }| j                  | j                  |      | j                  | j                        t         j"                  d      }||| j$                  | j&                  d}d|d<   ||||dS )Nre   r   r,   z/api/r   rb   ?z/api/v1/r   HEAD base64)zPF-API-SIGNzPF-API-TIMESTAMPz
PF-API-KEYzPF-API-PASSPHRASEzapplication/jsonzContent-Type)urlmethodbodyheaders)ra   r   r   r  r,   implode_paramsrX  extract_params	urlencodecheck_required_credentialsstrr  jsonhmacencoder   hashlibsha256r   r   )r   pathre   rM  r   rO  rN  rL  r   apiVersionsmethodVersionsdefaultVersionr,   tailqueryqueryLengthendpointbodyEncodednowendpartpayload	signatures                         r   signzpoloniexfutures.sign  s   iis#??4<<R@oohR8fbA)).$M""69nE 3&)<)<T6)JJt		&$"5"5d";<(?sT^^E222++-!D$7$7f$EEH../K6V#3;"#43,,Ck 11Hd'')*CGyy'FlX-7G		$++g"6DKK8PRYR`R`bjkI($'"kk%)]]	G '9GN#fdwOOr   r  reasonrL  rM  rO  rN  c
                 x   |s!| j                  | j                  d   ||       y | j                  |d      }
| j                  |dd      }| j                  dz   |z   }| j	                  | j                  d   ||       | j	                  | j                  d   |
|       | j                  | j                  d   ||       y )Nr   r  msgrJ   r   )throw_broadly_matched_exceptionr   r  r%   throw_exactly_matched_exception)r   r  rh  rL  rM  rO  rN  r   requestHeadersrequestBody	errorCodemessagefeedbacks                r   handle_errorszpoloniexfutures.handle_errorsC  s    001I4QUV $$Xv6	""8UB777S=7*,,T__W-EwPXY,,T__W-EyRZ[,,T__W-EtXVr   )N):__name__
__module____qualname__r   r   r   r   r   dictr  r   rB  rT  rH  r   r   rO  r   r   r]  r_  r   r}  r  r  listr  r   r  r  r   r   floatr	   r  r   r  r  r  r  r  r  r
   r  r  r  r  r   r$  r&  r#  r5  rB  rF  rg  r  rs  __classcell__)r   s   @r   r"   r"      s   O# Ob $& I($v, I(VB
4 B
F B
H?4 ? ?6 ?B 02 "P3 "Pf "PH 04B 1W 17 1 :>b Ps P3 PY Pd =A G# Gc GT Tv T Tl 6:UW #?3 #?s #?# #?\`af\g #?J !# 3s 3& 26DW[df /H# /Hc /HQT /Hkoptku /Hb) ) $& !,( !,F gksu a3 ai ay aRW a`c aF 37r %&s %&C %&N 26b ;3w ;3zY
t Y
V Y
v 37TX\eg CC Cs CRU CJ /32 : :x <@daenp b?S b? b?[^ b?H /3TXac Q Q3 Qc Qhlmrhs Q$ 154VZce S# SS SPS Sjnotju S$ 26b H6c H63 H6Tv vv v vp 68 5 5K 58 :< 
7S 
7 
7
v 
 
B? -1tRV_a =?c =? =?C =?~ >B" 9# 9s 96 &eBSW &PP# s  c TX `c r   r"   )'ccxt.base.exchanger   ccxt.abstract.poloniexfuturesr   rX  ccxt.base.typesr   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   ccxt.base.decimal_to_precisionr   ccxt.base.preciser    r"    r   r   <module>r     se    ( 5  W  W  W  W  W  0 - . ' ) * ) . 1 ) 4 %zh zr   