
    !:h                       d dl mZ d dlmZ d dlZd dlmZmZmZm	Z	m
Z
mZmZmZmZmZmZmZmZmZmZmZmZmZmZmZmZmZmZmZ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"m0Z0 d dl1m2Z2 d dl1m3Z3 d dl1m4Z4 d dl1m5Z5 d dl6m7Z7  G d dee      Z8y)    )Exchange)ImplicitAPIN)AnyBalances
CurrenciesCurrencyDepositAddressIntLedgerEntryMarginModificationMarketNumOrder	OrderBookOrderRequest	OrderSide	OrderTypePositionStrStringsTickerTickersFundingRateFundingRatesTradeTradingFeesTransactionTransferEntry)List)ExchangeError)AuthenticationError)PermissionDenied)ArgumentsRequired)
BadRequest)	BadSymbol)InsufficientFunds)InvalidOrder)OrderNotFound)NotSupported)RateLimitExceeded)ExchangeNotAvailable)OnMaintenance)InvalidNonce)ROUND)TRUNCATE)DECIMAL_PLACES)SIGNIFICANT_DIGITS)Precisec                       e Zd Zdef fdZd Zd Zd Zd Zd Z	i fdZ
i fdee   fd	Zi fdefd
Zi fdefdZi fdededededef
dZdbdededefdZdedefdZd Zdi fdededefdZdbdededefdZ di fde!de"fdZ#i fdedefd Z$dbd!edede%fd"Z&ddi fded#ededee%   fd$Z'd%dd&i fded#ededee(   fd'Z)dbdede(fd(Z*defd)Z+d* Z,d+ Z-dbd,edede.fd-Z/di fded.e0d/e1ded0e2f
d1Z3di fded.e0d/e1ded0e2f
d2Z4i fd3ee5   fd4Z6di fdefd5Z7di fd6edefd7Z8di fdefd8Z9di fd6edefd9Z:di fd6edefd:Z;dddi fded#ededee.   fd;Z<dddi fded#ededee.   fd<Z=dddi fd6eded#edefd=Z>dddi fded#edefd>Z?i fdede@fd?ZAi fdede@fd@ZBdefdAZCdbdBededeDfdCZEi fdeFfdDZGdddi fded#ededeeD   fdEZHdi fdededFedeDfdGZIdi fde!deeJ   fdHZKdbdIedefdJZLdK ZMdLdMi ddfdNZNdO ZOd.efdPZPdbdQededeQfdRZRdddi fded#ededeeQ   fdSZSdi fde!deTfdTZUdddi fded#edefdUZVdbdedeWfdVZXdbdefdWZYdi fde!fdXZZi fdefdYZ[d%ddi fded#edefdZZ\dbdefd[Z]ddi fded#edefd\Z^dbdefd]Z_i fdedede`fd^Zadbde`fd_Zbdi fd6edefd`Zcddi fd6eded.e0d/e1de2d0e2fdaZd xZeS )cbitfinexreturnc                    | j                  t        t        |          i ddddddg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
d.dd/di d0d
d1d
d2dd3dd4d
d5d
d6dd7d
d8d9d:dd;dd<d
d=d
d>d
d?dd@d
dAd
i dBddCd
dDd
dEd
dFddGddHddIddJddKddLddMddNddOd
dPddQd
dRd
i dSddTd
dUddVddWd
dXd
dYddZd d[d9d\d
d]d
d^d
d_d
d`ddad
dbd
dcd
dddddedfdgdhdidjdkdldmdndodpdqdrdsdtdudvdwdxdydxdzd{d|d}gd~ddi ddddddddddddddddddddddddddddddddddi ddddddddddddddddddddddddddddddddddi dddddddddddddddddddddddddddddddddddddddddddddddddddi ddddddddddddddddddddddddddddddddddi ddddddddddddddddddddddddddddddddddi ddddddddddddddddddddddddddddddddddi ddddddddddddddddddddddddddddd ddddddddddiddddd| j	                  d      | j	                  d	      | j	                  d
      | j	                  d	      g| j	                  d      | j	                  d	      g| j	                  d      | j	                  d	      g| j	                  d      | j	                  d	      g| j	                  d      | j	                  d	      g| j	                  d      | j	                  d	      g| j	                  d      | j	                  d      g| j	                  d      | j	                  d      g| j	                  d      | j	                  d      g| j	                  d      | j	                  d      g| j	                  d      | j	                  d      gg| j	                  d
      | j	                  d      g| j	                  d      | j	                  d      g| j	                  d      | j	                  d      g| j	                  d      | j	                  d      g| j	                  d      | j	                  d      g| j	                  d      | j	                  d
      g| j	                  d      | j	                  d
      g| j	                  d      | j	                  d
      g| j	                  d      | j	                  d
      g| j	                  d      | j	                  d
      g| j	                  d      | j	                  d
      ggdddi id d!t
        d"d#d$d$d%d%d$d%d%d%d&d'd(d)d*d+d,d-d.d/d0d0d1ddddd2d3d
id4d5d6d7d8d9d:d;d<d=d>d?d@dAdBdCdDidEdFd
ddd d
ddd dddd
dGd
ddd
dd
d
dHdIdJid
dKd dLd
dMd
d
d
d
dNd
d d
d
d
dOd d
d d d dLd
d
d
dPd%dQidR	dSdTidSdTid dUd d dUdVdWt        t        t        t        t        t        t        dXt        t        t        t        dYdZd[i d\d]d^d_d`d]dadbdcdddedfdgdhdidjdkdldmdndodpdqdrdsdtdud_dvdwdxdydzd{i d|d}d~ddd~dddddddddddddddddddddddddddddddd      S (  Nidr4   nameBitfinex	countriesVGversionv2	certifiedFproThasCORSspotmarginswapfutureoption	addMarginborrowCrossMarginborrowIsolatedMargincancelAllOrderscancelOrdercancelOrderscreateDepositAddresscreateLimitOrdercreateMarketOrdercreateOrdercreatePostOnlyOrdercreateReduceOnlyOrdercreateStopLimitOrdercreateStopMarketOrdercreateStopOrdercreateTrailingAmountOrdercreateTrailingPercentOrdercreateTriggerOrder	editOrderfetchBalancefetchBorrowInterestfetchBorrowRatefetchBorrowRateHistoriesfetchBorrowRateHistoryfetchBorrowRatesfetchBorrowRatesPerSymbolfetchClosedOrderfetchClosedOrdersfetchCrossBorrowRatefetchCrossBorrowRatesfetchCurrenciesfetchDepositAddressfetchDepositAddressesfetchDepositAddressesByNetworkfetchDepositsWithdrawalsfetchFundingHistoryfetchFundingRateemulatedfetchFundingRateHistoryfetchFundingRatesfetchIndexOHLCVfetchIsolatedBorrowRatefetchIsolatedBorrowRatesfetchLedgerfetchLeveragefetchLeverageTiersfetchLiquidationsfetchMarginModefetchMarketLeverageTiersfetchMarkOHLCVfetchMyTrades
fetchOHLCVfetchOpenInterestfetchOpenInterestHistoryfetchOpenInterestsfetchOpenOrderfetchOpenOrders
fetchOrderfetchOrderBookfetchOrderBooksfetchOrderTradesfetchPositionfetchPositionModefetchPositionsfetchPremiumIndexOHLCVfetchStatusfetchTickers	fetchTimefetchTradingFeefetchTradingFeesfetchTransactionFeesfetchTransactionsreduceMarginrepayCrossMarginrepayIsolatedMarginsetLeverage	setMarginsetMarginModesetPositionModesignIn)transferwithdraw
timeframes1m5m15m30m1h3h4h6h12h1D7D14D1M)r   r   r   r   r   r   r   r   r   1d1w2wr   	rateLimit   urlszOhttps://github.com/user-attachments/assets/4a8e947f-ab46-481a-a8ae-8b20e9b03178zhttps://api.bitfinex.comzhttps://api-pub.bitfinex.com)v1publicprivatezhttps://www.bitfinex.comz"https://docs.bitfinex.com/v2/docs/z0https://github.com/bitfinexcom/bitfinex-api-nodezhttps://www.bitfinex.com/fees)logoapiwwwdocfeesr   zconf/{config}g@zconf/pub:{action}:{object}z#conf/pub:{action}:{object}:{detail}zconf/pub:map:{object}zconf/pub:map:{object}:{detail}zconf/pub:map:currency:{detail}zconf/pub:map:currency:symzconf/pub:map:currency:labelzconf/pub:map:currency:unitzconf/pub:map:currency:undlzconf/pub:map:currency:poolzconf/pub:map:currency:explorerzconf/pub:map:currency:tx:feezconf/pub:map:tx:methodzconf/pub:list:{object}zconf/pub:list:{object}:{detail}zconf/pub:list:currencyzconf/pub:list:pair:exchangezconf/pub:list:pair:marginzconf/pub:list:pair:futureszconf/pub:list:competitionszconf/pub:info:{object}zconf/pub:info:{object}:{detail}zconf/pub:info:pairzconf/pub:info:pair:futureszconf/pub:info:tx:statuszconf/pub:feeszplatform/status   tickerszticker/{symbol}ztickers/histztrades/{symbol}/histzbook/{symbol}/{precision}   zbook/{symbol}/P0zbook/{symbol}/P1zbook/{symbol}/P2zbook/{symbol}/P3zbook/{symbol}/R0z-stats1/{key}:{size}:{symbol}:{side}/{section}z(stats1/{key}:{size}:{symbol}:{side}/lastz(stats1/{key}:{size}:{symbol}:{side}/histz&stats1/{key}:{size}:{symbol}/{section}z!stats1/{key}:{size}:{symbol}/lastz!stats1/{key}:{size}:{symbol}/histz&stats1/{key}:{size}:{symbol}:long/lastz&stats1/{key}:{size}:{symbol}:long/histz'stats1/{key}:{size}:{symbol}:short/lastz'stats1/{key}:{size}:{symbol}:short/histz5candles/trade:{timeframe}:{symbol}:{period}/{section}z,candles/trade:{timeframe}:{symbol}/{section}z'candles/trade:{timeframe}:{symbol}/lastP   
   )z'candles/trade:{timeframe}:{symbol}/histzstatus/{type}zstatus/derivzstatus/deriv/{symbol}/histzliquidations/histz-rankings/{key}:{timeframe}:{symbol}/{section}z(rankings/{key}:{timeframe}:{symbol}/histz
