
    ei                       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          Z8dS )    )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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ddd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ddd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#ddd 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de
e'         f
d'Z(dddede'fd(Z)defd)Z*d* Z+d+ Z,ddd,edede-fd-Z.di fded.e/d/e0ded0e1f
d1Z2di fded.e/d/e0ded0e1f
d2Z3i fd3e
e4         fd4Z5di fdefd5Z6di fd6edefd7Z7di fd8e
e         defd9Z8di fd6edefd:Z9d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@Z@i fdede?fdAZAdefdBZBdddCededeCfdDZDi fdeEfdEZFdddi fded"edede
eC         fdFZGdi fdededGedHedeCf
dIZHdi fde de
eI         fdJZJdddKedefdLZKdM ZLdNdOi ddfdPZMdQ ZNd.efdRZOdddSededePfdTZQdddi fded"edede
eP         fdUZRdi fde deSfdVZTdddi fded"edefdWZUdddedeVfdXZWdddefdYZXdi fde fdZZYi fdefd[ZZd$ddi fded"edefd\Z[dddefd]Z\ddi fded"edefd^Z]dddefd_Z^i fdedede_fd`Z`ddde_fdaZadi fd6edefdbZbddi fd6eded.e/d/e0de1d0e1fdcZc xZdS )ebitfinexreturnc                    |                      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d8d
d9d: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[d
d\d
d]dd^d d_d:d`d
dad
dbd
dcd
d
dd
d
d
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|                     d          |                     d	          |                     d
          |                     d	          g|                     d          |                     d	          g|                     d          |                     d	          g|                     d          |                     d	          g|                     d          |                     d	          g|                     d          |                     d	          g|                     d          |                     d          g|                     d          |                     d          g|                     d          |                     d          g|                     d          |                     d          g|                     d          |                     d          gg|                     d
          |                     d          g|                     d          |                     d          g|                     d          |                     d          g|                     d          |                     d          g|                     d          |                     d          g|                     d          |                     d
          g|                     d          |                     d
          g|                     d          |                     d
          g|                     d          |                     d
          g|                     d          |                     d
          g|                     d          |                     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fetchAllGreeksfetchBalancefetchBorrowInterestfetchBorrowRatefetchBorrowRateHistoriesfetchBorrowRateHistoryfetchBorrowRatesfetchBorrowRatesPerSymbolfetchClosedOrderfetchClosedOrdersfetchCrossBorrowRatefetchCrossBorrowRatesfetchCurrenciesfetchDepositAddressfetchDepositAddressesfetchDepositAddressesByNetworkfetchDepositsWithdrawalsfetchFundingHistoryfetchFundingRateemulatedfetchFundingRateHistoryfetchFundingRatesfetchGreeksfetchIndexOHLCVfetchIsolatedBorrowRatefetchIsolatedBorrowRatesfetchLedgerfetchLeveragefetchLeverageTiersfetchLiquidationsfetchMarginModefetchMarketLeverageTiersfetchMarkOHLCVfetchMyTrades
fetchOHLCVfetchOpenInterestfetchOpenInterestHistoryfetchOpenInterestsfetchOpenOrderfetchOpenOrdersfetchOptionfetchOptionChain
fetchOrderfetchOrderBookfetchOrderBooksfetchOrderTradesfetchPositionfetchPositionModefetchPositionsfetchPremiumIndexOHLCVfetchStatusfetchTickers	fetchTimefetchTradingFeefetchTradingFeesfetchTransactionFeesfetchTransactionsfetchVolatilityHistory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   createOrdersr{   r   r   fetchOrdersrc   r|   extendsdefault)linearinverse)r0  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    K/var/www/html/volatility/venv/lib/python3.11/site-packages/ccxt/bitfinex.pyr  zbitfinex.describe"   s\   h 5 5 > > @ @ OC
*OC
JOC
 $OC
 t	OC

 OC
 4OC
  ]]] $] 	]
 %] %] U] $U] '] "4] t] ] '] #D] $T]  t!]" &t#] ]$ (%]& '']( ()]* "4+], ,T-]. -e/]0 %d1]2 T3]4 !%5]6 7]8 &u9]: "5;]< +E=]> )%?]@ #EA]B ,UC]D #DE] ] ]F $TG]H 'I]J (K]L "4M]N &tO]P (Q]R 1%S]T +DU]V &uW]X #JY]Z *4[]\ $T]]^ u_]` "5a]b *5c]d +Ee]f tg] ] ]h  i]j %ek]l $Tm]n "5o]p +Eq]r !%s]t  u]v dw]x $Ty]z +D{]| %d}]~ !$]@ "4A]B uC]D #EE]F dG]H !$I] ] ]J "5K]L #DM]N  O]P $UQ]R !$S]T )%U]V tW]X Y]Z U[]\ "5]]^ #D_]` 'a]b $Zc]d )%e]f g]h #Ei]j &uk] ]l  %!!&#(  y] ] ]OC
L  MOC
l mOC
n i4<9 
 28F 8 oOC
J ?'?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 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 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 K 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 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 KN 03-0,.,/UK K KMOU UKOC
v $"&!%!..w77!..w77 "..s33T5F5Fw5O5OP!..x88$:K:KG:T:TU!..y994;L;LW;U;UV!..y994;L;LW;U;UV!..y994;L;LW;U;UV!..y994;L;LW;U;UV!..z::D<M<Mh<W<WX!..z::D<M<Mh<W<WX!..z::D<M<Mh<W<WX!..z::D<M<Mh<W<WX!..z::D<M<Mg<V<VW" "..s33T5F5Fw5O5OP!..x88$:K:KH:U:UV!..y994;L;LX;V;VW!..y994;L;LX;V;VW!..y994;L;LX;V;VW!..y994;L;LS;Q;QR!..z::D<M<Mc<R<RS!..z::D<M<Mc<R<RS!..z::D<M<Mc<R<RS!..z::D<M<Mc<R<RS!..z::D<M<Mc<R<RS" " "H I' 'wOC
F
 /G