pulse/histzpulse/profile/{nickname}zfunding/stats/{symbol}/histz	ext/vasps)zcalc/trade/avgzcalc/fx)getpostr   zauth/r/walletszauth/r/wallets/histzauth/r/orderszauth/r/orders/{symbol}zauth/w/order/submitzauth/w/order/updatezauth/w/order/cancelzauth/w/order/multizauth/w/order/cancel/multizauth/r/orders/{symbol}/histzauth/r/orders/histz!auth/r/order/{symbol}:{id}/tradeszauth/r/trades/{symbol}/histzauth/r/trades/histzauth/r/ledgers/{currency}/histzauth/r/ledgers/histzauth/r/info/margin/{key}zauth/r/info/margin/basezauth/r/info/margin/sym_allzauth/r/positionszauth/w/position/claimzauth/w/position/increase:zauth/r/position/increase/infozauth/r/positions/histzauth/r/positions/auditzauth/r/positions/snapzauth/w/deriv/collateral/setzauth/w/deriv/collateral/limitszauth/r/funding/offerszauth/r/funding/offers/{symbol}zauth/w/funding/offer/submitzauth/w/funding/offer/cancelzauth/w/funding/offer/cancel/allzauth/w/funding/closezauth/w/funding/autozauth/w/funding/keepz#auth/r/funding/offers/{symbol}/histzauth/r/funding/offers/histzauth/r/funding/loanszauth/r/funding/loans/histzauth/r/funding/loans/{symbol}z"auth/r/funding/loans/{symbol}/histzauth/r/funding/creditszauth/r/funding/credits/histzauth/r/funding/credits/{symbol}z$auth/r/funding/credits/{symbol}/histz#auth/r/funding/trades/{symbol}/histzauth/r/funding/trades/histzauth/r/info/funding/{key}zauth/r/info/userzauth/r/summaryzauth/r/logins/histzauth/r/permissionszauth/w/tokenzauth/r/audit/histzauth/w/transferzauth/w/deposit/address   zauth/w/deposit/invoicezauth/w/withdrawz auth/r/movements/{currency}/histzauth/r/movements/histzauth/r/alertsg\(\@zauth/w/alert/setz'auth/w/alert/price:{symbol}:{price}/delz(auth/w/alert/{type}:{symbol}:{price}/delzauth/calc/order/availzauth/w/settings/setzauth/r/settings   )zauth/w/settings/delzauth/r/pulse/histzauth/w/pulse/addzauth/w/pulse/del)r   r   r   r   z0.001z0.0020500000100000025000005000000750000010000000z0.001815000000z0.001620000000z0.001425000000z0.001230000000z0.0008z0.0006z0.0004z0.0002)takermaker)feeSide
percentage	tierBasedr   r   tiersr   )tradingfundingprecisionModeoptionsR0marketlimit)MARKETEXCHANGE MARKETLIMITEXCHANGE LIMITEXCHANGE STOPEXCHANGE FOKEXCHANGE STOP LIMITEXCHANGE IOCr   r   )r   r   USDEURJPYGBPCHN)r   r   r   r   r   exchanger   )rB   r   r   rC   derivativesrE   rD   
includeFeeBITCOINLITECOINETHEREUM	TETHERUSO	TETHERUSL	TETHERUSX	TETHERUSSTETHERUSDTAVAXTETHERUSDTSOLTETHERUSDTALGTETHERUSDTBCHTETHERUSDTKSMTETHERUSDTDVFTETHERUSDTOMG)BTCLTCERC20OMNILIQUIDTRC20EOSAVAXSOLALGOBCHKSMDVFOMG	TETHERUSEr   )	precisionexchangeTypes
orderTypesfiatv2AccountsByTyper   networksnetworksByIdfeatures)IOCFOKPOGTD)
marginModetriggerPricetriggerPriceTypetriggerDirectionstopLossPricetakeProfitPriceattachedStopLossTakeProfittimeInForcehedgedtrailingleveragemarketBuyRequiresPricemarketBuyByCostselfTradePreventionicebergmaxK   	  i )r  r   daysBack	untilDayssymbolRequired)r  triggerr  r#  )r  r   r$  r  r#  )r  r   r!  daysBackCanceledr"  r$  r  r#  '  )	sandboxrP   createOrdersry   r   r   fetchOrdersrb   rz   extendsdefault)linearinverse)r+  rB   rD   rE   
exceptions)110101000110020101001011420060temporarily_unavailable)zavailable balance is onlyznot enough exchange balancezOrder not foundzsymbol: invalid)exactbroadcommonCurrenciesUSTUSDTEUTF0EURTUSTF0ALGr   AMPAMPLATOATOMBCHABCXECBCHNr   DATDATADOGMDOGEDSHDASHEDOPNTEUSEURSEUTHTXHTIDXIDIOTIOTAIQXIQLUNALUNCLUNA2MNAMANAORSz	ORS GroupPASPASSQSHQASHQTMQTUMRBTRBTCSNGSNGLSSTJSTORJTERRAUSTUSTCTSDTUSDYGGYEEDYYWYOYOWUDCUSDCVSYVSYSWAXPXCHFZB)WAXXCHZBT)deep_extendsuperr4   describeparse_numberr1   r*   r"   r$   r!   r-   r,   r+   r&   r(   r%   )self	__class__s    G/var/www/html/turnos/venv/lib/python3.12/site-packages/ccxt/bitfinex.pyr  zbitfinex.describe"   s   h > @ JC
*JC
JJC
 $JC
 t	JC

 JC
 4JC
  XXX $X 	X
 %X %X UX $UX 'X "4X tX X 'X #DX $TX  t!X" &t#X$ (%X& ''X( ()X* "4+X, ,T-X. -e/X0 %d1X2 T3X4 5X6 &u7X8 "59X: +E;X< )%=X> #E?X@ ,UAXB #DCXD $TEXF 'GXH (IXJ "4KXL &tMXN (OXP 1%QXR +DSXT &uUXV #JWXX *4YXZ $T[X\ "5]X^ *5_X` +EaXb tcXd  eXf %egXh $TiXj "5kXl +EmXn !%oXp  qXr dsXt $TuXv +DwXx %dyXz !${X| "4}X~ dX@ !$AXB "5CXD #DEXF  GXH $UIXJ !$KXL )%MXN tOXP QXR USXT "5UXV #DWXX 'YXZ $Z[X\ ]X^ #E_X` &uaXb ucXd TeXf  gXh "5iXj %kXl ! oXJC
B CJC
b cJC
d i4<9
 28F 8eJC
@ ?'?4c? >s? 0	?
 9#? 9#? 4S? 6s? 5c? 5c? 5c? 9#? 7? 1#? 1#?  :3!?" 1##?$ 6s%?& 4S'?( 5c)?* 5c+?, 1#-?. :3/?0 -c1?2 5c3?4 235?6 (7?8 *19?: "3;?< *3=?> '??@ /A?B 4QC?D +AE?F +AG?H +AI?J +AK?L +AM?N HO?P CCQ?R CCS?T A#U?V <SW?X <SY?Z A#[?\ A#]?^ B3_?` B3a?b PQTc?d Ge?f B3g?h DG),(+69-/ILDG&)4779%&}?B +.#&CEN  K )#K .s	K
 (K 1#K .sK .sK .sK -cK 4SK 6sK -cK <SK 6sK  -c!K" 9##K$ .s%K& 3C'K( 23)K* 5c+K, +C-K. 0/K0 4S1K2 83K4 05K6 1#7K8 09K: 6s;K< 9#=K> 0?K@ 9#AKB 6sCKD 6sEKF :3GKH /IKJ .sKKL .sMKN >sOKP 5cQKR /SKT 4SUKV 8WKX =cYKZ 1#[K\ 6s]K^ :3_K` ?aKb >scKd 5ceKf 4SgKh +CiKj )#kKl -cmKn -coKp 'qKr ,SsKt *3uKv 1"wKx 1"yKz *2{K| ;C}K~ 0K@ (AKB +CCKD B3EKF CCGKH 0IKJ .sKKL *3MKN 03-0,.,/UKMOUAJC
l $"&!%!..w7!..w7 "..s3T5F5Fw5OP!..x8$:K:KG:TU!..y94;L;LW;UV!..y94;L;LW;UV!..y94;L;LW;UV!..y94;L;LW;UV!..z:D<M<Mh<WX!..z:D<M<Mh<WX!..z:D<M<Mh<WX!..z:D<M<Mh<WX!..z:D<M<Mg<VW" "..s3T5F5Fw5OP!..x8$:K:KH:UV!..y94;L;LX;VW!..y94;L;LX;VW!..y94;L;LX;VW!..y94;L;LS;QR!..z:D<M<Mc<RS!..z:D<M<Mc<RS!..z:D<M<Mc<RS!..z:D<M<Mc<RS!..z:D<M<Mc<RS""H I'mJC
|	 /}	JC
~	 !
 ''/$&-%- %,+2$+"( 0-
 !     ' *(&#+&$% !% %%'')(&,*+****"  !CD	JC
H $&*(,,0,1)-+/6:#'#'"&#(	( #($($(27+//4#()$. r% ',!%$(%+*/& ',#($)*/	# ',!%#($)*/( $(&+!%$(,0%+#($)*/	*  #u=~ y
 "9  $	 ##QLIJC
b .-'0)*/C	 2C3D'4'0	cJC
F  &!v&!&! &! v	&!
 v&! v&! %&! &! v&! w&! v&! u&! v&! v&! t&!  t!&!" v#&!$ t%&!& '&!( )&!* v+&!, {-&!. v/&!0 v1&!2 v3&!4 v5&!6 w7&!8 w9&!: F;&!< v=&!> v?&!@ wA&!B vC&!D vE&!F K&!GJC
 J J	    c                 $    || j                   d   v S )Nr  )r   r  codes     r  is_fiatzbitfinex.is_fiat/  s    t||F++,r  c                     d|z   S )Nf r  s     r  get_currency_idzbitfinex.get_currency_id2  s    Tzr  c                     || j                   d   v r| j                   d   |   S t        | j                  dz   |z   dz         )NcurrencyNames z not supported for withdrawal)r   r)   r7   r  s     r  get_currency_namezbitfinex.get_currency_name5  sE    4<<00<<066477S=4/2QQRRr  c                     | j                  |      }| j                  |t        | j                  |   d   d   t              S )Nr  amount)safe_symboldecimal_to_precisionr/   marketsr0   )r  symbolr  s      r  amount_to_precisionzbitfinex.amount_to_precision;  sA     !!&)((4<<;OP[;\]e;fhvwwr  c                     | j                  |      }| j                  |t        | j                  |   d   d   | j                        }| j                  |t
        dt              S )Nr  pricer   )r  r  r.   r  r   r/   r0   )r  r  r  s      r  price_to_precisionzbitfinex.price_to_precisionB  s\    !!&)))%V8L[8YZa8bdhdvdvw
 ((!^LLr  c                     | j                  |      }| j                  |d      }| j                  ddd||      ddd|dS )aY  
        the latest known information on the availability of the exchange API

        https://docs.bitfinex.com/reference/rest-public-platform-status

        :param dict [params]: extra parameters specific to the exchange API endpoint
        :returns dict: a `status structure <https://docs.ccxt.com/#/?id=exchange-status-structure>`
        r   maintenanceok)r   1N)statusupdatedetaurlinfo)publicGetPlatformStatussafe_string)r  paramsresponse	statusRaws       r  fetch_statuszbitfinex.fetch_statusK  sT     //7$$Xq1	&&]'F	S\]
 	
r  c                    | j                  |      }| j                  |      }| j                  |      }|||g\  }}}| j                  |dg       }| j                  |dg       }| j	                  ||      }| j                  |dg       }g }	t        dt        |            D ],  }
||
   }| j                  |d      }| j                  |di       }d}|j                  d      dk\  rd}| }d}d}|j                  d      dk\  r|j                  d      }|d   }|d   }n
|dd }|dd	 }| j                  |      }| j                  |      }|j                  d      }|j                  d      }| j                  |d      }| j                  |d      }|d
z   |z   }| j                  |      }| j                  |      }d}d}|r|}|}|dz   |z   }| j                  |d      }| j                  |d      }d}|r| j                  ||      rd}|	j                  i dd|z   d|d|d|d|d|d|d|d|rdndd|d|d|ddddddd|d|rdnd|rdnd|r| j!                  d      ndddddt#        d      t#        d       d!ddd"| j!                  |      | j!                  |      d"| j!                  d#      dd"ddd"d$d|d%
       / |	S )&a  
        retrieves data on all markets for bitfinex

        https://docs.bitfinex.com/reference/rest-public-conf

        :param dict [params]: extra parameters specific to the exchange API endpoint
        :returns dict[]: an array of objects representing market data
        r   r   TF0FN:      /   r7   tr  basequotesettlebaseIdquoteIdsettleIdtyperB   rD   rC   rE   rF   activecontractr,  r  85)r  r  minr  z1e-8)r  r  r  cost)