OC
H
 !
 ''/$&-%- %,+2$+" "( 0- 
 !      ' *(&#+&$% % !% %%'')(&,*+**** "  !CD DI
OC
R $&*(,,0,1)-+/6:#'#'"&#(	( ( #($($(27+//4#()$ $. r% ',!%$(%+*/& & ',#($)*/	# # ',!%#($)*/( ( $(&+!%$(,0%+#($)*/	* 	*  #u= =~ y
 "9  $	  ## QL LSOC
l .-'0)*/C	 	 2C3D'4'0	  mOC
P  &!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&! &! &!QOC
 O O O	    c                      || j         d         v S )Nr  )r   r  codes     r  is_fiatzbitfinex.is_fiat4  s    t|F++,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_name7  sE    4<000<06647S=4/2QQRRRr  c                     |                      |          }|                     |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=  sE     !!&))((4<;OP[;\]e;fhvwwwr  c                     |                      |          }|                     |t          | j        |         d         d         | 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_precisionD  s`    !!&))))%V8L[8YZa8bdhdvww
 ((!^LLLr  c                     |                      |          }|                     |d          }|                     ddd||          ddd|dS )aW  
        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_statusM  se     //77$$Xq11	&&]'F'F	S\]]
 
 	
r  c                 t   |                      |          }|                     |          }|                     |          }|||g\  }}}|                     |dg           }|                     |dg           }|                     ||          }|                     |dg           }g }	t          dt          |                    D ]s}
||
         }|                     |d          }|                     |di           }d}|	                    d          dk    rd}| }d}d}|	                    d          dk    r&|
                    d          }|d         }|d         }n|dd         }|dd	         }|                     |          }|                     |          }|
                    d          }|
                    d          }|                     |d          }|                     |d          }|d
z   |z   }d}d}|r|}|}|dz   |z   }|                     |d          }|                     |d          }d}|r|                     ||          rd}|	                    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|                     d          ndddddt!          d          t!          d           d!ddd"|                     |          |                     |          d"|                     d#          dd"ddd"d$d|d%
           u|	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contractr1  r  85)r  r  minr#  z1e-8)r  r  r  cost)
r2  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  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_marketsd  sv    "&!>!>v!F!F$($H$H$P$P!>>vFF:PRkm}9~6+Y..!R@@!^^,>2FF##O5GHHOOIq"55	( q#g,,'' U	 U	A1:D''a00B__T1b11FDwwt}}!!8DFGwws||q  q(AaCQqS'**622D++G44E

4((IT**J##Iq11D$$Z33ECZ%'F FH / #.!%!1!1&!!<!<!%!1!1&!!<!<F b)44 MM 0cBh0&0 0 	0
 &0 &0 70 H0 $2F0 0 &0 0 %0 %0 $0  D!0" $0$$D#0$ %)255d:> H 1 1# 6 6 6D"&"!#hh XX   $#! !
  $001CDD#001CDD 
  $0088# 
  $#  $  _0 0 0 0 0 0 0b r  c                 	   g d}d                     |          }d|i}|                     |                     ||                    }|                     |                     |dg           d          |                     |                     |dg           d          |                     |                     |dg           d          |                     |                     |dg           d          |                     |                     |d	g           d          |                     |                     |d
g           d          |                     |                     |dg           d          |                     |dg           |                     |                     |dg           d          d	}i }t          dt          |d                             D ]}|d         |         }	|                     |	d          }
|                     |	d          }|                     |d          }|                     ||g           }|                    |
           |||<   |                     |dg           }i }t          dt          |                    D ]L}||         }|	                    d          r!| 
                    |          }|                     |d         |g           }|                     |d          }|                     |d         |g           }|                     |d          }|dup	||d         v }d}|rd}|                     |d         |g           }|                     |dg           }|                     |d          }|                     |d         |g           }d}|                     |d         |g           }|                     |d          dk    }|                     |d          dk    }i } |                     ||g           }!t          dt          |!                    D ]E}"|!|"         }
|                     |
          }#|
|
                                |
dddddddddid	| |#<   F|                     |||||||g||d|||t!          |          |                     |                     |                    dd|ddd| d          ||<   N|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  r7   networkr  depositr   feer  r  T)r  r   )r7   r  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  
dwStatusesdepositEnabledwithdrawEnabledr  	netwokIdsjr  s$                                       r  fetch_currencieszbitfinex.fetch_currencies  s"   
 
 
 &!!f
 ++DKK,H,HIIj ==!R!@!@!DD]]4>>(Ar#B#BAFFMM$..1b"A"A1EEMM$..1b"A"A1EEMM$..1b"A"A1EEdnnXq"&E&EqIIMM$..1b"A"A1EExB77dnnXq"&E&EqII

 

 !#q#gj12233 	8 	8A ,Q/J((Q77I
A66J**:q99K>>/;KKL	***+7OK((nnXq"--q#c((## A	 A	AQB{{4   **2..DNN77#3R<<E##E1--D>>'&/2r::D&&tQ//G#4/OR7:;N5NLD  wvB??I>>)Q33D""4++C>>'&/2r::DI
(;RDDJ!..z1==BN"//
A>>!COHB??I1c)nn--  %aL	11)<<%#//++("# $!%"#'#'% %% %!!   77UD)T:)+ ^^  $001E1Ei1P1PQQ# 
  ##! !	 	 %+9 9  F4LL. r  c                    |                                   |                     | j        di           }|                     |dd          }|                     |||          }|Nt	          |                                          }t          | j        dz   d                    |          z             |dk    }| 	                    |d          }| 
                    |          }d|i}	t          d	t          |                    D ]}
||
         }|                                 }|                     |d
          }|dk    r||d<   |                     |d	          }|                     |dd          }t          |          dz
  }||d         dk    }| p|}||k    rN|rL|                     |          }|                     |d          |d<   |                     |d          |d<   ||	|<   |                     |	          S )a_  
        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N((DD&&~}mTT++--..D*Z Z]a]f]fgk]l]l lmmm$5		&&))//66)q#h--(( 	' 	'AqkGllnnG''33H3"*##GQ//D//B??J
OOa'E)%&&1T9'3#3#G7Gt##)<#..z::#'#3#3GQ#?#? "&"2"27A">">&t  (((r  r  r  fromAccount	toAccountc                 .   |                                   |                     | j        di           }|                     ||          }|Nt	          |                                          }t          | j        dz   d                    |          z             |                     ||          }	|	Nt	          |                                          }t          | j        dz   d                    |          z             | 	                    |          }
| 
                    |
|          }| 
                    |
|          }|                     ||          }|||||	d}|                     |                     ||                    }|                     |d          }|dk    r^|                     |d	d
          }|                     | j        d         || j        dz   |z              t!          | j        dz   |z             |                     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  Nz' transfer() fromAccount must be one of r  z% transfer() toAccount must be one of )r  currencycurrency_tofromtor   errorr  r  r;  r  r  )r  r  r   r  r  r  r#   r7   r  r4  convert_derivatives_idcurrency_to_precisionprivatePostAuthWTransferr  throw_exactly_matched_exceptionr3  r    parse_transfer)r  r  r  r1  r2  r  r%  fromIdr  toIdr4  fromCurrencyIdtoCurrencyIdrequestedAmountr  r  r8  messages                     r  r   zbitfinex.transfer  s    	7I2NN!!.+>>>++--..D#DG.W$WZ^ZcZcdhZiZi$ijjj	::<++--..D#DG.U$UX\XaXabfXgXg$ghhh==&&44X{KK228YGG44T6BB &&'
 
 00Wf1M1MNN,   1--G&&xB77G001I7TXT[^aTadkTklll# 7888""Hh#7BBBr  Nr   r4  c           
         |                      |d          }|                     |d          }|                     |d          }|                     |d          }|                     |d          }|                     |d          }|                     |d          }	d ||                     |          |                     |	          |                     |d          |                     ||          |||d		S )
Nr  r   r  r   r  r  r  r  )	r7   	timestampdatetimer  r  r4  r1  r2  r  )r  r  r  r  iso8601parse_transfer_statusr  r  )
r  r   r4  r  rE  r  r1  r2  r,  r  s
             r  r=  zbitfinex.parse_transfer  s    0 (33%%fa00	vq))&&tQ//$$T1--	%%dA..
!!&!,,"Y//0088&&tQ////
HEE&"

 

 
	
r  r  c                 <    dddd}|                      |||          S )Nr  failed)SUCCESSERRORFAILUREr  r  r  r  s      r  rH  zbitfinex.parse_transfer_status@  s1    
 

 &&999r  c                 Z   |                      |d          }|                     |d          }|                      |dg           }d }|dk    r?|                     |d|          }t          |          dz
  }||d          dk    }|s|dz   }n |dk    r|                     |d|          }n|}|S )	Nr  r   r  r   r  r  rC   r   )r  r  r  )	r  r4  r  r  
transferId
underlyingr,  r-  r.  s	            r  r9  zbitfinex.convert_derivatives_idH  s     x00%%dA..
__T1b11

=  ))*aDDJ
OOa'E)%&&1T9# /'$.
X))*aDDJJ#Jr  r  r   c                 z   |                                   |                     | j        dd          }|                     |          }|d         |d}|||d<   |                     ||          }|                     |          }|                                 }	|d         g g |	|                     |	          dd}
|d         dk    rd	nd
}t          d
t          |                    D ]}||         }| 
                    ||          }|                     |d          }t          j        |          }t          j        |d          rdnd}|
|         }|                    ||                     |          g           |                     |
d         d
d          |
d<   |                     |
d         d
          |
d<   |
S )aT  
        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asksrE  rF  noncer   r   r  r   rT  rU  T)r  r  r   r   r  publicGetBookSymbolPrecisionmillisecondsrG  r  r  r  r  r2   
string_abs	string_gtr  r  sort_by)r  r  r   r  r  r   r  fullRequest	orderbookrE  r  
priceIndexr  orderr  signedAmountr  side
resultSides                      r  fetch_order_bookzbitfinex.fetch_order_book^  s    	OODL+tDD	V$$Tl"
 
 "GENkk'62255kBB	%%''	X&"Y//
 
 '{3t;;QQ!
q#i..)) 	B 	BAaLE$$UJ77E++E155L'55F$.|SAAM66vDJud&7&7&?&?@AAAAfVna>>vfVna88vr  tickerr   c                    t          |          }|dk    p|dk    }d }d}d}|r	d}|dk    }n2|                     |d          }|                     ||          }|dk    }|                     d |          }d }	d }
d }d }d }d }d }d }|r|                     |d|z
            }	|                     |d|z
            }
|                     |d|z
            }|                     |d	|z
            }|                     |d
|z
            }|                     |d|z
            }|                     |d|z
            }|                     |d|z
            }n|                     |d|z
            }	|                     |d|z
            }
|                     |d|z
            }|                     |d|z
            }|                     |d|z
            }t	          j        |d          }|                     |d	|z
            }|                     |d
|z
            }|                     |d|z
            }|                     i d|dd dd d|d|d|
dd d|dd dd dd d|	d|	dd d |d!|d"d |d |d#|          S )$Nr   r   r   Fr      r  r  r   r           r  r  r  100r  rE  rF  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  rd  r   lengthisFetchTickerr  
minusIndexisFundingCurrencymarketIdrt  rm  ro  rv  r   volumerk  rl  s                    r  parse_tickerzbitfinex.parse_ticker  so   R V286R<
! 	/J!'2''22H%%h77F!'2!!$//
 	<##FBO<<D""61z>::C""61z>::C%%fa*n==F))&!j.AAJ%%fb:o>>F##FBO<<D""62
?;;CC ##FA
N;;D""61z>::C""61z>::C%%fa*n==F))&!j.A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                 @   |                                   |                     |          }i }|.|                     |          }d                    |          |d<   nd|d<   |                     |                     ||                    }|                     ||          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>`
        Nr  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(DEEP !!'7333r  c                     |                                   |                     |          }d|d         i}|                     |                     ||                    }|                     ||          S )a  
        fetches a price ticker, a statistical calculation with the information calculated over the past 24 hours for a specific market

        https://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  rd  s         r  fetch_tickerzbitfinex.fetch_ticker0  sp     	V$$fTl
 ++DKK,H,HII  000r  tradec                    |                      |dg           }t          |          }|dk    }|                     |d          }|rdnd}d }|                     ||          }	|rdnd}