r-  contractSizeexpiryexpiryDatetimestrike
optionTyper  limitscreatedr  )publicGetConfPubInfoPairpublicGetConfPubInfoPairFuturespublicGetConfPubListPairMargin	safe_listarray_concat
safe_valuerangelensafe_string_upperfindsplitsafe_currency_coder  r  in_arrayappendr  int)r  r  spotMarketsInfoPromisefuturesMarketsInfoPromisemarginIdsPromisespotMarketsInfofuturesMarketsInfo	marginIdsr  resultipairr7   r   rB   rD   r  r  partsr  r  	splitBase
splitQuoter  r  r  minOrderSizeStringmaxOrderSizeStringrC   s                                r  fetch_marketszbitfinex.fetch_marketsb  s    "&!>!>v!F$($H$H$P!>>vF:PRkm}9~6+Y..!R@!^^,>2F##O5GHOOIq"5	( q#g,' U	A1:D''a0B__T1b1FDwwt}!8DFGwws|q q(AaQq'**62D++G4E

4(IT*J##Iq1D$$Z3ECZ%'F))&1F**73GFH #.!%!1!1&!!<!%!1!1&!!<Fb)4MM 0cBh0&0 0 	0
 &0 &0 70 H0 $F0 0 &0 0 %0 %0 $0  D!0" $$D#0$ %)5d:> 1 1# 6D"&"!#h X  $#!
  $001CD#001CD
  $008#
  $#$  _0 0KU	l r  c                    g d}dj                  |      }d|i}| j                  | j                  ||            }| j                  | j	                  |dg       d      | j                  | j	                  |dg       d      | j                  | j	                  |dg       d      | j                  | j	                  |dg       d      | j                  | j	                  |d	g       d      | j                  | j	                  |d
g       d      | j                  | j	                  |dg       d      | j	                  |dg       | j                  | j	                  |dg       d      d	}i }t        dt        |d               D ]i  }|d   |   }	| j                  |	d      }
| j	                  |	d      }| j                  |d      }| j	                  ||g       }|j                  |
       |||<   k | j	                  |dg       }i }t        dt        |            D ]  }||   }|j                  d      r| j                  |      }| j	                  |d   |g       }| j                  |d      }| j	                  |d   |g       }| j                  |d      }|duxs ||d   v }d}|rd}| j	                  |d   |g       }| j	                  |dg       }| j                  |d      }| j	                  |d   |g       }d}d|z   }| j	                  |d   |g       }| j                  |d      dk(  }| j                  |d      dk(  } i }!| j	                  ||g       }"t        dt        |"            D ]:  }#|"|#   }
| j                  |
      }$|
|
j                         |
dddddddddid	|!|$<   < | j                  ||||||||g||d|| |t!        |      | j#                  | j%                  |            dd|ddd|!d       ||<    |S )!a  
        fetches all available currencies on an exchange

        https://docs.bitfinex.com/reference/rest-public-conf

        :param dict [params]: extra parameters specific to the exchange API endpoint
        :returns dict: an associative dictionary of currencies
        )
zpub:list:currencyzpub:map:currency:symzpub:map:currency:labelzpub:map:currency:unitzpub:map:currency:undlzpub:map:currency:poolzpub:map:currency:explorerzpub:map:currency:tx:feezpub:map:tx:methodzpub:info:tx:status,configr   r      r  r     r     r   	   )	symlabelunitundlpoolexplorerr   r  statusesr  r  r  r  Nr  cryptor   r  r  r  r  r   r  )	r  r7   networkr  depositr   feer  r  T)r  r   )r7   uppercaseIdr  r  r  r8   r  r  r   r  r  r  r  )joinpublicGetConfConfigextendindex_byr  r  r  r  r  endswithr  safe_numbersafe_integernetwork_id_to_codelowersafe_currency_structurer  r  parse_precision)%r  r  labelsr  requestr  indexedindexedNetworksr  
networkObj	networkId
valuesListnetworkNamenetworksListidsr  r7   r  r  r8   r  rawTypeisCryptoCoinr  	feeValuesr   r  r  r  fid
dwStatusesdepositEnabledwithdrawEnabledr  	netwokIdsjr  s%                                        r  fetch_currencieszbitfinex.fetch_currencies  sU   
 &!f
 ++DKK,HIj ==!R!@!D]]4>>(Ar#BAFMM$..1b"A1EMM$..1b"A1EMM$..1b"A1EdnnXq"&EqIMM$..1b"A1ExB7dnnXq"&EqI

 !#q#gj123 	8A ,Q/J((Q7I
A6J**:q9K>>/;KL	*+7OK(	8 nnXq"-q#c(# C	AQB{{4 **2.DNN77#3R<E##E1-D>>'&/2r:D&&tQ/G#4/OR7:;N5NLDwvB?I>>)Q3D""4+C>>'&/2r:DI(C
(;RDJ!..z1=BN"//
A>!COHB?I1c)n- %aL	11)<%#//+("# $!%"#'#'%%!&  77!UD)T:)+ ^  $001E1Ei1PQ#
  ##!	 %-9 F4LYC	H r  c                 X   | j                          | j                  | j                  di       }| j                  |dd      }| j                  |||      }|Ct	        |j                               }t        | j                  dz   dj                  |      z         |dk(  }| j                  |d      }| j                  |      }d|i}	t        d	t        |            D ]  }
||
   }| j                         }| j                  |d
      }|dk7  r||d<   | j                  |d	      }| j                  |dd      }t        |      dz
  }||d dk(  }| xs |}||k(  s||s| j                  |      }| j                  |d      |d<   | j                  |d      |d<   ||	|<    | j!                  |	      S )aa  
        query for balance and get the amount of funds available for trading or funds locked in orders

        https://docs.bitfinex.com/reference/rest-auth-wallets

        :param dict [params]: extra parameters specific to the exchange API endpoint
        :returns dict: a `balance structure <https://docs.ccxt.com/#/?id=balance-structure>`
        r  r  r   Nz. fetchBalance() type parameter must be one of , r   r  r   r  r   debtr    r  f0totalr  free)load_marketsr  r   r  listkeysr    r7   r  omitprivatePostAuthRWalletsr  r  accountsafe_string_lowerr  safe_balance)r  r  accountsByTyperequestedTypeaccountTyper   isDerivativequeryr  r  r  balancer#  interestr  
currencyIdstartisDerivativeCodederivativeConditionr  s                       r  fetch_balancezbitfinex.fetch_balance  s    	7I2N((D&&~}mT++-.D*Z Z]a]f]fgk]l lmm$5		&&)//6)q#h-( 	'AqkGllnG''3H3"*##GQ/D//B?J
Oa'E)%&1T9'3#3#G7Gt#)<..z:#'#3#3GQ#? "&"2"27A">&t!	'"   ((r  r  r  fromAccount	toAccountc                    | j                          | j                  | j                  di       }| j                  ||      }|Ct	        |j                               }t        | j                  dz   dj                  |      z         | j                  ||      }	|	Ct	        |j                               }t        | j                  dz   dj                  |      z         | j                  |      }
| j                  |
|      }| j                  |
|      }| j                  ||      }|||||	d}| j                  | j                  ||            }| j                  |d      }|dk(  r^| j                  |dd	      }| j                  | j                  d
   || j                  dz   |z          t!        | j                  dz   |z         | j#                  d|i|
      S )a  
        transfer currency internally between wallets on the same account

        https://docs.bitfinex.com/reference/rest-auth-transfer

        :param str code: unified currency code
        :param float amount: amount to transfer
        :param str fromAccount: account to transfer from
        :param str toAccount: account to transfer to
        :param dict [params]: extra parameters specific to the exchange API endpoint
        :returns dict: a `transfer structure <https://docs.ccxt.com/#/?id=transfer-structure>`
        r  z' transfer() fromAccount must be one of r  z% transfer() toAccount must be one of )r  currencycurrency_tofromtor   errorr  r  r6  r  r  )r  r  r   r  r  r   r#   r7   r  r5  convert_derivatives_idcurrency_to_precisionprivatePostAuthWTransferr  throw_exactly_matched_exceptionr.  r    parse_transfer)r  r  r  r2  r3  r  r&  fromIdr   toIdr5  fromCurrencyIdtoCurrencyIdrequestedAmountr  r  r9  messages                     r  r   zbitfinex.transfer  s    	7I2N!!.+>>++-.D#DGG.W$WZ^ZcZcdhZi$ijj	:<++-.D#DGG.U$UX\XaXabfXg$ghh==&44X{K228YG44T6B &&'
 00Wf1MN,   1-G&&xB7G001I7TXT[T[^aTadkTkl# 788""Hh#7BBr  Nr   r5  c           
         | j                  |d      }| j                  |d      }| j                  |d      }| j                  |d      }| j                  |d      }| j                  |d      }| j                  |d      }	d || j	                  |      | j                  |	      | j                  |d      | j                  ||      |||d		S )
Nr  r   r  r   r  r  r  r  )	r7   	timestampdatetimer  r  r5  r2  r3  r  )r  r  r  r  iso8601parse_transfer_statusr  r  )
r  r   r5  r  rF  r  r2  r3  r-  r  s
             r  r>  zbitfinex.parse_transfer  s    0 (3%%fa0	vq)&&tQ/$$T1-	%%dA.
!!&!,"Y/008&&tQ///
HE&"

 
	
r  r  c                 4    dddd}| j                  |||      S )Nr  failed)SUCCESSERRORFAILUREr  r  r  r  s      r  rI  zbitfinex.parse_transfer_status@  s)    

 &&99r  c                    | j                  |d      }| j                  |d      }| j                  |dg       }d }|dk(  r2| j                  |d|      }t        |      dz
  }||d  dk(  }|s|dz   }|S |dk7  r| j                  |d|      }|S |}|S )	Nr  r   r  r   r  r  rC   r   )r  r  r  )	r  r5  r  r  
transferId
underlyingr-  r.  r/  s	            r  r:  zbitfinex.convert_derivatives_idH  s     x0%%dA.
__T1b1

= ))*aDJ
Oa'E)%&1T9#'$.

 	 X))*aDJ  $Jr  r  r   c                    | j                          | j                  | j                  dd      }| j                  |      }|d   |d}|||d<   | j	                  ||      }| j                  |      }| j                         }	|d   g g |	| j                  |	      dd}
|d   dk(  rd	nd
}t        d
t        |            D ]  }||   }| j                  ||      }| j                  |d      }t        j                  |      }t        j                  |d      rdnd}|
|   }|j                  || j!                  |      g        | j#                  |
d   d
d      |
d<   | j#                  |
d   d
      |
d<   |
S )aV  
        fetches information on open orders with bid(buy) and ask(sell) prices, volumes and other data

        https://docs.bitfinex.com/reference/rest-public-book

        :param str symbol: unified symbol of the market to fetch the order book for
        :param int [limit]: the maximum amount of order book entries to return, bitfinex only allows 1, 25, or 100
        :param dict [params]: extra parameters specific to the exchange API endpoint
        :returns dict: A dictionary of `order book structures <https://docs.ccxt.com/#/?id=order-book-structure>` indexed by market symbols
        r  r   r7   )r  r  Nr  r  )r  bidsasksrF  rG  noncer   r   r  r   rU  rV  T)r  r  r   r   r  publicGetBookSymbolPrecisionmillisecondsrH  r  r  r  r  r2   
string_abs	string_gtr  r  sort_by)r  r  r   r  r  r   r  fullRequest	orderbookrF  r  
priceIndexr  orderr  signedAmountr  side
resultSides                      r  fetch_order_bookzbitfinex.fetch_order_book^  s    	OODLL+tD	V$Tl"
 "GENkk'6255kB	%%'	X&"Y/
 '{3t;Q!
q#i.) 	BAaLE$$UJ7E++E15L''5F$..|SA6vDJud&7&7&?@A	B fVna>vfVna8vr  tickerr   c                 N   t        |      }|dk(  xs |dk(  }d }d}d}|rd}|dk(  }n)| j                  |d      }| j                  ||      }|dk(  }| j                  d |      }d }	d }
d }d }d }d }d }d }|r| j                  |d|z
        }	| j                  |d|z
        }
| j                  |d|z
        }| j                  |d	|z
        }| j                  |d
|z
        }| j                  |d|z
        }| j                  |d|z
        }| j                  |d|z
        }n| j                  |d|z
        }	| j                  |d|z
        }
| j                  |d|z
        }| j                  |d|z
        }| j                  |d|z
        }t	        j
                  |d      }| j                  |d	|z
        }| j                  |d
|z
        }| j                  |d|z
        }| 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#|      S )$Nr   r   r   Fr      r  r  r   r           r  r  r  100r  rF  rG  highlowbid	bidVolumeask	askVolumevwapopencloselastpreviousClosechanger   average)