|                     ||
          }|	d         dk    rd}t          j        |	          }	nd	}d }d }d }d }|                     d |          }|rdnd
}|                     ||          }|r|d
         }|                     |          }|                     |d          }|                     |d          }|d
k    rdnd}|                     |d          }t          j        |          }|                     |d          }|                     |          }||d}|d         }|                     | j	        d         |          }| 
                    |||                     |          |||||||	d ||d|          S )Nr  r  r   r  r  r  -sellbuyr   r   r   r   r  r   )r  r4  r  r	  )r7   rE  rF  r  r_  ra  r  takerOrMakerr  r  r  r  r  )r  r  r  r2   rY  r  r  
string_negr  r   
safe_traderG  )r  r  r   	tradeListtradeLength	isPrivater7   amountIndexra  amountStringr^  priceStringorderIdr  r  r  r  timestampIndexrE  r  r   feeCostStringfeeCurrencyIdfeeCurrency	orderTypes                            r  parse_tradezbitfinex.parse_tradeB  sB   8 NN5(B77	)nn 1_	i++$+aa!''	;??#*QQ
&&y*==?c!!D"-l;;LLD!!$//'.Q%%i@@	 	N |H%%h//F&&y!44G%%i33E',zz77L ,,Y::M#.}==M ,,Y;;M11-@@K%' C "!I##DL$A9MMD"Y//( " 
  
   	r  sincec                    |                                   d}|                     |dd          \  }}|r|                     d||||d          S |                     |          }d}d|d         i}|||d	<   d
}|t	          |d          |d<   ||d<   |                     d||          \  }}|                     |                     ||                    }	|                     |	d          }
g }t          dt          |
                    D ]}|                    d|