baseVolumequoteVolumer  )r  r  safe_marketr  r2   
string_mulsafe_ticker)r  re  r   lengthisFetchTickerr  
minusIndexisFundingCurrencymarketIdru  rn  rp  rw  r   volumerl  rm  s                    r  parse_tickerzbitfinex.parse_ticker  s   R V286R<
!J!'2''2H%%h7F!'2!!$/
##FBO<D""61z>:C""61z>:C%%fa*n=F))&!j.AJ%%fb:o>F##FBO<D""62
?;C ##FA
N;D""61z>:C""61z>:C%%fa*n=F))&!j.AJ ++J>J%%fa*n=F##FA
N;D""62
?;C !
f!
!
 !
 D	!

 3!
 3!
 !
 3!
 !
 D!
 D!
 T!
 D!
 T!
 f!
  *!!
" t#!
$ !)!
* + 	r  symbolsc                    | j                          | j                  |      }i }|&| j                  |      }dj                  |      |d<   nd|d<   | j	                  | j                  ||            }| j                  ||      S )a  
        fetches price tickers for multiple markets, statistical information calculated over the past 24 hours for each market

        https://docs.bitfinex.com/reference/rest-public-tickers

        :param str[]|None symbols: unified symbols of the markets to fetch the ticker for, all market tickers are returned if not assigned
        :param dict [params]: extra parameters specific to the exchange API endpoint
        :returns dict: a dictionary of `ticker structures <https://docs.ccxt.com/#/?id=ticker-structure>`
        r  r  ALL)r  market_symbols
market_idsr  publicGetTickersr  parse_tickers)r  r  r  r  r  r   s         r  fetch_tickerszbitfinex.fetch_tickers  s     	%%g.//'*C!$#GI!&GI''GV(DEP !!'733r  c                     | j                          | j                  |      }d|d   i}| j                  | j                  ||            }| j	                  ||      S )a  
        fetches a price ticker, a statistical calculation with the information calculated over the past 24 hours for a specific market

        https://docs.bitfinex.com/reference/rest-public-ticker

        :param str symbol: unified symbol of the market to fetch the ticker for
        :param dict [params]: extra parameters specific to the exchange API endpoint
        :returns dict: a `ticker structure <https://docs.ccxt.com/#/?id=ticker-structure>`
        r  r7   )r  r   publicGetTickerSymbolr  r  )r  r  r  r   r  re  s         r  fetch_tickerzbitfinex.fetch_ticker0  s^     	V$fTl
 ++DKK,HI  00r  tradec                 F   | j                  |dg       }t        |      }|dkD  }| j                  |d      }|rdnd}d }| j                  ||      }	|rdnd}
| j                  ||
      }|	d   dk(  rd}t        j                  |	      }	nd	}d }d }d }d }| j                  d |      }|rdnd
}| j                  ||      }|r|d
   }| j                  |      }| j                  |d      }| j                  |d      }|d
k(  rdnd}| j                  |d      }t        j                  |      }| j                  |d      }| j                  |      }||d}|d   }| j                  | j                  d   |      }| j                  ||| j                  |      |||||||	d ||d|      S )Nr  r  r   r  r  r  -sellbuyr   r   r   r   r  r   )r  r5  r  r  )r7   rF  rG  r  r`  rb  r  takerOrMakerr  r  r  r  r  )r  r  r  r2   rZ  r  r  
string_negr  r   
safe_traderH  )r  r  r   	tradeListtradeLength	isPrivater7   amountIndexrb  amountStringr_  priceStringorderIdr  r  r  r  timestampIndexrF  r  r   feeCostStringfeeCurrencyIdfeeCurrency	orderTypes                            r  parse_tradezbitfinex.parse_tradeB  s   8 NN5(B7	)n 1_	i+$a!''	;?#Q
&&y*=?c!D"--l;LD!!$/'Q%%i@	 |H%%h/F&&y!4G%%i3E',z7L ,,Y:M#..}=M ,,Y;M11-@K%'C "!I##DLL$A9MD"Y/( " 
  	r  sincec                    | j                          d}| j                  |dd      \  }}|r| j                  d||||d      S | j                  |      }d}d|d   i}|||d	<   d
}|t	        |d      |d<   ||d<   | j                  d||      \  }}| j                  | j                  ||            }	| j                  |	d      }
g }t        dt        |
            D ]  }|j                  d|
|   i        | j                  ||d|      S )aw  
        get the list of most recent trades for a particular symbol

        https://docs.bitfinex.com/reference/rest-public-trades

        :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, default 120, max 10000
        :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 [available parameters](https://github.com/ccxt/ccxt/wiki/Manual#pagination-params)
        :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=public-trades>`
        FfetchTradespaginater&  z-1r  r7   Nr.  r  r   sortendr   r   r  )r  handle_option_and_paramsfetch_paginated_call_dynamicr   r  handle_until_optionpublicGetTradesSymbolHistr  r\  r  r  r  parse_trades)r  r  r  r   r  r  r   r  r  r  trades
tradesListr  s                r  fetch_tradeszbitfinex.fetch_trades  s<    	88PZ[&44]FESXZ`bghhV$fTl
 $GGD"5%0GG225'6J11$++gv2NO h*
q#f+& 	5Ax34	5  VT5AAr  r   d   c           	         | j                          d}| j                  |dd      \  }}|r| j                  d|||||d      S | j                  |      }|d}nt	        |d      }|d   | j                  | j                  ||      d|d}|||d<   | j                  d	||      \  }}| j                  | j                  ||            }	| j                  |	||||      S )
a  
        fetches historical candlestick data containing the open, high, low, and close price, and the volume of a market

        https://docs.bitfinex.com/reference/rest-public-candles

        :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, default 100 max 10000
        :param dict [params]: extra parameters specific to the exchange API endpoint
        :returns int[][]: A list of candles ordered, open, high, low, close, volume
        :param int [params.until]: timestamp in ms of the latest candle to fetch
        :param boolean [params.paginate]: default False, when True will automatically paginate by calling self endpoint multiple times. See in the docs all the [available parameters](https://github.com/ccxt/ccxt/wiki/Manual#pagination-params)
        Frz   r  r&  r7   r   )r  	timeframer  r   r.  r  )r  r  "fetch_paginated_call_deterministicr   r  r  r   r  (publicGetCandlesTradeTimeframeSymbolHistr  parse_ohlcvs
r  r  r  r  r   r  r  r   r  r  s
             r  fetch_ohlcvzbitfinex.fetch_ohlcv  s    	88zZ&::<QVX]_hjprwxxV$=Eu%ETl))$//9iP	
 $GG225'6J@@WV\A]^   69eUKKr  c           	          | j                  |d      | j                  |d      | j                  |d      | j                  |d      | j                  |d      | j                  |d      gS )Nr   r   r  r  r  r  )r  r  )r  ohlcvr   s      r  parse_ohlcvzbitfinex.parse_ohlcv  sn     eQ'UA&UA&UA&UA&UA&
 	
r  c                     ||S |j                  d      }| j                  |d      }ddddddddddd
}| j                  |||      S )Nr  r   rs  closedcanceledrejected)
ACTIVE	PARTIALLYEXECUTEDCANCELEDINSUFFICIENTzPOSTONLY CANCELEDRSN_DUST	RSN_PAUSEzIOC CANCELEDzFILLORKILL CANCELED)r  r  )r  r  r  stater  s        r  parse_order_statuszbitfinex.parse_order_status  sh    >MS!  * "&!+"#&#-
 %88r  c                 <    dgdgddgd}| j                  ||d       S )N
reduceOnlypostOnly)102440965120)r  )r  flags
flagValuess      r  parse_order_flagszbitfinex.parse_order_flags  s2     "NL!:.

 z5$77r  c                 6    ddddd}| j                  ||d      S )Nr  r  )r   r   r  r  GTCrO  )r  r  r  s      r  parse_time_in_forcezbitfinex.parse_time_in_force#  s,    !!	

 
Iu==r  r`  c                    | j                  |d      }| j                  |d      }| j                  |d      }| j                  |      }| j                  |d      }t	        j
                  | j                  |d            }| j                  |d      }	t	        j
                  |	      }
t	        j                  |	d      rdnd	}| j                  |d
      }| j                  | j                  | j                  d      |      }| j                  |      }| j                  |d      }| j                  |      }d}|%t        dt        |            D ]  }||   dk(  sd} | j                  |d      }d }|dk(  s|dk(  r+d }| j                  |d      }|dk(  r| j                  |d      }d }| j                  |d      }|2|j                  d      }| j                  | j                  |d            }| j                  |d      }| j                  |d      }| j                  i d|d|d|d|d| j!                  |      dd d|d|d |d|d!|d"|d#|d$|
d%d d&|d'd ||d d d(|      S ))Nr  r   r  r  r  r  r   r  r  r   r  ri  Fr  Tr   r   r      rj   @ rg  r  r  r7   clientOrderIdrF  rG  lastTradeTimestampr  r  r  rb  r  r  r  r  rx  filled)	remainingr  r  r  )r  r  r  r  r2   rZ  	string_ltr  r   r  r  r  r  r  r  
safe_orderrH  )r  r`  r   	orderListr7   r  r  rF  r  ra  r  rb  r  r  r  rawFlagsr  r  r  r  r  r  statusStringr  rx  r  s                             r  parse_orderzbitfinex.parse_order,  s   NN5(3	i+##Iq1!!(+ %%i3	&&t'7'7	1'EF	''	15##L1 **<=v5$$Y2	o NPYZ..y9##Ir2&&x01c%j) $8z)#H$   B/(i;P.PE++Ir:L11((B7''	26# &&u-E,,T-=-=eQ-GHF""9b1((A6  
I 
" 
 ] 
 	 

 Y/ 
 !$ 
 f 
 D 
 ; 
  
 D 
 U 
 L 
 f 
 D 
  w! 
" d# 
$ #+ 
, - 	r  r  rb  r  c                    | j                  |      }| j                  ||      }|dk(  r|nt        j                  |      }|d   |d}	| j	                  |dd      }
| j                  |d      }| j                  |d      }| j                  |dd	      }| j                  |d
d	      }| j                  |dd      }|j                         }|d}||	d<   n6|
4| j                  ||
      |	d<   |dk(  rd}| j                  ||      |	d<   nd}|dk(  }|dk(  }|xs |dk(  }|s|r|t        | j                  dz         |s|r|dk(  rt        | j                  dz         |dk7  r|
| j                  ||      |	d<   |rd}n|rd}d}| j                  d|      \  }}|d   r|d|z   }||	d<   d}|r| j                  |d       }|r| j                  |d!      }|dk7  r||	d"<   |||	d<   | j                  |g d#      }| j                  |	|      S )$a  
 @ignore
        helper function to build an order request
        :param str symbol: unified symbol of the market to create an order in
        :param str type: 'market' or 'limit'
        :param str side: 'buy' or 'sell'
        :param float amount: how much you want to trade in units of the base currency
        :param float [price]: the price of the order, in units of the quote currency, ignored in market orders
        :param dict [params]: extra parameters specific to the exchange API endpoint
        :param float [params.triggerPrice]: The price at which a trigger order is triggered at
        :param str [params.timeInForce]: "GTC", "IOC", "FOK", or "PO"
        :param bool [params.postOnly]:
        :param bool [params.reduceOnly]: Ensures that the executed order does not flip the opened position.
        :param int [params.flags]: additional order parameters: 4096(Post Only), 1024(Reduce Only), 16384(OCO), 64(Hidden), 512(Close), 524288(No Var Rates)
        :param int [params.lev]: leverage for a derivative order, supported by derivative symbol orders only. The value should be between 1 and 100 inclusive.
        :param str [params.price_traling]: The trailing price for a trailing stop order
        :param str [params.price_aux_limit]: Order price for stop limit orders
        :param str [params.price_oco_stop]: OCO stop price
        :returns dict: an `order structure <https://github.com/ccxt/ccxt/wiki/Manual#order-structure>`
        r  r7   )r  r  	stopPricer  trailingAmountr  r  Fr  cidr  NzTRAILING STOPprice_trailingr  r   z