|         i            |                     ||d|          S )au  
        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  sq    	88PZ[[& 	i44]FESXZ`bghhhV$$fTl
 $GGD"5%00GG225'6JJ11$++gv2N2NOO h**
q#f++&& 	5 	5Ax34444  VT5AAAr  r   d   	timeframec           	         |                                   d}|                     |dd          \  }}|r|                     d|||||d          S |                     |          }|d}nt	          |d          }|d         |                     | j        ||          d|d}|||d	<   |                     d
||          \  }}|                     | 	                    ||                    }	| 
                    |	||||          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)
        Fr|   r  r+  Nr7   r   )r  r  r  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Z& 	y::<QVX]_hjprwxxxV$$=EEu%%ETl))$/9iPP	
 
 $GG225'6JJ@@WV\A]A]^^   69eUKKKr  c           	         |                      |d          |                     |d          |                     |d          |                     |d          |                     |d          |                     |d          gS )Nr   r   r  r  r  r  )r  r  )r  ohlcvr   s      r  parse_ohlcvzbitfinex.parse_ohlcv  s     eQ''UA&&UA&&UA&&UA&&UA&&
 	
r  c                     ||S |                     d          }|                     |d          }ddddddddddd
}|                     |||          S )Nr  r   rr  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  sv    >MS!!  ** "&!+"#&#-
 
 %888r  c                 D    dgdgddgd}|                      ||d           S )N
reduceOnlypostOnly)102440965120)r  )r  flags
flagValuess      r  parse_order_flagszbitfinex.parse_order_flags  s:     "NL!:.
 

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

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

 Y// 
 !$ 
 f 
 D 
 ; 
  
 D 
 U 
 L 
 f 
 D 
  w! 
" d# 
$ #+ 
  
  
, -  	r  r  ra  r  c                    |                      |          }|                     ||          }|dk    r|nt          j        |          }|d         |d}	|                     |dd          }
|                     |d          }|                     |d          }|                     |dd	          }|                     |d
d	          }|                     |dd          }|                                }|d}||	d<   n?|
=| 	                    ||
          |	d<   |dk    rd}| 	                    ||          |	d<   nd}|dk    }|dk    }|p|dk    }|s|r|t          | j        dz             |s|r|dk    rt          | j        dz             |dk    r|
| 	                    ||          |	d<   |rd}n|rd}d}|                     d|          \  }}|d         r|d|z   }||	d<   d}|r|                     |d           }|r|                     |d!          }|dk    r||	d"<   |||	d<   |                     |g d#          }|                     |	|          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  ra  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  s   * V$$//??(,||G<N|<\<\Tl"
 
 ))&+~NN))&2BCC&&v}==vz5AA^^FL%@@
))&%IIJJLL	%'I(6G$%%%#66v|LLGGw(	-1-D-DVU-S-S)**"	e#e#!:kT&9 	m3 	mU]tw)kklll 	d3 	dTX--tw)bbcccH<#7#66vuEEGG 	II 	I
!??vVV
F&> 	0z1#i/I# 	*HHUD))E 	*HHUD))EA::$GG$*GEN6  $M  $M  $M  N  N{{7F+++r  c                    |                                   |                     |          }|                     ||||||          }|                     |          }	|                     |	d          }
|
dk    r?|	d         }|	d         }t          | j        dz   |	d         z   dz   |z   dz   |z   dz             |                     |	d	g           }|                     |d
          }d|i}|                     ||          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  rK  r  r  r  : (#)r  r   r  )	r  r   r  privatePostAuthWOrderSubmitr  r    r7   r  r  )r  r  r  ra  r  r  r  r   r  r  r  	errorCode	errorTextordersr_  newOrders                   r  create_orderzbitfinex.create_order  s   . 	V$$++FD$vVV33G<<` !!(A..Y I I# ;d BY NQU UXa adg ghhh!R00vq))e$&111r  r  c           	         |                                   g }t          dt          |                    D ]}||         }|                     |d          }|                     |d          }|                     |d          }|                     |d          }	|                     |d          }
|                     |di           }|                     ||||	|
|          }|                    d|g           d	|i}|                     |          }g }| 	                    |d
g           }t          dt          |                    D ]/}||         }|d
         }|                    d|d         i           0| 
                    |          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  ra  r  r  r  onopsr  r  )r  r  r  r  r  	safe_dictr  r  privatePostAuthWOrderMultir  parse_orders)r  r  r  ordersRequestsr  rawOrderr  r  ra  r  r  orderParamsorderRequestr  r  resultsdataentryindividualOrders                      r  create_orderszbitfinex.create_orders
  s    	q#f++&& 		8 		8AayH%%h99F##Hf55D##Hf55D%%h99F$$Xw77E..8R@@K44VT4QVXcddL!!4"67777>
 227;;4 ~~h2..q#d))$$ 	; 	;AGE#AhONNHoa&89::::  )))r  c                 Z   |                                   ddi}|                     |                     ||                    }|                     |dg           }g }t	          dt          |                    D ]}|                    d||         i            |                     |          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Wf9U9UVV!R00
q#f++&& 	5 	5Ax34444  ,,,r  r7   c                     |                                   |                     |dd          }d}d}||                     |          }|M|                     |d          }|t	          | j        dz             ||d}|                     |ddg          }ndt          |          i}|                     | 	                    ||                    }|                     |d          }	d	|	i}
| 
                    |