STOP LIMITprice_aux_limitSTOPr  r  r  z@ createOrder() requires a price argument with IOC and FOK ordersr   z7 createOrder() does not allow market IOC and FOK ordersrP   rB   z	EXCHANGE r  r         r  )r  r  r  r  r  r  r  )r   r  r2   r  safe_string_2r  	safe_boolsafe_value_2upperr  r'   r7   handle_margin_mode_and_paramssumr!  r  )r  r  r  rb  r  r  r  r   r  r  r  r  r  postOnlyParamr  r  r  iocfokr  r  r  s                         r  create_order_requestzbitfinex.create_order_requesth  sk   * V$//?(,|G<N<N|<\Tl"
 ))&+~N))&2BC&&v}=vz5A^^FL%@
))&%IJJL	%'I(6G$%%#66v|LGGw(	-1-D-DVU-S)*"	e#e#!:kT&93U]tww)kkll3TX-tww)bbccH<#7#66vuEGGII
!??vV
F&>z1#i/I#HHUD)EHHUD)EA:$GG$*GEN6  $M  N{{7F++r  c                    | j                          | j                  |      }| j                  ||||||      }| j                  |      }	| j	                  |	d      }
|
dk7  r7|	d   }|	d   }t        | j                  dz   |	d   z   dz   |z   dz   |z   dz         | j                  |	d	g       }| j                  |d
      }d|i}| j                  ||      S )a  
        create an order on the exchange

        https://docs.bitfinex.com/reference/rest-auth-submit-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]: price of the order
        :param dict [params]: extra parameters specific to the exchange API endpoint
        :param float [params.triggerPrice]: the price that triggers a trigger order
        :param str [params.timeInForce]: "GTC", "IOC", "FOK", or "PO"
        :param boolean [params.postOnly]: set to True if you want to make a post only order
        :param boolean [params.reduceOnly]: indicates that the order is to reduce the size of a position
        :param int [params.flags]: additional order parameters: 4096(Post Only), 1024(Reduce Only), 16384(OCO), 64(Hidden), 512(Close), 524288(No Var Rates)
        :param int [params.lev]: leverage for a derivative order, supported by derivative symbol orders only. The value should be between 1 and 100 inclusive.
        :param str [params.price_aux_limit]: order price for stop limit orders
        :param str [params.price_oco_stop]: OCO stop price
        :param str [params.trailingAmount]: *swap only* the quote amount to trail away from the current market price
        :returns dict: an `order structure <https://docs.ccxt.com/#/?id=order-structure>`
        r  rL  r  r  r  : (#)r  r   r  )	r  r   r  privatePostAuthWOrderSubmitr  r    r7   r  r  )r  r  r  rb  r  r  r  r   r  r  r  	errorCode	errorTextordersr`  newOrders                   r  create_orderzbitfinex.create_order  s    . 	V$++FD$vV33G<` !!(A.Y I I# ;d BY NQU UXa adg ghh!R0vq)e$&11r  r  c           	      z   | j                          g }t        dt        |            D ]  }||   }| j                  |d      }| j                  |d      }| j                  |d      }| j	                  |d      }	| j	                  |d      }
| j                  |di       }| j                  ||||	|
|      }|j                  d|g        d	|i}| j                  |      }g }| j                  |d
g       }t        dt        |            D ]"  }||   }|d
   }|j                  d|d   i       $ | j                  |      S )a  
        create a list of trade orders

        https://docs.bitfinex.com/reference/rest-auth-order-multi

        :param Array orders: list of orders to create, each object should contain the parameters required by createOrder, namely symbol, type, side, amount, price and params
        :param dict [params]: extra parameters specific to the exchange API endpoint
        :returns dict: an `order structure <https://docs.ccxt.com/#/?id=order-structure>`
        r   r  r  rb  r  r  r  onopsr  r  )r  r  r  r  r  	safe_dictr  r  privatePostAuthWOrderMultir  parse_orders)r  r  r  ordersRequestsr  rawOrderr  r  rb  r  r  orderParamsorderRequestr  r  resultsdataentryindividualOrders                      r  create_orderszbitfinex.create_orders
  sa    	q#f+& 		8AayH%%h9F##Hf5D##Hf5D%%h9F$$Xw7E..8R@K44VT4QVXcdL!!4"67		8 >
 227;4 ~~h2.q#d)$ 	;AGE#AhONNHoa&89:	;   ))r  c                    | j                          ddi}| j                  | j                  ||            }| j                  |dg       }g }t	        dt        |            D ]  }|j                  d||   i        | j                  |      S )a  
        cancel all open orders

        https://docs.bitfinex.com/reference/rest-auth-cancel-orders-multiple

        :param str symbol: unified market symbol, only orders in the market of self symbol are cancelled when symbol is not None
        :param dict [params]: extra parameters specific to the exchange API endpoint
        :returns dict[]: a list of `order structures <https://docs.ccxt.com/#/?id=order-structure>`
        allr   r  r   r  )r   privatePostAuthWOrderCancelMultir  r  r  r  r  r  )r  r  r  r  r  r  
ordersListr  s           r  cancel_all_orderszbitfinex.cancel_all_ordersE  s     	1
 88Wf9UV!R0
q#f+& 	5Ax34	5  ,,r  r7   c                    | j                          | j                  |dd      }d}d}|| j                  |      }|F| j                  |d      }|t	        | j
                  dz         ||d}| j                  |ddg      }ndt        |      i}| j                  | j                  ||            }| j                  |d      }	d	|	i}
| j                  |
|      S )
ay  
        cancels an open order

        https://docs.bitfinex.com/reference/rest-auth-cancel-order

        :param str id: order id
        :param str symbol: Not used by bitfinex cancelOrder()
        :param dict [params]: extra parameters specific to the exchange API endpoint
        :returns dict: An `order structure <https://docs.ccxt.com/#/?id=order-structure>`
        r  r  NcidDatez\ canceling an order by clientOrderId('cid') requires both 'cid' and 'cid_date'('YYYY-MM-DD'))r  cid_dater7   r  r  )r  r  r   r  r'   r7   r!  r  privatePostAuthWOrderCancelr  r  )r  r7   r  r  r  r  r   r  r  r`  r  s              r  cancel_orderzbitfinex.cancel_orderZ  s     	?[[(F?oofi8G"477  .L  $L  M  M#G YYv'?@F c"gG 33DKK4PQ!,e$&11r  c                    | j                          t        dt        |            D ]  }| j                  ||         ||<    d|i}d}|| j	                  |      }| j                  | j                  ||            }| j                  |dg       }g }	t        dt        |            D ]  }|	j                  d||   i        | j                  |	|      S )a  
        cancel multiple orders at the same time

        https://docs.bitfinex.com/reference/rest-auth-cancel-orders-multiple

        :param str[] ids: order ids
        :param str symbol: unified market symbol, default is None
        :param dict [params]: extra parameters specific to the exchange API endpoint
        :returns dict: an array of `order structures <https://docs.ccxt.com/#/?id=order-structure>`
        r   r7   Nr  r  )
r  r  r  parse_to_numericr   r  r  r  r  r  )
r  r  r  r  r  r  r   r  r  r  s
             r  cancel_orderszbitfinex.cancel_orders}  s     	q#c(# 	3A**3q62CF	3 #
 [[(F88Wf9UVf !R0
q#f+& 	5Ax34	5  V44r  c           	          dt        |      gi}| j                  |dd| j                  ||            }| j                  |d      }|t	        | j
                  dz   |z   dz         |S a  
        fetch an open order by it's id

        https://docs.bitfinex.com/reference/rest-auth-retrieve-orders
        https://docs.bitfinex.com/reference/rest-auth-retrieve-orders-by-symbol

        :param str id: order id
        :param str symbol: unified market symbol, default is None
        :param dict [params]: extra parameters specific to the exchange API endpoint
        :returns dict: an `order structure <https://docs.ccxt.com/#/?id=order-structure>`
        r7   Nr   z order z
 not found)r  fetch_open_ordersr  r  r(   r7   r  r7   r  r  r  r  r`  s          r  fetch_open_orderzbitfinex.fetch_open_order  sr     3r7)
 ''dDKKQW<XY*=) 3b 8< GHHr  c           	          dt        |      gi}| j                  |dd| j                  ||            }| j                  |d      }|t	        | j
                  dz   |z   dz         |S r  )r  fetch_closed_ordersr  r  r(   r7   r   s          r  fetch_closed_orderzbitfinex.fetch_closed_order  sr     3r7)
 ))&$dkk'SY>Z[*=) 3b 8< GHHr  c                 v   | j                          i }d}d}|"| j                  | j                  ||            }n:| j                  |      }|d   |d<   | j	                  | j                  ||            }g }t        dt        |            D ]  }	|j                  d||	   i        | j                  ||||      S )a`  
        fetch all unfilled currently open orders

        https://docs.bitfinex.com/reference/rest-auth-retrieve-orders
        https://docs.bitfinex.com/reference/rest-auth-retrieve-orders-by-symbol

        :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
        :returns Order[]: a list of `order structures <https://docs.ccxt.com/#/?id=order-structure>`
        Nr7   r  r   r  )	r  privatePostAuthROrdersr  r   privatePostAuthROrdersSymbolr  r  r  r  )
r  r  r  r   r  r  r   r  r  r  s
             r  r  zbitfinex.fetch_open_orders  s     	>224;;w3OPH[[(F &tGH88Wf9UVHN 
q#h-( 	7Ax!56	7  VUEBBr  c                    | j                          d}| j                  |dd      \  }}|r| j                  d||||      S i }|||d<   |||d<   | j                  d||      \  }}d}d}|"| j	                  | j                  ||            }n:| j                  |      }|d   |d	<   | j                  | j                  ||            }g }	t        d
t        |            D ]  }
|	j                  d||
   i        | j                  |	|||      S )a  
        fetches information on multiple closed orders made by the user

        https://docs.bitfinex.com/reference/rest-auth-retrieve-orders
        https://docs.bitfinex.com/reference/rest-auth-retrieve-orders-by-symbol

        :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]: the latest time in ms to fetch entries for
        :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 Order[]: a list of `order structures <https://docs.ccxt.com/#/?id=order-structure>`
        Frb   r  Nr.  r   r  r7   r  r   r  )r  r  r  r  privatePostAuthROrdersHistr  r    privatePostAuthROrdersSymbolHistr  r  r  r  )r  r  r  r   r  r  r  r   r  r  r  s              r  r#  zbitfinex.fetch_closed_orders6  s?     	88ATV`a&445H&RWY^`fgg$GG$GG225'6J>66t{{7F7STH[[(F &tGH<<T[[RX=YZHN 
q#h-( 	7Ax!56	7  VUEBBr  c                 l   |t        | j                  dz         | j                          | j                  |      }t	        |      }||d   d}| j                  | j                  ||            }	g }
t        dt        |	            D ]  }|
j                  d|	|   i        | j                  |
|||      S )a  
        fetch all the trades made from a single order

        https://docs.bitfinex.com/reference/rest-auth-order-trades

        :param str id: order id
        :param str symbol: unified market symbol
        :param int [since]: the earliest time in ms to fetch trades for
        :param int [limit]: the maximum number of trades to retrieve
        :param dict [params]: extra parameters specific to the exchange API endpoint
        :returns dict[]: a list of `trade structures <https://docs.ccxt.com/#/?id=trade-structure>`
        z. fetchOrderTrades() requires a symbol argumentr7   )r7   r  r   r  )r#   r7   r  r   r  #privatePostAuthROrderSymbolIdTradesr  r  r  r  r  )r  r7   r  r  r   r  r   r  r  r  r  r  s               r  fetch_order_tradeszbitfinex.fetch_order_trades  s     >#DGG.^$^__V$b'Tl

 ;;DKKQW<XY
q#h-( 	7Ax!56	7  VUEBBr  c                    | j                          d}d| j                         i}|||d<   |||d<   d}|;| j                  |      }|d   |d<   | j                  | j	                  ||            }n!| j                  | j	                  ||            }g }t        dt        |            D ]  }	|j                  d||	   i        | j                  ||||      S )	a<  
        fetch all trades made by the user

        https://docs.bitfinex.com/reference/rest-auth-trades
        https://docs.bitfinex.com/reference/rest-auth-trades-by-symbol

        :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
        :returns Trade[]: a list of `trade structures <https://docs.ccxt.com/#/?id=trade-structure>`
        Nr  r.  r   r7   r  r   r  )
r  rY  r    privatePostAuthRTradesSymbolHistr  privatePostAuthRTradesHistr  r  r  r  )
r  r  r  r   r  r   r  r  r  r  s
             r  fetch_my_tradeszbitfinex.fetch_my_trades  s     	4$$&
 $GG$GG[[(F &tGH<<T[[RX=YZH66t{{7F7STH
q#h-( 	7Ax!56	7  VUEBBr  c                 n    | j                          ddi}| j                  || j                  ||            S )a  
        create a currency deposit address

        https://docs.bitfinex.com/reference/rest-auth-deposit-address

        :param str code: unified currency code of the currency for the deposit address
        :param dict [params]: extra parameters specific to the exchange API endpoint
        :returns dict: an `address structure <https://docs.ccxt.com/#/?id=address-structure>`
        op_renewr   )r  fetch_deposit_addressr  )r  r  r  r  s       r  create_deposit_addresszbitfinex.create_deposit_address  s<     	
 ))$GV0LMMr  c                    | j                          | j                  |      }| j                  |d|      }| j                  |di       }| j                  ||      }| j                  |d      }|t	        | j
                  dz   |z   dz         | j                  |dd      }| j                  |dd      }||d	d
}	| j                  | j                  |	|            }
| j                  |
dg       }| j                  |d      }|| j                  |d      n|}|dn| j                  |d      }| j                  |       |||d|
dS )a  
        fetch the deposit address for a currency associated with self account

        https://docs.bitfinex.com/reference/rest-auth-deposit-address

        :param str code: unified currency code
        :param dict [params]: extra parameters specific to the exchange API endpoint
        :returns dict: an `address structure <https://docs.ccxt.com/#/?id=address-structure>`
        r  r  r7   Nz5 fetchDepositAddress() could not find a network for 'D'. You can specify it by providing the 'network' value inside paramswalletr   r   )methodr8  r3  r  r  )r5  addresstagr  r  )
r  r5  r  r  r#   r7   r!  privatePostAuthWDepositAddressr  check_address)r  r  r  r5  r  currencyNetworkscurrencyNetworkr  r8  r  r  r  poolAddressr:  r;  s                  r  r4  zbitfinex.fetch_deposit_address  sn    	==&""69d;??8ZD//*:GD$$_d;	#DGG.e$ehl$l  pv  %v  w  w!!&(J?69h7

 66t{{7F7ST( 1b1&&vq12=2E$""61-K"*d1A1A&!1L7#
 	
r  c                 D    dddddddddddd}| j                  |||      S )Nr  rK  r  pending)rL  	COMPLETEDrM  rN  r  zPENDING APPROVALPENDINGzPENDING REVIEWzPENDING CANCELLATIONSENDINGzUSER APPROVEDrO  rP  s      r  parse_transaction_statusz!bitfinex.parse_transaction_status	  sA    " ) '$- &
 &&99r  transactionc                 R   t        |      }d }d }d }d }d }d }	d }
d }d }d }d }d }d }|dk(  r| j                  |dg       }| j                  |d      }||d   }| j                  |d      }|t	        j
                  |      }| j                  |d      }| j                  |d      }d}	|dk(  rd }d}	| j                  |d      }
d	}| j                  |d
      }| j                  |j                               }nG|dk(  rA| j                  |d      }| j                  |d      }| j                  ||      }| j                  |d
      }| j                  |      }| j                  |d      }| j                  |d      }| j                  | j                  |d            }	| j                  |d      }t	        j
                  |      }|t	        j                  |d      rd	}nd}| j                  |d      }|t	        j
                  |      }| j                  |d      }| j                  |d      }| j                  |d      }i d|d|d|d|d|d|d| j                  |      d|	d|d| j                  |      d |d!d d"|d#|
d$d d%|
d&||d || j                  |      d d'd(S ))Nr   r  r   r  r  r  rK  r  
withdrawalr     r   r  r  ri  r   r  rj  r         r  r7   txidr  r5  r  r  r  rF  rG  r:  addressFrom	addressTor;  tagFromtagTor  )r5  r  rate)commentinternalr  )r  r  r  r  r2   rZ  r  r  r  r  rF  r  r  rH  )r  rG  r5  transactionLengthrF  r  r  r  r7   r  r;  r  feeCostrM  rO  r  rS  r  r  r-  ra  s                        r  parse_transactionzbitfinex.parse_transaction	  s}   h  ,		!??;26D))+q9I#'&&tQ/G"!,,W5%%dA.F""4+BFQw!""4+CD((q1I--ioo.?@G"$!!+q1B))+q9J**:x@D((a8I--i8G))+q9I''Q7G2243C3CKQR3STF++K<L''5F'$$\37'D$D&&{B7G"!,,W5((b9I##K4D&&{B7G
K
"
 D
 D	

 
 w
 d''/
 f
 
 Y/
 y
 4
 
 3
 t
  S!
" w#
$  ))'2)
 	
r  c                    | j                          | j                  |      }i }| j                  | j                  di       }| j                  |dg       }| j                  |dg       }| j                  |dg       }| j	                  |d      }| j	                  |d      }	| j	                  |d      }
| j	                  |d      }| j	                  |d      }| j	                  |d      }t        dt        | j                              D ]Z  }| j                  |   }| j                  |      }||ddd}|d	   |v r|	|d
<   ||d<   n|d   r|
|d
<   ||d<   n
||d
<   ||d<   |||<   \ |S )aP  
        fetch the trading fees for multiple markets

        https://docs.bitfinex.com/reference/rest-auth-summary

        :param dict [params]: extra parameters specific to the exchange API endpoint
        :returns dict: a dictionary of `fee structures <https://docs.ccxt.com/#/?id=fee-structure>` indexed by market symbols
        r  r  r   r   r  r  T)r  r  r   r   r  r   r   r  )	r  privatePostAuthRSummaryr  r   r  r  r  r  r   )r  r  r  r  r  feeData	makerData	takerDatamakerFeemakerFeeFiatmakerFeeDerivtakerFeetakerFeeFiattakerFeeDerivr  r  r   r  s                     r  fetch_trading_feeszbitfinex.fetch_trading_fees	  s    	//7H t||VR8//(Ar2OOGQ3	OOGQ3	##Iq1''	15((A6##Iq1''	15((A6q#dll+, 	!A\\!_F[[(F  "!	C g$&+G+G
#,G,G'G'G F6N%	!& r  c                 .   | j                          d}i }|||d<   |||d<   d}|;| j                  |      }|d   |d<   | j                  | j                  ||            }n!| j	                  | j                  ||            }| j                  ||||      S )a  
        fetch history of deposits and withdrawals

        https://docs.bitfinex.com/reference/movement-info
        https://docs.bitfinex.com/reference/rest-auth-movements

        :param str [code]: unified currency code for the currency of the deposit/withdrawals, default is None
        :param int [since]: timestamp in ms of the earliest deposit/withdrawal, default is None
        :param int [limit]: max number of deposit/withdrawals to return, default is None
        :param dict [params]: extra parameters specific to the exchange API endpoint
        :returns dict: a list of `transaction structure <https://docs.ccxt.com/#/?id=transaction-structure>`
        Nr.  r   r  r5  )r  r5  %privatePostAuthRMovementsCurrencyHistr  privatePostAuthRMovementsHistparse_transactions)r  r  r  r   r  r5  r  r  s           r  fetch_deposits_withdrawalsz#bitfinex.fetch_deposits_withdrawals
  s     	$GG$GG}}T*H"*="9GJAA$++gW]B^_H99$++gv:VWH: &&x5%HHr  r:  c                 4   | j                  |       | j                          | j                  |      }| j                  |d|      }| j	                  |d      }| j                  |di       }| j                  ||      }	| j                  |	d      }
|
t        | j                  dz   |z   dz         | j                  |dd      }| j	                  |dd      }|
|| j                  |      |d}|||d	<   | j                  | j                  d
i       }| j                  |dd      }|rd|d<   | j                  | j                  ||            }| j                  |d      }|dk(  rp| j                  dz   |z   }| j                  |dd      }| j                  | j                  d   ||       | j                  | j                  d   ||       t!        |      | j                  |d      }|dk7  r | j                  | j                  d   ||       | j#                  ||      S )a  
        make a withdrawal

        https://docs.bitfinex.com/reference/rest-auth-withdraw

        :param str code: unified currency code
        :param float amount: the amount to withdraw
        :param str address: the address to withdraw to
        :param str tag:
        :param dict [params]: extra parameters specific to the exchange API endpoint
        :returns dict: a `transaction structure <https://docs.ccxt.com/#/?id=transaction-structure>`
        r  r  r7   z* withdraw() could not find a network for 'r7  r8  r   )r9  r8  r  r:  
payment_idr   r   Fr   
fee_deductr   r9  r  r  r  r6  r7  r  success)r=  r  r5  r  r!  r  r#   r7   number_to_stringr   r  privatePostAuthWWithdrawr  r=  r.  throw_broadly_matched_exceptionr    rW  )r  r  r  r:  r;  r  r5  r  r>  r?  r  r8  r  withdrawOptionsr   r  statusMessagefeedbackrD  texts                       r  r   zbitfinex.withdrawJ
  s-    	7#==&""69d;69-??8ZD//*:GD$$_d;	#DGG.Z$Z]a$a  ek  %k  l  l!!&(J?69h7++F3	
 ?$'GL!//$,,
BG^^O\5I
$%GL!00Wf1MN> ((15G#ww}x/H&&xB7G001I7T\]001I7T\]))!,9001I4QUV%%h99r  c                     | j                          | j                  |      }| j                  |      }g }t        dt	        |            D ]  }|j                  d||   i        | j                  ||      S )al  
        fetch all open positions

        https://docs.bitfinex.com/reference/rest-auth-positions

        :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   r  )r  r  privatePostAuthRPositionsr  r  r  parse_positions)r  r  r  r  positionsListr  s         r  fetch_positionszbitfinex.fetch_positions
  s|     	%%g.11&9F q#h-( 	:A  (HQK!89	:##M7;;r  positionc                    | j                  |d      }| j                  |d      }| j                  |d      }| j                  |d      }| j                  |d      }| j                  |d      }| j                  |d      }	| j                  i d|d	| j                  |d
      d| j	                  ||      d| j                  |      ddd| j                  |d      d| j                  |d      d| j                  |d      d| j                  |d      dd dd dd dd dt        j                  |d      rdnddd d |d!| j                  |      | j                  |d"      | j                  |d#      d | j                  |d$      | j                  t        j                  |	|            d | j                  |d%      d d d d&
      S )'Nr  r   r  ri  r  trade_pricetrade_amountr  r7   rh  r  notionalr  isolatedliquidationPricer   
entryPricer  unrealizedPnlr  r   r  	contractsr  	markPrice	lastPricerb  r   longshortr  rF  rG  rj     rg  r  )
lastUpdateTimestampmaintenanceMarginmaintenanceMarginPercentage
collateralinitialMargininitialMarginPercentager  marginRatior  r  )r  r  r  safe_positionr  r  r  r2   r[  rH  r|  )
r  ry  r   positionListr  r  rF  meta
tradePricetradeAmounts
             r  parse_positionzbitfinex.parse_position
  sE   B ~~h9##L!4!!,2%%lB7	b1%%dM:
&&t^<!! #
L#
$""<4#
 d&&x8#
 ))&1	#

 *#
  0 0q A#
 $**<;#
 T--lA>#
 $**<;#
 #
 D#
 #
 #
 g//<F'#
 d#
  !#