|          S )
aw  
        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88G"47  .L  $L  M  M  M# G YYv'?@@FF c"ggG 33DKK4P4PQQ!,,e$&111r  r  c                 .   |                                   g }t          dt          |                    D ]0}|                    |                     ||                              1d|i}d}||                     |          }|                     |                     ||                    }|                     |dg           }	g }
t          dt          |	                    D ]}|
                    d|	|         i            | 	                    |
|          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  r  parse_to_numericr   r  r  r  r  )r  r  r  r  
numericIdsr  r  r   r  r  r  s              r  cancel_orderszbitfinex.cancel_orders}  s     	
q#c((## 	= 	=Ad33CF;;<<<<*
 [[((F88Wf9U9UVVf !R00
q#f++&& 	5 	5Ax34444  V444r  c           	          dt          |          gi}|                     |dd|                     ||                    }|                     |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  s~     3r77)
 ''dDKKQW<X<XYY**=) 3b 8< GHHHr  c           	          dt          |          gi}|                     |dd|                     ||                    }|                     |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  s~     3r77)
 ))&$dkk'SY>Z>Z[[**=) 3b 8< GHHHr  c                    |                                   i }d}d}|*|                     |                     ||                    }nI|                     |          }|d         |d<   |                     |                     ||                    }g }t          dt          |                    D ]}	|                    d||	         i            |                     ||||          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3O3OPPHH[[((F &tGH88Wf9U9UVVHN 
q#h--(( 	7 	7Ax!56666  VUEBBBr  c                    |                                   d}|                     |dd          \  }}|r|                     d||||          S i }|||d<   |||d<   |                     d||          \  }}d}d}|*|                     |                     ||                    }nI|                     |          }|d         |d	<   |                     |                     ||                    }g }	t          d
t          |                    D ]}
|	
                    d||
         i            |                     |	|||          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>`
        Frc   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_orders8  sv     	88ATV`aa& 	h445H&RWY^`fggg$GG$GG225'6JJ>66t{{7F7S7STTHH[[((F &tGH<<T[[RX=Y=YZZHN 
q#h--(( 	7 	7Ax!56666  VUEBBBr  c                    |t          | j        dz             |                                  |                     |          }t	          |          }||d         d}|                     |                     ||                    }	g }
t          dt          |	                    D ]}|
	                    d|	|         i            | 
                    |
|||          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>`
        Nz. 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     >#DG.^$^___V$$b''Tl
 

 ;;DKKQW<X<XYY
q#h--(( 	7 	7Ax!56666  VUEBBBr  c                    |                                   d}d|                                 i}|||d<   |||d<   d}|J|                     |          }|d         |d<   |                     |                     ||                    }n)|                     |                     ||                    }g }t          dt          |                    D ]}	|                    d||	         i            | 	                    ||||          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  rX  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=YZZHH66t{{7F7S7STTH
q#h--(( 	7 	7Ax!56666  VUEBBBr  c                     |                                   ddi}|                     ||                     ||                    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  sH     	
 ))$GV0L0LMMMr  c                    |                                   |                     |          }|                     |d|          }|                     |di           }|                     ||          }|                     |d          }|t	          | j        dz   |z   dz             |                     |dd          }|                     |dd          }||d	d
}	|                     |                     |	|                    }
|                     |
dg           }|                     |d          }||                     |d          n|}|dn|                     |d          }| 	                    |           |||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  )r4  addresstagr  r  )
r  r4  r  r  r#   r7   r   privatePostAuthWDepositAddressr  check_address)r  r  r  r4  r  currencyNetworkscurrencyNetworkr  r8  r  r  r  poolAddressr:  r;  s                  r  r4  zbitfinex.fetch_deposit_address  s    	==&&""69d;;??8ZDD//*:GDD$$_d;;	#DG.e$ehl$l  pv  %v  w  w  w!!&(J??69h77
 

 66t{{7F7S7STT( 1b11&&vq112=2E$""61---K"*dd1A1A&!1L1L7###
 
 	
r  c                 L    dddddddddddd}|                      |||          S )Nr  rJ  r  pending)rK  	COMPLETEDrL  rM  r  zPENDING APPROVALPENDINGzPENDING REVIEWzPENDING CANCELLATIONSENDINGzUSER APPROVEDrN  rO  s      r  parse_transaction_statusz!bitfinex.parse_transaction_status	  sI    " ) '$- &
 
 &&999r  transactionc                 .   t          |          }d }d }d }d }d }d }	d }
d }d }d }d }d }d }|dk    r|                     |dg           }|                     |d          }||d         }|                     |d          }|t	          j        |          }|                     |d          }|                     |d          }d}	|dk    rd }d}	|                     |d          }
d	}|                     |d
          }|                     |                                          }n}|dk    rv|                     |d          }|                     |d          }| 	                    ||          }|                     |d
          }|                     |          }|                     |d          }|                     |d          }| 
                    |                     |d                    }	|                     |d          }t	          j        |          }|t	          j        |d          rd	}nd}|                     |d          }|t	          j        |          }|                     |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(S ))Nr   r  r   r  r  r  rJ  r  