" Y/##
$ $(#4#4\2#F!%!1!1,!C+/**<<!..w/A/A+z/Z['+((q9!#7#
  	r  c                 "    | j                         S N)rY  )r  s    r  rW  zbitfinex.nonce  s      ""r  r   GETc                 d   d| j                  ||      z   }| j                  || j                  |            }|dk(  r||z   }n| j                  |z   }| j                  d   |   dz   |z   }	|dk(  r|r|	d| j                  |      z   z  }	|dk(  r| j                          t        | j                               }
| j                  |      }d|z   |
z   |z   }| j                  | j                  |      | j                  | j                        t        j                        }|
| j                  |dd	}|	|||d
S )Nr  r   r   r   ?r   z/api/zapplication/json)z	bfx-noncez
bfx-apikeyzbfx-signaturezContent-Type)r  r9  bodyheaders)implode_paramsr!  extract_paramsr<   r   	urlencodecheck_required_credentialsstrrW  jsonhmacencodesecrethashlibsha384apiKey)r  pathr   r9  r  r  r  r  r*  r  rW  auth	signatures                r  signzbitfinex.sign  s+   ++D&99		&$"5"5d";<$;GmGllW,Giis#c)G3(?sT^^E222)++-

%E99U#DW$u,t3D		$++d"3T[[5Mw~~^I""kk!* 2	G fdwOOr  c
                 &   |t        |t              s| j                  |dd      }
| j                  dz   |z   }| j	                  | j
                  d   |
|       | j                  | j
                  d   |
|       t        | j                  dz   |z         |dk(  rt        | j                  dz         |dk(  rt        | j                  dz   |z         |d	k(  r| j                  |d
d      }| j                  |dd      }| j                  dz   |z   }| j                  | j
                  d   ||       | j	                  | j
                  d   ||       | j	                  | j
                  d   ||       t        | j                  dz   |z   dz   |z   dz         |S )NrD  r9  r  r6  r7  r  z returned empty responsei    r   r  r  r  )