withdrawalr     r   r  r  rh  r   r  ri  r         r  r7   txidr  r4  r  r  r  rE  rF  r:  addressFrom	addressTor;  tagFromtagTor  )r4  r  rate)commentinternalr  )r  r  r  r  r2   rY  r  r  r  r  rF  r  r  rG  )r  rG  r4  transactionLengthrE  r  r  r  r7   r  r;  r  feeCostrM  rO  r  rS  r  r  r,  r`  s                        r  parse_transactionzbitfinex.parse_transaction 	  s   h  ,,		!!??;266D))+q99I#'&&tQ//G"!,W55%%dA..F""4++BFQww!""4++CD((q11I--ioo.?.?@@GG"$$!!+q11B))+q99J**:x@@D((a88I--i88G))+q99I''Q77G2243C3CKQR3S3STTF++K<<L'55F'$\377 %'DD$D&&{B77G"!,W55((b99I##K44D&&{B77G
K
"
 D
 D	

 
 w
 d''//
 f
 
 Y//
 y
 4
 
 3
 t
  S!
" w#
$  ))'22 )
 
 
 	
r  c                 0   |                                   |                     |          }i }|                     | j        di           }|                     |dg           }|                     |dg           }|                     |dg           }|                     |d          }|                     |d          }	|                     |d          }
|                     |d          }|                     |d          }|                     |d          }t          dt          | j                            D ]b}| j        |         }|                     |          }||ddd}|d	         |v r|	|d
<   ||d<   n|d         r|
|d
<   ||d<   n
||d
<   ||d<   |||<   c|S )aN  
        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7H t|VR88//(Ar22OOGQ33	OOGQ33	##Iq11''	155((A66##Iq11''	155((A66q#dl++,, 	! 	!A\!_F[[((F  "!	 C g$&&+G+G
# (,G,G'G'G F6NNr  c                 l   |                                   d}i }|||d<   |||d<   d}|J|                     |          }|d         |d<   |                     |                     ||                    }n)|                     |                     ||                    }|                     ||||          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   r7   r4  )r  r4  %privatePostAuthRMovementsCurrencyHistr  privatePostAuthRMovementsHistparse_transactions)r  r  r  r   r  r4  r  r  s           r  fetch_deposits_withdrawalsz#bitfinex.fetch_deposits_withdrawals
  s     	$GG$GG}}T**H"*4.GJAA$++gW]B^B^__HH99$++gv:V:VWWH: &&x5%HHHr  r:  r;  c                    |                      |           |                                  |                     |          }|                     |d|          }|                     |d          }|                     |di           }|                     ||          }	|                     |	d          }
|
t          | j        dz   |z   dz             |                     |dd          }|                     |dd          }|
||                     |          |d	}|||d
<   |                     | j	        di           }| 
                    |dd          }|rd|d<   |                     |                     ||                    }|                     |d          }|dk    rw| j        dz   |z   }|                     |dd          }|                     | j        d         ||           |                     | j        d         ||           t!          |          |                     |d          }|dk    r"|                     | j        d         ||           |                     ||          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   Nz* withdraw() could not find a network for 'r7  r8  r   )r9  r8  r  r:  
payment_idr   r   Fr   
fee_deductr   r8  r  r  r  r;  r<  r  success)r=  r  r4  r  r   r  r#   r7   number_to_stringr   r  privatePostAuthWWithdrawr  r<  r3  throw_broadly_matched_exceptionr    rW  )r  r  r  r:  r;  r  r4  r  r>  r?  r  r8  r  withdrawOptionsr   r  statusMessagefeedbackrC  texts                       r  r   zbitfinex.withdrawL
  s    	7###==&&""69d;;69--??8ZDD//*:GDD$$_d;;	#DG.Z$Z]a$a  ek  %k  l  l  l!!&(J??69h77++F33	
 
 ?$'GL!//$,
BGG^^O\5II
 	&$%GL!00Wf1M1MNN> ((155G##w}x/H&&xB77G001I7T\]]]001I7T\]]])))!,,9001I4QUVVV%%h999r  c                 (   |                                   |                     |          }|                     |          }g }t          dt	          |                    D ]}|                    d||         i            |                     ||          S )aj  
        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9F q#h--(( 	: 	:A  (HQK!89999##M7;;;r  positionc                 6   |                      |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t          j        |d          rdnddd d |d!| 	                    |          |                     |d"          |                     |d#          d |                     |d$          |                     t          j
        |	|                    d |                     |d%          d d d d&
          S )'Nr  r   r  rh  r  trade_pricetrade_amountr  r7   rg  r  notionalr  isolatedliquidationPricer   
entryPricer  unrealizedPnlr  r   r  	contractsr  	markPrice	lastPricera  r   longshortr  rE  rF  ri     rf  r  )
lastUpdateTimestampmaintenanceMarginmaintenanceMarginPercentage
collateralinitialMargininitialMarginPercentager  marginRatior  r  )r  r  r  safe_positionr  r  r  r2   rZ  rG  r{  )
r  ry  r   positionListr  r  rE  meta
tradePricetradeAmounts
             r  parse_positionzbitfinex.parse_position
  s   B ~~h99##L!44!!,22%%lB77	b11%%dM::
&&t^<<!! #
L#
$""<44#
 d&&x88#
 ))&11	#

 *#
  0 0q A A#
 $**<;;#
 T--lA>>#
 $**<;;#
 #
 D#
 #
 #
 g/<<IFF'#
 d#
  !#
" Y//##
$ $(#4#4\2#F#F!%!1!1,!C!C+/**<<<!..w/A+z/Z/Z[['+((q99!#7#
 #
 #
   	r  c                 *    |                                  S N)rX  )r  s    r  rV  zbitfinex.nonce  s      """r  r   GETc                    d|                      ||          z   }|                     ||                     |                    }|dk    r||z   }n
| j        |z   }| j        d         |         dz   |z   }	|dk    r|r|	d|                     |          z   z  }	|dk    r|                                  t          |                                           }
| 	                    |          }d|z   |
z   |z   }| 
                    |                     |          |                     | 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strrV  jsonhmacencodesecrethashlibsha384apiKey)r  pathr   r9  r  r  r  r  r)  r  rV  auth	signatures                r  signzbitfinex.sign  sZ   ++D&999		&$"5"5d";";<<$;;GmGGlW,Gis#c)G3(?? 3sT^^E2222)++---

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

isinstancer  r  r7   r<  r3  ro  r    r*   r  )r  
statusCode
statusTextr  r9  r  r  r  requestHeadersrequestBodyrC  rr  r  r  s                 r  handle_errorszbitfinex.handle_errors4  s   h-- :,,Xy'JJ7S=4/44T_W5MwX`aaa44T_W5MwX`aaa#DGcMD$8999: ^^*D DEEE#DGcMD$8999((1b99I((1b99Iw}y0H001I9V^___001I9V^___001I9V^___#	 9D @9 Ls RSSSr  c                    |d S |                     d          dk    s|                     d          dk    rdS |                     d          dk    rdS |                     d          dk    s|                     d          dk    rdS |                     d          dk    rdS |                     d	          dk    rd
S |                     d          dk    s|                     d          dk    rdS |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_typeL  s    <4YYu""dii	&:&:a&?&?5YYx  A%%8YYy!!Q&&$))L*A*AQ*F*F =YYz""a'':YYy!!Q&&8YYz""a''499Z+@+@A+E+E7Kr  itemc                    |                      |dg           }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  r7   	directionr"  referenceIdreferenceAccountr  r4  r  rE  rF  beforeafterr  r  )r  r  r  safe_currencyr  r  r  r#  r  safe_ledger_entryrG  )r  r  r4  itemListr  r7   r,  r  rE  r  r  descriptionr  firsts                 r  parse_ledger_entryzbitfinex.parse_ledger_entry^  sg     >>$"55h**%%h22
&&z8<<%%j(;;%%h22	!!(A..  1--&&x33"%%e,,E**5!44E//66D%% $"Y//'
 '
  !  	r  c                    |                                   d}|                     |dd          \  }}|r|                     d||||d          S d}i }|||d<   |||d<   |                     d||          \  }}d}|J|                     |          }|d	         |d
<   |                     |                     ||                    }n)|                     |                     ||                    }g }	t          dt          |                    D ]!}
||
         }|	
                    d|i           "|                     |	|||          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-entry-structure>`
        Frt   r  r%  Nr-  r   r  r7   r4  r   r  )r  r  r  r  r4  #privatePostAuthRLedgersCurrencyHistr  privatePostAuthRLedgersHistr  r  r  parse_ledger)r  r  r  r   r  r  r4  r  r  ledgerObjectsr  r  s               r  fetch_ledgerzbitfinex.fetch_ledger  s{    	88PZ[[& 	f44]D%QVX^`deee$GG$GG225'6JJ}}T**H"*4.GJ??GU[@\@\]]HH77GV8T8TUUH  q#h--(( 	3 	3AA;D  (D!12222  %GGGr  c                 2   |t          | j        dz             |                                  |                     |          }dd                    |          i}|                     |                     ||                    }|                     ||          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>`
        Nz0 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     ?#DG.`$`aaaOOG,,	CHHY''
 ,,T[[&-I-IJJ> ''':::r  c           	         |t          | j        dz             |                                  d}|                     |dd          \  }}|r|                     d|||d|d          S |                     |          }d|d	         i}|||d
<   |                     d||          \  }}|                     |                     ||                    }g }	t          dt          |                    D ]5}
||
         }|                     ||          }|	                    |           6g }|                     |	|||          }t          |          }t          d|          D ]'}
||
z
  dz
  }||         }|                    |           (|S )aP  
        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>`
        Nz5 fetchFundingRateHistory() requires a symbol argumentFrn   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    >#DG.e$efff88AZ\fgg& 	@::;TV\^cejlprxz~V$$fTl
 $GG225'6JJ66t{{7F7S7STT> q#h--(( 	 	A!B222v>>DLL44UFE5QQ(mmq+&& 	/ 	/A!Oa'E#E?L  ....r  c                    |                      |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 iS )Nr   r   r   r  r  r     
indexPricer  interestRateestimatedSettlePricerE  rF  fundingRaterh  fundingTimestampfundingDatetimenextFundingRater  nextFundingTimestampnextFundingDatetimepreviousFundingRatepreviousFundingTimestamppreviousFundingDatetimeinterval)r  r  r  r  rG  )r  r  r   r  rE  r  s         r  parse_funding_ratezbitfinex.parse_funding_rate?  s   : ##Ha00%%h22	#001==
H
d&&x88
 ))(B77
 $**8Q77	

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

 D
 #D
 
 Y//
 4++Hb99
 
 t
 t//!<<
 #$8
 "4<<0D#E#E
 "4
  '!
" &t#
 	
r  c                 4   |                                   |                     |          }dg}||                     |          }dd                    |          i}|                     |                     ||                    }|                     ||          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  Nr  r  )r  r  r  r  r  r  parse_open_interestsr  s         r  fetch_open_interestszbitfinex.fetch_open_interests  s     	%%g..G	00ICHHY''
 ,,T[[&-I-IJJ> ((7;;;r  c                    |                                   |                     |          }d|d         i}|                     |                     ||                    }|                     |d          }|                     ||          S )an  
        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  s     	V$$F4L
 ,,T[[&-I-IJJ> ^^Ha((''F333r  c           	         |                                   d}|                     |dd          \  }}|r|                     d|||d|d          S |                     |          }d|d         i}|||d	<   |||d
<   |                     d||          \  }}|                     |                     ||                    }	|                     |	|||          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   Nr-  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h& 	A::;UW]_dfkmqsy{  A  A  AV$$fTl
 $GG$GG225'6JJ66t{{7F7S7STT< 0065%PPPr  c           	      @   t          |          }|dk    rdnd}|                     |d          }|                     |d          }|                     |                     ||d d          |                     ||          d ||                     |          |d|          S )N   rf  r  r   r   rD   )r  openInterestAmountopenInterestValuerE  rF  r  )r  r  r  safe_open_interestr  r  rG  )r  r+  r   interestLengthopenInterestIndexrE  r  s          r  r  zbitfinex.parse_open_interestG  s    v X#1R#7#7BBb%%h22	##Ha00&&&&xvFF"&"2"28=N"O"O!%"Y//(
 (
   	r  c           	         |                                   d}|                     |dd          \  }}|r|                     d|||d|d          S |                     |          }i }|||d<   |||d<   |                     d	||          \  }}|                     |                     ||                    }|                     ||||          S )
aN  
        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>`
        Frw   r  r  r  Nr-  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a& 	y::;NPVX]_dfjlrtwxxxV$$$GG$GG225'6JJ11$++gv2N2NOO* &&xFFFr  c                    |d         }|                      |d          }|                     |d          }t          j        |                     |d                    }|                     |d          }t          j        ||          }|                     |d          }	|                      |d          }
|
dk    rd	nd
}|                     ||                     ||d d          |                     |          |                     |          |                     |	          ||                     |          |                     t          j        ||	                    ||                     |          d
          S )Nr   r  r  r  r  rg  r   r   r  r  r  )
r  r  r  r  r  ra  	baseValue
quoteValuerE  rF  )	r  r  r2   rY  r{  safe_liquidationr  r  rG  )r  liquidationr   r  rE  r  r  r  r	  r  sideFlagra  s               r  parse_liquidationzbitfinex.parse_liquidation  sl   & A%%eQ//	##E1--&t'7'7q'A'ABB	''??&y,??	  ++$$UA..!QuuV$$&&xzJJ**955 --l;;&&u--**955++G,>y%,P,PQQ"Y//&
 &
   	r  c                 x   |                                   |                     |          }|d         st          | j        dz             |d         |                     |          d}|                     |                     ||                    }|                     |d          }|                     ||          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~ 	Stw)QQRRRTl//77
 
 ::4;;wPV;W;WXX x++--dF;;;r  c                 L    |d         }|dk    rdnd}||d         d dd d d |d d d
S )Nr   r   r  rJ  r  r~  )
r  r  r  r  r  r  r  r  rE  rF   )r  r  r   marginStatusRawmarginStatuss        r  r  z"bitfinex.parse_margin_modification  sR     q' /1 4 4tt8X&$"
 
 	
r  c                    |                                   d|                     |          gi}d}d}|*|                     |                     ||                    }nI|                     |          }|d         |d<   |                     |                     ||                    }|                     |d          }d|i}|                     ||          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3O3OPPHH[[((F &tGH88Wf9U9UVVHN x++e$&111r  c                 8   |                                   |                     |          }d|                     |          i}	|7|                     ||          }
|dk    r|
nt	          j        |
          }
|
|	d<   |                     |dd          }|                     |d          }|                     |d          }|                     |d	d
          }|                     |dd
          }| 	                    |dd          }|||	d<   n:|8| 
                    ||          |	d<   |dk    r| 
                    ||          |	d<   |p|dk    }|dk    r|| 
                    ||          |	d<   d}|r|                     |d          }|r|                     |d          }|dk    r||	d<   |||	d<   | 	                    |dd          }|||	d<   |                     |g d          }|                     |                     |	|                    }|                     |d          }|dk    r?|d         }|d         }t          | j        dz   |d         z   d z   |z   d!z   |z   d"z             |                     |d#g           }d$|i}|                     ||          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   Nr  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  rK  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  ra  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_orderb  s	   , 	V$$$''++
 33FFCCL,0EMM<<@RS_@`@`L ,GH))&+~NN))&2BCC&&v}==vz5AA^^FL%@@
++FE?KK%(6G$%%%#66v|LLGGw-1-D-DVU-S-S)*!:kT&9H<#7#66vuEEGG 	*HHUD))E 	*HHUD))EA::$GG$*GEN&&vz5AA%GEN6  $Y  $Y  $Y  Z  Z33DKK4P4PQQ\ !!(A..Y I I# ;d BY NQU UXa adg ghhhxB//e$&111r  r  )e__name__
__module____qualname__r   r  r  r  r  r  r  r   r   r  r   r  r   r0  r  floatr   r   dictr   r=  r   rH  r9  r
   r   rc  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  rV  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       s       P# P P P P P Pd- - -S S Sx x xM M M #% 
 
 
 
. $& { {$v, { { { {z ') F FZ F F F FP $& ') ')( ') ') ') ')R [] AC ACS AC% ACc ACc ACan AC AC AC ACF)
 )
t )
x )
= )
 )
 )
 )
V:C :C : : : :  , :>b * *s *3 *Y * * * *Xh h4 h h6 h h h hT 04B :4 :4W :47 :4 :4 :4 :4x 02 1 13 1f 1 1 1 1$O O Ov O O O O Ob 6:UW .B .B3 .Bs .B# .B\`af\g .B .B .B .B` 9=4^ajl *L *L# *L# *LS *LX[ *Lquvzq{ *L *L *L *LX
 
 
4 
 
 
 
(9 9 9 9 9&8 8 8> > >: : :v : : : : :x os{} L, L,3 L,i L,y L,Z_ L,hk L, L, L, L,\ gksu R2 R23 R2i R2y R2RW R2`c R2 R2 R2 R2h @B 9* 9*D$6 9* 9* 9* 9*v /32 - - - - - -* 37r !2 !2s !2C !2 !2 !2 !2F ;?r M5 M5c M5C M5 M5 M5 M5^ 7;2  3     * 9=R  S #    * /3TXac @C @C @C3 @Cc @Chlmrhs @C @C @C @CD 154VZce LC LC# LCS LCPS LCjnotju LC LC LC LC\ 9=4^bkm C CS C# CS CX[ C C C C: -1tRV_a  C  Cc  C  CC  C  C  C  CD 8: N N3 Nn N N N N  79 9
 9
# 9
^ 9
 9
 9
 9
v:s : : : : C
 C
T C
X C
Q\ C
 C
 C
 C
J )+ l l{ l l l l\ 6:[_hj 7I 7Is 7I# 7IUX 7Iost  pA 7I 7I 7I 7Ir KOWY P: P:S P:% P:# P:C P:^i P: P: P: P:d 26b 2< 2<w 2<T(^ 2< 2< 2< 2<hD Dt DV D D D DL# # # &eBSW P P P P2  0C    $. .t .x .; . . . .` (,$TZ\ 4H 4H 4HC 4Hs 4Haefqar 4H 4H 4H 4Hl 6:" 0; 0;7 0; 0; 0; 0; 0;d 8<$]ajl G G GC GWZ G G G GR3
 3
6 3
[ 3
 3
 3
 3
j0
 0
6 0
 0
 0
 0
d 7;2 1< 1<G 1< 1< 1< 1<f 79 /4 /4# /4 /4 /4 /4b BFTXgktv ;Q ;Q# ;Qc ;Qad ;Q ;Q ;Q ;QzF FF F F F FP <@d[] /G /G /GS /G /G /G /G /Gb' 'V ' ' ' 'R =? < < <e <CU < < < <<
 
>P 
 
 
 
2 26b @2 @2c @23 @2 @2 @2 @2D `drv  @B r2 r2S r2# r2Y r2i r2Y\ r2lo r2 r2 r2 r2 r2 r2 r2 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  m  m  m  m  m  m  m  m  m  m  m  m  m  m  m  m  m  m  m  m  m  m  m  m  m  m  m  m  m  m  m  m  m  m  m  m  m  m  m  m  m  m  m  m  m  m  m  m  m       * * * * * * 0 0 0 0 0 0 - - - - - - . . . . . . ' ' ' ' ' ' & & & & & & . . . . . . ) ) ) ) ) ) * * * * * * ) ) ) ) ) ) . . . . . . 1 1 1 1 1 1 * * * * * * ) ) ) ) ) ) 0 0 0 0 0 0 3 3 3 3 3 3 9 9 9 9 9 9 = = = = = = % % % % % %t:2 t:2 t:2 t:2 t:2x t:2 t:2 t:2 t:2 t:2r  