isinstancer  r  r7   r=  r.  ro  r    r*   r  )r  
statusCode
statusTextr  r9  r  r  r  requestHeadersrequestBodyrD  rr  r  r  s                 r  handle_errorszbitfinex.handle_errors2  s   h-,,Xy'J77S=4/44T__W5MwX`a44T__W5MwX`a#DGGcMD$899^*D DEE#DGGcMD$899((1b9I((1b9Iww}y0H001I9V^_001I9V^_001I9V^_#	 9D @9 Ls RSSr  c                    |y |j                  d      dk\  s|j                  d      dk\  ry|j                  d      dk\  ry|j                  d      dk\  s|j                  d      dk\  ry|j                  d      dk\  ry|j                  d	      dk\  ry
|j                  d      dk\  s|j                  d      dk\  ry|S )Nr  r   chargedrebater  rI  rG  r   paymentpayoutr   ry  r  )r  )r  r  s     r  parse_ledger_entry_typez bitfinex.parse_ledger_entry_typeJ  s    <YYu"dii	&:a&?YYx A%YYy!Q&$))L*AQ*F YYz"a'YYy!Q&YYz"a'499Z+@A+EKr  itemc                    | j                  |dg       }d }| j                  |d      }| j                  |d      }| j                  ||      }| j                  ||      }| j	                  |d      }| j                  |d      }	| j                  |d      }
| j                  |d      }|4|j                  d      }| j                  |d      }| j                  |      }| j                  ||d d |d |||	|| j                  |      d |
d d d	|      S )
Nr  r   r   r  r  r  r   r  )r  r7   	directionr#  referenceIdreferenceAccountr  r5  r  rF  rG  beforeafterr  r  )r  r  r  safe_currencyr  r  r  r$  r  safe_ledger_entryrH  )r  r  r5  itemListr  r7   r-  r  rF  r  r  descriptionr  firsts                 r  parse_ledger_entryzbitfinex.parse_ledger_entry\  s6     >>$"5h*%%h2
&&z8<%%j(;%%h2	!!(A.  1-&&x3"%%e,E**5!4E//6D%% $"Y/'
  ! 	r  c                 "   | j                          d}| j                  |dd      \  }}|r| j                  d||||d      S d}i }|||d<   |||d<   | j                  d||      \  }}d}|;| j	                  |      }|d	   |d
<   | j                  | j                  ||            }n!| j                  | j                  ||            }g }	t        dt        |            D ]  }
||
   }|	j                  d|i        | j                  |	|||      S )a  
        fetch the history of changes, actions done by the user or operations that altered the balance of the user

        https://docs.bitfinex.com/reference/rest-auth-ledgers

        :param str [code]: unified currency code, default is None
        :param int [since]: timestamp in ms of the earliest ledger entry, default is None
        :param int [limit]: max number of ledger entries to return, default is None, max is 2500
        :param dict [params]: extra parameters specific to the exchange API endpoint
        :param int [params.until]: timestamp in ms of the latest ledger entry
        :param boolean [params.paginate]: default False, when True will automatically paginate by calling self endpoint multiple times. See in the docs all the [available parameters](https://github.com/ccxt/ccxt/wiki/Manual#pagination-params)
        :returns dict: a `ledger structure <https://docs.ccxt.com/#/?id=ledger>`
        Frr   r  r   Nr.  r   r  r  r5  r   r  )r  r  r  r  r5  #privatePostAuthRLedgersCurrencyHistr  privatePostAuthRLedgersHistr  r  r  parse_ledger)r  r  r  r   r  r  r5  r  r  ledgerObjectsr  r  s               r  fetch_ledgerzbitfinex.fetch_ledger  sG    	88PZ[&44]D%QVX^`dee$GG$GG225'6J}}T*H"*="9GJ??GU[@\]H77GV8TUH  q#h-( 	3AA;D  (D!12	3   %GGr  c                    |t        | j                  dz         | j                          | j                  |      }ddj	                  |      i}| j                  | j                  ||            }| j                  ||      S )a  
        fetch the current funding rate for multiple symbols

        https://docs.bitfinex.com/reference/rest-public-derivatives-status

        :param str[] symbols: list of unified market symbols
        :param dict [params]: extra parameters specific to the exchange API endpoint
        :returns dict[]: a list of `funding rate structures <https://docs.ccxt.com/#/?id=funding-rate-structure>`
        z0 fetchFundingRates() requires a symbols argumentr   r  )r#   r7   r  r  r  publicGetStatusDerivr  parse_funding_ratesr  r  r  	marketIdsr  r  s         r  fetch_funding_rateszbitfinex.fetch_funding_rates  s     ?#DGG.`$`aaOOG,	CHHY'
 ,,T[[&-IJ> '''::r  c           	         |t        | j                  dz         | j                          d}| j                  |dd      \  }}|r| j	                  d|||d|d      S | j                  |      }d|d   i}|||d	<   | j                  d
||      \  }}| j                  | j                  ||            }g }	t        dt        |            D ]*  }
||
   }| j                  ||      }|	j                  |       , g }| j                  |	|||      }t        |      }t        d|      D ]   }
||
z
  dz
  }||   }|j                  |       " |S )aR  
        fetches historical funding rate prices

        https://docs.bitfinex.com/reference/rest-public-derivatives-status-history

        :param str symbol: unified market symbol
        :param int [since]: timestamp in ms of the earliest funding rate entry
        :param int [limit]: max number of funding rate entrys to return
        :param dict [params]: extra parameters specific to the exchange API endpoint
        :param int [params.until]: timestamp in ms of the latest funding rate
        :param boolean [params.paginate]: default False, when True will automatically paginate by calling self endpoint multiple times. See in the docs all the [available parameters](https://github.com/ccxt/ccxt/wiki/Manual#pagination-params)
        :returns dict: a `funding rate structure <https://docs.ccxt.com/#/?id=funding-rate-structure>`
        z5 fetchFundingRateHistory() requires a symbol argumentFrm   r  8h  r  r7   r.  r  r   r   )r#   r7   r  r  r  r   r  publicGetStatusDerivSymbolHistr  r  r  parse_funding_rate_historyr  filter_by_symbol_since_limit)r  r  r  r   r  r  r   r  r  ratesr  frrR  reversedArrayrawRatesratesLengthindexvalueAtIndexs                     r  fetch_funding_rate_historyz#bitfinex.fetch_funding_rate_history  s    >#DGG.e$eff88AZ\fg&::;TV\^cejlprxz~V$fTl
 $GG225'6J66t{{7F7ST> q#h-( 	A!B222v>DLL	 44UFE5Q(mq+& 	/A!Oa'E#E?L  .	/ r  c                    | j                  |d      }| j                  |d      }| j                  |d      }i d|d| j                  ||      d| j                  |d      d| j                  |d	      d
d dd d|d| j	                  |      d| j                  |d      dd dd d| j                  |d      d|d| j	                  |      dd dd dd dd iS )Nr   r   r   r  r  r     
indexPricer  interestRateestimatedSettlePricerF  rG  fundingRateri  fundingTimestampfundingDatetimenextFundingRater  nextFundingTimestampnextFundingDatetimepreviousFundingRatepreviousFundingTimestamppreviousFundingDatetimeinterval)r  r  r  r  rH  )r  r  r   r  rF  r  s         r  parse_funding_ratezbitfinex.parse_funding_rate=  sn   : ##Ha0%%h2	#001=
H
d&&x8
 ))(B7
 $**8Q7	

 D
 #D
 
 Y/
 4++Hb9
 
 t
 t//!<
 #$8
 "4<<0D#E
 "4
  '!
" &t#
$ %
 	
r  c                    | j                  |d      }| j                  |d      }i d|d| j                  d |      d| j                  |d      d| j                  |d      d	d d
d d|d| j                  |      d| j                  |d      dd dd d| j                  |d      d|d| j                  |      dd dd dd S )Nr   r  r  r  r     r  r  r  r  rF  rG  r  rh  r  r  r  r   r  r  r  r  r  )r  r  r  rH  )r  r  r   rF  r  s        r  r  z#bitfinex.parse_funding_rate_historyr  sP   8 %%h2	#001=
H
d&&tV4
 ))(B7
 $**8Q7	

 D
 #D
 
 Y/
 4++Hb9
 
 t
 t//!<
 #$8
 "4<<0D#E
 "4
  '!
" &t#
 	
r  c                     | j                          | j                  |      }dg}|| j                  |      }ddj                  |      i}| j	                  | j                  ||            }| j                  ||      S )a  
        Retrieves the open interest for a list of symbols

        https://docs.bitfinex.com/reference/rest-public-derivatives-status

        :param str[] [symbols]: a list of unified CCXT market symbols
        :param dict [params]: exchange specific parameters
        :returns dict[]: a list of `open interest structures <https://docs.ccxt.com/#/?id=open-interest-structure>`
        r  r   r  )r  r  r  r  r  r  parse_open_interestsr  s         r  fetch_open_interestszbitfinex.fetch_open_interests  s     	%%g.G	0ICHHY'
 ,,T[[&-IJ> ((7;;r  c                     | j                          | j                  |      }d|d   i}| j                  | j                  ||            }| j	                  |d      }| j                  ||      S )ap  
        retrieves the open interest of a contract trading pair

        https://docs.bitfinex.com/reference/rest-public-derivatives-status

        :param str symbol: unified CCXT market symbol
        :param dict [params]: exchange specific parameters
        :returns dict: an `open interest structure <https://docs.ccxt.com/#/?id=open-interest-structure>`
        r   r7   r   )r  r   r  r  r  parse_open_interest)r  r  r  r   r  r  ois          r  fetch_open_interestzbitfinex.fetch_open_interest  sp     	V$F4L
 ,,T[[&-IJ> ^^Ha(''F33r  c           	      f   | j                          d}| j                  |dd      \  }}|r| j                  d|||d|d      S | j                  |      }d|d   i}|||d<   |||d	<   | j	                  d
||      \  }}| j                  | j                  ||            }	| j                  |	|||      S )a  
        retrieves the open interest history of a currency

        https://docs.bitfinex.com/reference/rest-public-derivatives-status-history

        :param str symbol: unified CCXT market symbol
        :param str timeframe: the time period of each row of data, not used by bitfinex
        :param int [since]: the time in ms of the earliest record to retrieve unix timestamp
        :param int [limit]: the number of records in the response
        :param dict [params]: exchange specific parameters
        :param int [params.until]: the time in ms of the latest record to retrieve unix timestamp
        :param boolean [params.paginate]: default False, when True will automatically paginate by calling self endpoint multiple times. See in the docs all the [available parameters](https://github.com/ccxt/ccxt/wiki/Manual#pagination-params)
        :returns: An array of `open interest structures <https://docs.ccxt.com/#/?id=open-interest-structure>`
        Fr|   r  r  r  r  r7   r.  r   r  )r  r  r  r   r  r  r  parse_open_interests_historyr  s
             r  fetch_open_interest_historyz$bitfinex.fetch_open_interest_history  s     	88A[]gh&::;UW]_dfkmqsy{  A  AV$fTl
 $GG$GG225'6J66t{{7F7ST< 0065%PPr  c           	         t        |      }|dk(  rdnd}| j                  |d      }| j                  |d      }| j                  | j	                  ||d d      | j                  ||      d || j                  |      |d|      S )N   rg  r  r   r   rD   )r  openInterestAmountopenInterestValuerF  rG  r  )r  r  r  safe_open_interestr  r  rH  )r  r,  r   interestLengthopenInterestIndexrF  r  s          r  r  zbitfinex.parse_open_interestE  s    v X#1R#7Bb%%h2	##Ha0&&&&xvF"&"2"28=N"O!%"Y/(
  	r  c           	      \   | j                          d}| j                  |dd      \  }}|r| j                  d|||d|d      S | j                  |      }i }|||d<   |||d<   | j	                  d||      \  }}| j                  | j                  ||            }| j                  ||||      S )	aP  
        retrieves the public liquidations of a trading pair

        https://docs.bitfinex.com/reference/rest-public-liquidations

        :param str symbol: unified CCXT market symbol
        :param int [since]: the earliest time in ms to fetch liquidations for
        :param int [limit]: the maximum number of liquidation structures to retrieve
        :param dict [params]: exchange specific parameters
        :param int [params.until]: timestamp in ms of the latest liquidation
        :param boolean [params.paginate]: default False, when True will automatically paginate by calling self endpoint multiple times. See in the docs all the [available parameters](https://github.com/ccxt/ccxt/wiki/Manual#pagination-params)
        :returns dict: an array of `liquidation structures <https://docs.ccxt.com/#/?id=liquidation-structure>`
        Fru   r  r  r  r.  r   r  )r  r  r  r   r  publicGetLiquidationsHistr  parse_liquidations)	r  r  r  r   r  r  r   r  r  s	            r  fetch_liquidationszbitfinex.fetch_liquidations  s     	88ATV`a&::;NPVX]_dfjlrtwxxV$$GG$GG225'6J11$++gv2NO* &&xFFr  c                 H   |d   }| j                  |d      }| j                  |d      }t        j                  | j                  |d            }| j                  |d      }t        j                  ||      }| j                  |d      }	| j                  || j                  ||d d      | j                  |      | j                  |      | j                  |	      | j                  |      | j                  t        j                  ||	            || j                  |      d	      S )	Nr   r  r  r  r  rh  r  )	r  r  r  r  r  	baseValue
quoteValuerF  rG  )	r  r  r2   rZ  r|  safe_liquidationr  r  rH  )
r  liquidationr   r  rF  r  r  r  r	  r  s
             r  parse_liquidationzbitfinex.parse_liquidation  s   & A%%eQ/	##E1-&&t'7'7q'AB	''?&&y,?	  +$$&&xzJ**95 --l;&&u-**95++G,>,>y%,PQ"Y/
&
 
 
	r  c                 6   | j                          | j                  |      }|d   st        | j                  dz         |d   | j	                  |      d}| j                  | j                  ||            }| j                  |d      }| j                  ||      S )a
  
        either adds or reduces margin in a swap position in order to set the margin to a specific value

        https://docs.bitfinex.com/reference/rest-auth-deriv-pos-collateral-set

        :param str symbol: unified market symbol of the market to set margin in
        :param float amount: the amount to set the margin to
        :param dict [params]: parameters specific to the exchange API endpoint
        :returns dict: A `margin structure <https://github.com/ccxt/ccxt/wiki/Manual#add-margin-structure>`
        rD   z& setMargin() only support swap marketsr7   )r  r  r   )	r  r   r)   r7   r  "privatePostAuthWDerivCollateralSetr  r  parse_margin_modification)r  r  r  r  r   r  r  r  s           r  
set_marginzbitfinex.set_margin  s     	V$f~tww)QQRRTl//7
 ::4;;wPV;WX x+--dF;;r  c                 >    |d   }|dk(  rdnd}||d   d dd d d |d d d
S )Nr   r   r  rK  r  r~  )
r  r  r  r  r  r  r  r  rF  rG  r  )r  r  r   marginStatusRawmarginStatuss        r  r  z"bitfinex.parse_margin_modification  sH     q' /1 4t8X&$"
 	
r  c                 ^   | j                          d| j                  |      gi}d}d}|"| j                  | j                  ||            }n:| j	                  |      }|d   |d<   | j                  | j                  ||            }| j                  |d      }d|i}| j                  ||      S )a  
        fetches information on an order made by the user

        https://docs.bitfinex.com/reference/rest-auth-retrieve-orders
        https://docs.bitfinex.com/reference/rest-auth-retrieve-orders-by-symbol

        :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>`
        r7   Nr  r   r  )r  r  r&  r  r   r'  r  r  )	r  r7   r  r  r  r   r  r`  r  s	            r  fetch_orderzbitfinex.fetch_order  s     	4((,-
 >224;;w3OPH[[(F &tGH88Wf9UVHN x+e$&11r  c                 r   | j                          | j                  |      }d| j                  |      i}	|3| j                  ||      }
|dk(  r|
nt	        j
                  |
      }
|
|	d<   | j                  |dd      }| j                  |d      }| j                  |d      }| j                  |dd	      }| j                  |d
d	      }| j                  |dd      }|||	d<   n1|/| j                  ||      |	d<   |dk(  r| j                  ||      |	d<   |xs |dk(  }|dk7  r|| j                  ||      |	d<   d}|r| j                  |d      }|r| j                  |d      }|dk7  r||	d<   |||	d<   | j                  |dd      }|||	d<   | j                  |g d      }| j                  | j                  |	|            }| j                  |d      }|dk7  r7|d   }|d   }t        | j                   dz   |d   z   dz   |z   d z   |z   d!z         | j#                  |d"g       }d#|i}| j%                  ||      S )$a  
        edit a trade order

        https://docs.bitfinex.com/reference/rest-auth-update-order

        :param str id: edit order id
        :param str symbol: unified symbol of the market to edit an order in
        :param str type: 'market' or 'limit'
        :param str side: 'buy' or 'sell'
        :param float amount: how much you want to trade in units of the base currency
        :param float [price]: the price at which the order is to be fulfilled, in units of the quote currency, ignored in market orders
        :param dict [params]: extra parameters specific to the exchange API endpoint
        :param float [params.triggerPrice]: the price that triggers a trigger order
        :param boolean [params.postOnly]: set to True if you want to make a post only order
        :param boolean [params.reduceOnly]: indicates that the order is to reduce the size of a position
        :param int [params.flags]: additional order parameters: 4096(Post Only), 1024(Reduce Only), 16384(OCO), 64(Hidden), 512(Close), 524288(No Var Rates)
        :param int [params.leverage]: leverage for a derivative order, supported by derivative symbol orders only, the value should be between 1 and 100 inclusive
        :param int [params.clientOrderId]: a unique client order id for the order
        :param float [params.trailingAmount]: *swap only* the quote amount to trail away from the current market price
        :returns dict: an `order structure <https://docs.ccxt.com/#/?id=order-structure>`
        r7   r  r  r  r  r  r  r  Fr  r  r  r  r  r   r  r  r   r   r  r  r  r  lev)r  r  r  r  r  r  r  r  r  rL  r  r  r  r  r  r  r  r  )r  r   r  r  r2   r  r  r  r  safe_integer_2r  r  r!  privatePostAuthWOrderUpdater  r    r7   r  r  )r  r7   r  r  rb  r  r  r  r   r  r  r  r  r  r  r  r  r  r  r  r  r  r  r  r`  r  s                             r  
edit_orderzbitfinex.edit_order]  s   , 	V$$''+
 33FFCL,0EM<@R@RS_@`L ,GH))&+~N))&2BC&&v}=vz5A^^FL%@
++FE?K%(6G$%%#66v|LGGw-1-D-DVU-S)*!:kT&9H<#7#66vuEGGHHUD)EHHUD)EA:$GG$*GEN&&vz5A%GEN6  $Y  Z33DKK4PQ\ !!(A.Y I I# ;d BY NQU UXa adg ghhxB/e$&11r  r  )f__name__
__module____qualname__r   r  r  r  r  r  r  r  r   r   r  r   r  r   r1  r  floatr   r   dictr   r>  r   rI  r:  r
   r   rd  r   r  r   r   r  r  r   r  r  r  r  r  r  r  r  r   r  r   r   r   r  r   r   r  r  r  r  r!  r$  r  r#  r-  r1  r	   r5  r4  rF  r   rW  r   rc  rh  r   r   rx  r  rW  r  r  r  r   r  r  r   r  r  r   r  r  r  r  r  r  r  r  r   r  r  r  r  __classcell__)r  s   @r  r4   r4       sM   K# KZ-SxM #% 
. $& {$v, {z ') HZ HT $& ')( ')R [] ACS AC% ACc ACc ACan ACF)
t )
x )
= )
V:C :C :, :>b *s *3 *Y *Xh4 h h6 hT 04B :4W :47 :4x 02 13 1f 1$O Ov O Ob 6:UW .B3 .Bs .B# .B\`af\g .B` 26DWZce *L# *Lc *LQT *Ljnosjt *LX
 
4 
(9 9&8>: :v : :x os{} L,3 L,i L,y L,Z_ L,hk L,\ gksu R23 R2i R2y R2RW R2`c R2h @B 9*D$6 9*v /32 - -* 37r !2s !2C !2F 04B K5 K5Z 7;2 3  * 9=R S # * /3TXac @C @C3 @Cc @Chlmrhs @CD 154VZce LC# LCS LCPS LCjnotju LC\ 9=4^bkm CS C# CS CX[ C: -1tRV_a  Cc  C  CC  CD 8: N3 Nn N  79 9
# 9
^ 9
v:s : C
T C
X C
Q\ C
J )+ l{ l\ 6:[_hj 7Is 7I# 7IUX 7Iost  pA 7Ir DHPR P:S P:% P:# P:Wb P:d 26b 2<w 2<T(^ 2<hDt DV DL# &eBSW P20C $.t .x .; .` (,$TZ\ 4H 4HC 4Hs 4Haefqar 4Hl 6:" 0;7 0; 0;d 8<$]ajl G GC GWZ GR3
6 3
[ 3
j0
6 0
d 7;2 1<G 1<f 79 /4# /4b BFTXgktv ;Q# ;Qc ;Qad ;QzFF FP <@d[] /G /GS /G /Gb$V $L =? < <e <CU <<
>P 
2 26b @2c @23 @2D `drv  @B r2S r2# r2Y r2i r2Y\ r2lo r2r  r4   )9ccxt.base.exchanger   ccxt.abstract.bitfinexr   r  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   r   r   typingr   ccxt.base.errorsr    r!   r"   r#   r$   r%   r&   r'   r(   r)   r*   r+   r,   r-   ccxt.base.decimal_to_precisionr.   r/   r0   r1   ccxt.base.preciser2   r4   r  r  r  <module>r)     s    ( .  m  m  m  m  m  m  m  * 0 - . ' & . ) * ) . 1 * ) 0 3 9 = %o:2x o:2r  