
    ii                       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 d dlmZ d dlmZ d dlmZ d dlmZ d d	lm Z  d d
lm!Z! d dlm"Z" d dlm#Z# d dlm$Z$ d dlm%Z% d dlm&Z& d dlm'Z' d dlm(Z( d dlm)Z) d dlm*Z* d dlm+Z+ d dl,m-Z- d dl,m.Z. d dl,m/Z/ d dl,m0Z0 d dl1m2Z2  G d dee          Z3dS )    )Exchange)ImplicitAPIN)Balances
CurrenciesCurrencyIntMarginModificationMarketNumOrder	OrderBookOrderRequest	OrderSide	OrderTypeStrStringsTickerTickersTradeTradingFeesTransactionTransferEntry)List)ExchangeError)AuthenticationError)PermissionDenied)ArgumentsRequired)
BadRequest)	BadSymbol)InsufficientFunds)InvalidAddress)InvalidOrder)OrderNotFound)NotSupported)RateLimitExceeded)ExchangeNotAvailable)OnMaintenance)InvalidNonce)ROUND)TRUNCATE)DECIMAL_PLACES)SIGNIFICANT_DIGITS)Precisec                   >    e Zd Z fdZd Zd Zd Zd Zd Zi fdZ	i fde
e         fd	Zi fdefd
Zd Zi fdefdZi fdededededef
dZdZdefdZd Zd Zdi fdededefdZdZd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"dZdede#fdZ$ddi fded edede
e#         fd!Z%d"dd#i fded edede
e&         fd$Z'dZdede&fd%Z(d& Z)d' Z*d( Z+dZdede,fd)Z-di fded*e.d+e/ded,e0f
d-Z1di fded*e.d+e/ded,e0f
d.Z2i fd/e
e3         fd0Z4di fde5fd1Z6di fd2ede5fd3Z7di fde5fd4Z8di fd2ede5fd5Z9di fd2ede5fd6Z:dddi fde5d edede
e,         fd7Z;dddi fde5d edede
e,         fd8Z<dddi fd2ede5d edefd9Z=dddi fde5d edefd:Z>i fdefd;Z?i fdefd<Z@d= ZAdZdedeBfd>ZCi fdeDfd?ZEdddi fde5d edede
eB         fd@ZFdi fdedefdAZGdi fdefdBZHdZdefdCZIdD ZJdEdFi ddfdGZKdH ZLdI ZMdZdefdJZNdddi fde5d edefdKZOi fdefdLZPdi fdefdMZQdddi fde5d edefdNZRdZdefdOZSdZdefdPZTi fdefdQZUd"ddi fded edefdRZVdZdefdSZWddi fded edefdTZXdZdefdUZYi fdededeZfdVZ[dZdeZfdWZ\di fd2ede5fdXZ]ddi fd2eded*e.d+e/de0d,e0fdYZ^ xZ_S )[	bitfinex2c                    |                      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d@d
i dAd
dBd
dCddDddEddFddGddHddIddJddKd
dLddMd
dNd
dOddPd
dQdi dRddSd
dTd
dUddVd dWdXdYd
dZd
d[d
d\d
d]dd^d
d_d
d`d
daddbddcdddedfdgdhdidjdkdldmdndodpdqdrdsdtdudvdwdvdxdydzd{gd|d}d~i dd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ddddddddddd
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dddd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dbi iddt
          dd d!d"d!d"d"d"d#d$d%d&d'd(d)d*d+d,d-d-d.ddddd/d0d
id1d2t          t          t          t          t          t          t          d3t          t          t          t          t           t"          d4d5d6i d7d8d9d:d;d8d<d=d>d?d@dAdBdCdDdEdFdGdHdIdJdKdLdMdNdOdPd:dQdRdSdTdUdVi dWdXdYdZd[dY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dvdwdxdydzd{          S (|  Nidr/   nameBitfinex	countriesVGversionv2	certifiedFproThasCORSspotmarginswapfutureoption	addMarginborrowCrossMarginborrowIsolatedMargincancelAllOrderscancelOrdercancelOrderscreateDepositAddresscreateLimitOrdercreateMarketOrdercreateOrdercreatePostOnlyOrdercreateReduceOnlyOrdercreateStopLimitOrdercreateStopMarketOrdercreateStopOrdercreateTrailingAmountOrdercreateTrailingPercentOrdercreateTriggerOrder	editOrderfetchBalancefetchBorrowInterestfetchBorrowRatefetchBorrowRateHistoriesfetchBorrowRateHistoryfetchBorrowRatesfetchBorrowRatesPerSymbolfetchClosedOrderfetchClosedOrdersfetchCrossBorrowRatefetchCrossBorrowRatesfetchCurrenciesfetchDepositAddressfetchDepositsWithdrawalsfetchFundingHistoryfetchFundingRatefetchFundingRateHistoryfetchFundingRatesfetchIndexOHLCVfetchIsolatedBorrowRatefetchIsolatedBorrowRatesfetchLedgerfetchLeveragefetchLeverageTiersfetchLiquidationsfetchMarginModefetchMarketLeverageTiersfetchMarkOHLCVfetchMyTrades
fetchOHLCVfetchOpenInterestfetchOpenInterestHistoryfetchOpenOrderfetchOpenOrders
fetchOrderfetchOrderBookfetchOrderBooksfetchOrderTradesfetchPositionfetchPositionModefetchPositionsfetchPremiumIndexOHLCVfetchStatusfetchTickers	fetchTimefetchTradingFeefetchTradingFeesfetchTransactionFeesfetchTransactionsemulated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   urlszchttps://user-images.githubusercontent.com/1294454/27766244-e328a50c-5ed2-11e7-947b-041416579bb3.jpgz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}/hist)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   tiers)tradingfundingprecisionModeoptionsR0marketlimit)EXCHANGE MARKET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   )r<   r   r   r=   derivativesr?   r>   
includeFee)	precisionexchangeTypes
orderTypesfiatv2AccountsByTyper   
exceptions)110101000110020101001011420060temporarily_unavailable)addresszavailable balance is onlyznot enough exchange balancezOrder not foundzsymbol: invalidzInvalid order)exactbroadcommonCurrenciesUSTUSDTEUTF0EURTUSTF0ALGALGOAMPAMPLATOATOMBCHABCXECBCHNBCH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superr/   describeparse_numberr,   r%   r   r   r   r(   r'   r&   r!   r    r#   r   r"   )self	__class__s    T/var/www/html/crypto-bot/backend/venv/lib/python3.11/site-packages/ccxt/bitfinex2.pyr4  zbitfinex2.describe#   s   i 6 6 ? ? A A hD
+hD
JhD
 $hD
 t	hD

 hD
 4hD
  UUU $U 	U
 %U %U UU $UU 'U "4U tU U 'U #DU $TU  t!U" &t#U U$ (%U& ''U( ()U* "4+U, ,T-U. -e/U0 %d1U2 T3U4 5U6 &u7U8 "59U: +E;U< )%=U> #E?U@ ,UAUB #DCUD $TEU U UF 'GUH (IUJ "4KUL &tMUN +DOUP &uQUR #DSUT *4UUV $TWUX "5YUZ *5[U\ +E]U^ t_U`  aUb %ecUd $TeUf "5gU U Uh +EiUj !%kUl  mUn doUp $TqUr +DsUt !$uUv "4wUx dyUz !${U| "5}U~ #DU@  AUB $UCUD !$EUF )%GUH tIU U UJ KUL UMUN "5OUP #DQUR 'SUT $ZUUV WUX #EYUZ &u[U\ u]U^ T_U`  aUb "5cUd %eUf DgUh DiU UhD
|  }hD
\ ]hD
^ }4<9 
 28F 8 _hD
z >'>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{> > >@ +.#& AD DL  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MT T{hD
d $"&!%!..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' 'ehD
t	 /u	hD
v	 ! (0&-%- %,+2$+" "( 0- 
 !      ' *(&#+&$% % !%]1 1w	hD
Z .-'0)*/C	 	  .1B3D'4'0%1  [hD
B  &!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&! &! &!ChD
 h h h	    c                      || j         d         v S )Nr   )r   r6  codes     r8  is_fiatzbitfinex2.is_fiat  s    t|F++,r9  c                     d|z   S )Nf r;  s     r8  get_currency_idzbitfinex2.get_currency_id  s    Tzr9  c                     || j         d         v r| j         d         |         S t          | j        dz   |z   dz             )NcurrencyNames z not supported for withdrawal)r   r$   r1   r;  s     r8  get_currency_namezbitfinex2.get_currency_name  sE    4<000<06647S=4/2QQRRRr9  c                     |                      |          }|                     |t          | j        |         d         d         t                    S )Nr   amount)safe_symboldecimal_to_precisionr*   marketsr+   )r6  symbolrG  s      r8  amount_to_precisionzbitfinex2.amount_to_precision  sE     !!&))((4<;OP[;\]e;fhvwwwr9  c                     |                      |          }|                     |t          | j        |         d         d         | j                  }|                     |t
          dt                    S )Nr   pricer   )rH  rI  r)   rJ  r   r*   r+   )r6  rK  rN  s      r8  price_to_precisionzbitfinex2.price_to_precision  s`    !!&))))%V8L[8YZa8bdhdvww
 ((!^LLLr9  c                     |                      |          }|                     |d          }|                     ddd||          ddd|dS )a]  
        the latest known information on the availability of the exchange API
        :see: 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)r6  paramsresponse	statusRaws       r8  fetch_statuszbitfinex2.fetch_status  se     //77$$Xq11	&&]'F'F	S\]]
 
 	
r9  returnc                    |                      |          }|                     |          }|                     |dg           }|                     |dg           }|                     ||          }|                     |          }|                     |dg           }g }t          dt          |                    D ]}||         }|                     |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%
           |S )&a  
        retrieves data on all markets for bitfinex2
        :see: 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:      /   r1   trK  basequotesettlebaseIdquoteIdsettleIdtyper<   r>   r=   r?   r@   activecontractlinearrS  85)rG  rN  minmaxz1e-8)leveragerG  rN  cost)
inversecontractSizeexpiryexpiryDatetimestrike
optionTyper   limitscreatedrX  )publicGetConfPubInfoPairpublicGetConfPubInfoPairFutures
safe_valuearray_concatpublicGetConfPubListPairMarginrangelensafe_string_upperfindsplitsafe_currency_coderZ  rA  in_arrayappendr5  int)r6  r[  spotMarketsInfofuturesMarketsInforJ  	marginIdsresultipairr1   r   r<   r>   rk  rl  partsrh  ri  	splitBase
splitQuoterK  rj  rm  minOrderSizeStringmaxOrderSizeStringr=   s                             r8  fetch_marketszbitfinex2.fetch_markets  s    77??!AA&II///1bAA!__-?BGG##O5GHH77??	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))&11F**733G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 r9  c                 X   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}|                     |dg           }i }t          dt          |                    D ]}	||	         }
|
                    d          dk    r%|                     |
          }|                     |d         |
g           }| 	                    |d          }|                     |d         |
g           }| 	                    |d          }|dnd}|                     |d         |
g           }|                     |dg           }| 
                    |d          }|                     |d         |
g           }d}d|
z   }||
||
||||g||ddd|t          |          |                     |                     |                    dd|dddi d||<   i }|                     |dg           }|
                    dd          }t          dt          |                    D ]}||         }| 	                    |d          }| 	                    |                     |dg           d          }||k    r;|                     |          }||                                |dddddddddid	||<   t#          |                                          }t          |          } | dk    r|||         d<   |S ) a  
        fetches all available currencies on an exchange
        :see: 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:method,configr   r      rc  rf     rd     )symlabelunitundlpoolexplorerr   ra  r  r  Nothercryptor   r  rr  r?  Trt  )rG  r   )r1   uppercaseIdr<  rX  rn  r2   ro  depositr   feer   r  networksr    r   )	rX  r1   networkro  r  r   r  r   r  r  )joinpublicGetConfConfigextendindex_byr  r  r  r  r  rZ  safe_numberr  r5  parse_precisionreplacesafe_networklowerlistkeys)!r6  r[  labelsr  requestr\  indexedidsr  r  r1   r<  r  r2   r  rawTypern  	feeValuesr   r  r  r   fidr  currencyNetworkscleanIdjr  	networkId
currencyIdr  keysNetworksnetworksLengths!                                    r8  fetch_currencieszbitfinex2.fetch_currenciesy  sd   

 

 

 &!!f
 ++DKK,H,HII` ==1b!A!A1EE]]4??8Q#C#CQGGMM$//(Ar"B"BAFFMM$//(Ar"B"BAFFMM$//(Ar"B"BAFFdooh2&F&FJJMM$//(Ar"B"BAFF
 
 ooh2..q#c((## E	4 E	4AQBwwt}}!!**2..DOOGG$4b"==E##E1--D??76?B;;D&&tQ//G&77XDR@@I??9a44D""4++C??76?B;;DI(C!UD)T:  ^^  $001E1Ei1P1PQQ# 
  ##! !	 	 - F4L0 H#xB??jjr**G1c"23344  '* ,,T155	!--doodAr.J.JANN
(("//	::G )'oo//#,"&#'$(#%)&'+'+) )#) )HW%   00L ..N!!+3tZ(r9  c                 T    dddddddddd	d
ddddd}|                      |||          S )NBTCLTCERC20OMNILIQUIDTRC20EOSAVAXSOLr   r   KSMDVFOMG)BITCOINLITECOINETHEREUM	TETHERUSE	TETHERUSO	TETHERUSL	TETHERUSX	TETHERUSSTETHERUSDTAVAXTETHERUSDTSOLTETHERUSDTALGTETHERUSDTBCHTETHERUSDTKSMTETHERUSDTDVFTETHERUSDTOMGrZ  )r6  r  networksByIds      r8  r  zbitfinex2.safe_network1  sU     ! $"#""""
 
" iCCCr9  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 )ae  
        query for balance and get the amount of funds available for trading or funds locked in orders
        :see: 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   rn  r   Nz. fetchBalance() type parameter must be one of , r   rX  r   rc  r   debtr   r  r  f0totalrf  free)load_marketsr  r   rZ  r  r  r   r1   r  omitprivatePostAuthRWalletsr  r  accountsafe_string_lowerr  safe_balance)r6  r[  accountsByTyperequestedTypeaccountTyper  isDerivativequeryr\  r  r  balancer  interestrn  r  startisDerivativeCodederivativeConditionr<  s                       r8  fetch_balancezbitfinex2.fetch_balanceE  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  (((r9  r<  rG  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             |                     ||
          S )a  
        transfer currency internally between wallets on the same account
        :see: 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 )rG  currencycurrency_tofromtor   errorr  r  r   rD  )r  r  r   rZ  r  r  r   r1   r  r  convert_derivatives_idcurrency_to_precisionprivatePostAuthWTransferr  throw_exactly_matched_exceptionr   r   parse_transfer)r6  r<  rG  r  r  r[  r  fromIdr  toIdr  fromCurrencyIdtoCurrencyIdrequestedAmountr  r\  r  messages                     r8  r   zbitfinex2.transferl  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""8X666r9  Nr  c           
         |                      |d          }|                     |d          }|                     |d          }|                     |d          }|                     |d          }|                     |d          }d ||                     |          |                     |          |                     |d          |                     ||          |||d	S )	Nr   rf  r   r  r  rd  r  )	r1   	timestampdatetimerT  rG  r  r  r  rX  )safe_integerr  rZ  iso8601parse_transfer_statusr  r  )	r6  r   r  r  rX  r  r  r  rT  s	            r8  r
  zbitfinex2.parse_transfer  s    0 %%h22	x++&&tQ//$$T1--	%%dA..
!!(A.."Y//0088&&tQ////
HEE&"

 

 
	
r9  c                 <    dddd}|                      |||          S )NrR  failed)SUCCESSERRORFAILUREr  r6  rT  statusess      r8  r  zbitfinex2.parse_transfer_status  s1    
 

 &&999r9  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 )	NrX  r   rf  r   r  ra  r=   r   )r  rZ  r  )	r6  r  rn  rX  
transferId
underlyingr  r  r  s	            r8  r  z bitfinex2.convert_derivatives_id  s     x00%%dA..
__T1b11

=  ))*aDDJ
OOa'E)%&&1T9# /'$.
X))*aDDJJ#Jr9  rK  r   c                 v   |                                   |                     | 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 )aZ  
        fetches information on open orders with bid(buy) and ask(sell) prices, volumes and other data
        :see: 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   r1   )rK  r   Nr  rK  )rK  bidsasksr  r  noncer   r   r  r   r"  r#  T)r  r  r   r   r  publicGetBookSymbolPrecisionmillisecondsr  r  r  r  rZ  r-   
string_abs	string_gtr  r5  sort_by)r6  rK  r   r[  r   r   r  fullRequest	orderbookr  r  
priceIndexr  orderrN  signedAmountrG  sides                     r8  fetch_order_bookzbitfinex2.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..)) 	D 	DAaLE$$UJ77E++E155L'55F$.|SAAM66vD4L(9(9&(A(A BCCCCfVna>>vfVna88vr9  r   c           	         |                      d |          }t          |          }|                     ||dz
            }|                     ||dz
            }|                     i d|dd dd d|                     ||dz
            d|                     ||d	z
            d
|                     ||dz
            d|                     ||dz
            d|                     ||dz
            d|                     ||dz
            dd dd d|d|dd d|                     ||dz
            dt	          j        |d          dd |                     ||dz
            d |d|          S )Nrf  r  rK  r  r  highr  lowr   bidr   	bidVolume	   askr   	askVolumer  vwapopencloselastpreviousClosechangerd  r   100averagerc  )
baseVolumequoteVolumerX  )rH  r  rZ  safe_tickerr-   
string_mul)r6  tickerr   rK  lengthr<  r   s          r8  parse_tickerzbitfinex2.parse_ticker  s   P !!$//V
33%%ffqj99
 !
f!
!
 !
 D$$VVaZ88	!

 4##FFQJ77!
 4##FFRK88!
 ))&&1*==!
 4##FFQJ77!
 ))&&1*==!
 D!
 D!
 T!
 D!
 T!
 d&&vvz::!
  ',Z??!!
" t#!
$ **66A:>>)!
 !
 !
* +  	r9  symbolsc                 .   |                                   |                     |          }i }|.|                     |          }d                    |          |d<   nd|d<   |                     |                     ||                    }i }t          dt          |                    D ]V}||         }|                     |d          }	| 	                    |	          }
|
d         }| 
                    ||
          ||<   W|                     |d|          S )a  
        fetches price tickers for multiple markets, statistical information calculated over the past 24 hours for each market
        :see: 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  rH  ALLr   rK  )r  market_symbols
market_idsr  publicGetTickersr  r  r  rZ  safe_marketrG  filter_by_array_tickers)r6  rH  r[  r  r  r   r  r  rE  marketIdr   rK  s               r8  fetch_tickerszbitfinex2.fetch_tickersa  s    	%%g..//'**C!$#GI!&GI''GV(D(DEEP q#g,,'' 	? 	?AQZF''22H%%h//FH%F!..vv>>F6NN++FHgFFFr9  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
        :see: 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>`
        rK  r1   )r  r   publicGetTickerSymbolr  rG  )r6  rK  r[  r   r  rE  s         r8  fetch_tickerzbitfinex2.fetch_ticker  sp     	V$$fTl
 ++DKK,H,HII  000r9  c                    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   rf  r  rc  -sellbuyr   r   r   r   r6  r   )rx  r  rd  r   )r1   r  r  rK  r-  r/  rn  takerOrMakerrN  rG  rx  r  rX  )r  rZ  r-   r'  rH  r  
string_negr  r   
safe_trader  )r6  trader   tradeLength	isPrivater1   amountIndexr/  amountStringr,  priceStringorderIdrY  rn  r  rK  timestampIndexr  rP  r   feeCostStringfeeCurrencyIdfeeCurrency	orderTypes                           r8  parse_tradezbitfinex2.parse_trade  s-   8 %jj 1_	eQ''$+aa!''{;;#*QQ
&&uj99?c!!D"-l;;LLD!!$//'.Q%%e^<<	 	NQxH%%h//F&&ua00G%%eQ//E',zz77L ,,UA66M#.}==M ,,UB77M11-@@K%' C aI##DL$A9MMD"Y//( " 
  
   	r9  sincec                    |                                   d}|                     |dd          \  }}|r|                     d||||d          S |                     |          }d}d|d         i}|||d	<   d
}|t	          |d          |d<   ||d<   |                     d||          \  }}|                     |                     ||                    }	|                     |	d          }
| 	                    |
|d|          S )a{  
        get the list of most recent trades for a particular symbol
        :see: 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paginate'  z-1rK  r1   Nr  rS  r   sortendr   )
r  handle_option_and_paramsfetch_paginated_call_dynamicr   ru  handle_until_optionpublicGetTradesSymbolHistr  r)  parse_trades)r6  rK  ri  r   r[  rl  r   rn  r  r\  tradess              r8  fetch_tradeszbitfinex2.fetch_trades  s-    	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**  u===r9  r   d   c           	         |                                   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
        :see: 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)
        Frq   rl  rm  Nr1   r   )rK  	timeframern  r   r  ro  )r  rp  "fetch_paginated_call_deterministicr   ru  rZ  r   rr  (publicGetCandlesTradeTimeframeSymbolHistr  parse_ohlcvs
r6  rK  ry  ri  r   r[  rl  r   r  r\  s
             r8  fetch_ohlcvzbitfinex2.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Kr9  c           	         |                      |d          |                     |d          |                     |d          |                     |d          |                     |d          |                     |d          gS )Nr   r   rc  rf  r  r  )r  r  )r6  ohlcvr   s      r8  parse_ohlcvzbitfinex2.parse_ohlcvW  s     eQ''UA&&UA&&UA&&UA&&UA&&
 	
r9  c                     ||S |                     d          }|                     |d          }ddddddddddd
}|                     |||          S )NrD  r   r:  closedcanceledrejected)
ACTIVE	PARTIALLYEXECUTEDCANCELEDINSUFFICIENTzPOSTONLY CANCELEDRSN_DUST	RSN_PAUSEzIOC CANCELEDzFILLORKILL CANCELED)r  rZ  )r6  rT  r  stater  s        r8  parse_order_statuszbitfinex2.parse_order_statusk  sv    >MS!!  ** "&!+"#&#-
 
 %888r9  c                 D    dgdgddgd}|                      ||d           S )N
reduceOnlypostOnly)102440965120)r  )r6  flags
flagValuess      r8  parse_order_flagszbitfinex2.parse_order_flags~  s:     "NL!:.
 

 z5$777r9  c                 >    ddddd}|                      ||d          S )NIOCFOK)r   r   r  r  GTCr  )r6  rg  r   s      r8  parse_time_in_forcezbitfinex2.parse_time_in_force  s4    !!	
 

 
Iu===r9  c           	      t   |                      |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   rc  r  rd  r  r   rW  rX  r   r      Fr  Tr   r   r          @    r  rX  r1   clientOrderIdr  r  lastTradeTimestamprK  rn  timeInForcer/  rN  	stopPricetriggerPricerG  rx  r@  )filled	remainingrT  r  ru  )rZ  rH  r  r-   r'  	string_ltr  r   r  r  r  r  r  r  
safe_orderr  )r6  r-  r   r1   rP  rK  r  r  r.  rG  r/  rg  rn  r  rawFlagsr  r  r  rN  r  rT  statusStringr  r@  r  s                            r8  parse_orderzbitfinex2.parse_order  sj   eQ''##E1--!!(++ %%eQ//	&t'7'7q'A'ABB	''q11#L11 *<==Hvv5$$UA..	o N NPYZZ..y99##E2..&&x001c%jj)) $ $8z))#H  ++	((i;P.P.PE((33I111((33''r22# &&u--E,,T-=-=eQ-G-GHHF""5"--((22  
E 
" 
 ] 
 	 

 Y// 
 !$ 
 f 
 D 
 ; 
  
 D 
 U 
  
 I 
 f 
  D! 
" w# 
$ "- 
  
  
. /  	r9  rn  r/  rN  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.stopPrice]: 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>`
        rX  r1   )rK  rG  r  r  trailingAmountr  r  Fr  cidr  NzTRAILING STOPprice_trailingrN  r   z
STOP LIMITprice_aux_limitSTOPr  r  POz@ createOrder() requires a price argument with IOC and FOK ordersr   z7 createOrder() does not allow market IOC and FOK ordersrJ   r<   z	EXCHANGE rn  r         r  )r  r  r  r  r  r  r  )r   rL  r-   rZ  safe_string_2rZ  	safe_boolsafe_value_2upperrO  r"   r1   handle_margin_mode_and_paramssumr  r  )r6  rK  rn  r/  rG  rN  r[  r   r`  r  r  r  r  postOnlyParamr  r  rg  iocfokr  
marginModer  s                         r8  create_order_requestzbitfinex2.create_order_request  s   * V$$//??(,||G<N|<\<\Tl"
 
 &&v{NKK	))&2BCC&&v}==vz5AA^^FL%@@
))&%IIJJLL	%'I(6G$%%"#66vyIIGG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9#4#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+++r9  c                    |                                   |                     |          }|                     ||||||          }|                     |          }	|                     |	d          }
|
dk    r?|	d         }|	d         }t          | j        dz   |	d         z   dz   |z   dz   |z   dz             |                     |	d	g           }|                     |d
          }|                     ||          S )a  
        create an order on the exchange
        :see: 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.stopPrice]: 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>`
        rd  r  r  r  rD  : (#)rf  r   )	r  r   r  privatePostAuthWOrderSubmitrZ  r   r1   	safe_listr  )r6  rK  rn  r/  rG  rN  r[  r   r  r\  rT  	errorCode	errorTextordersr-  s                  r8  create_orderzbitfinex2.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))v...r9  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                    .| 
                    |          S )a  
        create a list of trade orders
        :see: 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   rK  rn  r/  rG  rN  r[  onopsrf  )r  r  r  rZ  r  	safe_dictr  r  privatePostAuthWOrderMultir  parse_orders)r6  r  r[  ordersRequestsr  rawOrderrK  rn  r/  rG  rN  orderParamsorderRequestr  r\  resultsdataentryindividualOrders                      r8  create_orderszbitfinex2.create_orderso  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NN?1-....  )))r9  c                     |                                   ddi}|                     |                     ||                    }|                     |dg           }|                     |          S )a  
        cancel all open orders
        :see: 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   rf  )r   privatePostAuthWOrderCancelMultir  r  r  )r6  rK  r[  r  r\  r  s         r8  cancel_all_orderszbitfinex2.cancel_all_orders  sn     	1
 88Wf9U9UVV!R00  (((r9  r1   c                    |                                   |                     |dd          }d}|M|                     |d          }|t          | j        dz             ||d}|                     |ddg          }ndt          |          i}|                     |                     ||                    }|                     |d          }| 	                    |          S )	a~  
        cancels an open order
        :see: https://docs.bitfinex.com/reference/rest-auth-cancel-order
        :param str id: order id
        :param str symbol: Not used by bitfinex2 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_dater1   rf  )
r  r  r  r"   r1   r  r  privatePostAuthWOrderCancelr  r  )	r6  r1   rK  r[  r  r  r  r\  r-  s	            r8  cancel_orderzbitfinex2.cancel_order  s     	???oofi88G"47  .L  $L  M  M  M# G YYv'?@@FF c"ggG 33DKK4P4PQQ!,,&&&r9  c                    |                                   t          dt          |                    D ] }|                     ||                   ||<   !d|i}d}||                     |          }|                     |                     ||                    }|                     |dg           }|                     ||          S )a  
        cancel multiple orders at the same time
        :see: 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   r1   Nrf  )	r  r  r  parse_to_numericr   r  r  r  r  )	r6  r  rK  r[  r  r  r   r\  r  s	            r8  cancel_orderszbitfinex2.cancel_orders  s     	q#c((## 	3 	3A**3q622CFF#
 [[((F88Wf9U9UVVf !R00  000r9  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
        :see: https://docs.bitfinex.com/reference/rest-auth-retrieve-orders
        :see: 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>`
        r1   Nr   z order z
 not found)r  fetch_open_ordersr  r  r#   r1   r6  r1   rK  r[  r  r  r-  s          r8  fetch_open_orderzbitfinex2.fetch_open_order  s~     3r77)
 ''dDKKQW<X<XYY**=) 3b 8< GHHHr9  c           	          dt          |          gi}|                     |dd|                     ||                    }|                     |d          }|t	          | j        dz   |z   dz             |S r  )r  fetch_closed_ordersr  r  r#   r1   r  s          r8  fetch_closed_orderzbitfinex2.fetch_closed_order0  s~     3r77)
 ))&$dkk'SY>Z>Z[[**=) 3b 8< GHHHr9  c                 P   |                                   i }d}d}|*|                     |                     ||                    }nI|                     |          }|d         |d<   |                     |                     ||                    }|                     ||||          S )aj  
        fetch all unfilled currently open orders
        :see: https://docs.bitfinex.com/reference/rest-auth-retrieve-orders
        :see: 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>`
        Nr1   rK  )r  privatePostAuthROrdersr  r   privatePostAuthROrdersSymbolr  )r6  rK  ri  r   r[  r  r   r\  s           r8  r  zbitfinex2.fetch_open_ordersC  s     	>224;;w3O3OPPHH[[((F &tGH88Wf9U9UVVHN   65%@@@r9  c                    |                                   d}|                     |dd          \  }}|r|                     d||||          S i }|||d<   |||d<   |                     d||          \  }}d}d}|*|                     |                     ||                    }nI|                     |          }|d         |d	<   |                     |                     ||                    }|                     ||||          S )
a  
        fetches information on multiple closed orders made by the user
        :see: https://docs.bitfinex.com/reference/rest-auth-retrieve-orders
        :see: 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>`
        Fr\   rl  Nr  r   ro  r1   rK  )	r  rp  rq  rr  privatePostAuthROrdersHistr  r    privatePostAuthROrdersSymbolHistr  )	r6  rK  ri  r   r[  rl  r  r   r\  s	            r8  r  zbitfinex2.fetch_closed_orders  s2    	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   65%@@@r9  c                 <   |t          | j        dz             |                                  |                     |          }t	          |          }||d         d}|                     |                     ||                    }	|                     |	|||          S )a  
        fetch all the trades made from a single order
        :see: 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 argumentr1   )r1   rK  )r   r1   r  r   r  #privatePostAuthROrderSymbolIdTradesr  rt  )
r6  r1   rK  ri  r   r[  r   rb  r  r\  s
             r8  fetch_order_tradeszbitfinex2.fetch_order_trades  s     >#DG.^$^___V$$b''Tl
 

 ;;DKKQW<X<XYY  65%@@@r9  c                    |                                   d}d|                                 i}|||d<   |||d<   d}|J|                     |          }|d         |d<   |                     |                     ||                    }n)|                     |                     ||                    }|                     ||||          S )aF  
        fetch all trades made by the user
        :see: https://docs.bitfinex.com/reference/rest-auth-trades
        :see: 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>`
        Nro  r  r   r1   rK  )r  r&  r    privatePostAuthRTradesSymbolHistr  privatePostAuthRTradesHistrt  )r6  rK  ri  r   r[  r   r  r\  s           r8  fetch_my_tradeszbitfinex2.fetch_my_trades  s     	4$$&&
 $GG$GG[[((F &tGH<<T[[RX=Y=YZZHH66t{{7F7S7STTH  65%@@@r9  c                     |                                   ddi}|                     ||                     ||                    S )a  
        create a currency deposit address
        :see: 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  )r6  r<  r[  r  s       r8  create_deposit_addressz bitfinex2.create_deposit_address  sH     	
 ))$GV0L0LMMMr9  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
        :see: 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  r1   Nz5 fetchDepositAddress() could not find a network for 'D'. You can specify it by providing the 'network' value inside paramswalletr   r   )methodr  r  rf  r  )r  r   tagr  rX  )
r  r  rZ  r  r   r1   r  privatePostAuthWDepositAddressr  check_address)r6  r<  r[  r  r  r  currencyNetworkr  r  r  r\  r  poolAddressr   r  s                  r8  r  zbitfinex2.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###
 
 	
r9  c                 L    dddddddddddd}|                      |||          S )NrR  r  r  pending)r  	COMPLETEDr  r  r  zPENDING APPROVALPENDINGzPENDING REVIEWzPENDING CANCELLATIONSENDINGzUSER APPROVEDr  r  s      r8  parse_transaction_statusz"bitfinex2.parse_transaction_statusE  sI    " ) '$- &
 
 &&999r9  c                    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	}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   rf  r   r<  r  rR  r  rc  
withdrawal   r   r  rd  r6  r  r   r  r  r         rX  r1   txidrn  r  r  rG  rT  r  r  r   addressFrom	addressTor  tagFromtagTorU  )r  rx  rate)commentinternalr  )r  r  r  rZ  r-   r'  r  r  r  r  r  r5  r  )r6  transactionr  transactionLengthr  rU  r<  rG  r1   rT  r  rn  feeCostr  r  r  r  r  r  r  r.  s                        r8  parse_transactionzbitfinex2.parse_transactionU  s   h  ,,		!!??;266D))+q99I#'&&tQ//G"!,W55%%dA..F!!$**BFQww!""4++CDD"$$!!+q11B))+q99J**:x@@D((a88I''	22G))+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 )
 
 
 	
r9  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 )aT  
        fetch the trading fees for multiple markets
        :see: 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   rf  r   r   r  r  T)rX  rK  r   r   ri  r   r   rp  )	r  privatePostAuthRSummaryr  r   r  r  r  rH  r   )r6  r[  r\  r  r   feeData	makerData	takerDatamakerFeemakerFeeFiatmakerFeeDerivtakerFeetakerFeeFiattakerFeeDerivr  rK  r   r  s                     r8  fetch_trading_feeszbitfinex2.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r9  c                 l   |                                   d}i }|||d<   |||d<   d}|J|                     |          }|d         |d<   |                     |                     ||                    }n)|                     |                     ||                    }|                     ||||          S )a  
        fetch history of deposits and withdrawals
        :see: https://docs.bitfinex.com/reference/movement-info
        :see: https://docs.bitfinex.com/reference/rest-auth-movements
        :param str [code]: unified currency code for the currency of the deposit/withdrawals, default is None
        :param int [since]: timestamp in ms of the earliest deposit/withdrawal, default is None
        :param int [limit]: max number of deposit/withdrawals to return, default is None
        :param dict [params]: extra parameters specific to the exchange API endpoint
        :returns dict: a list of `transaction structure <https://docs.ccxt.com/#/?id=transaction-structure>`
        Nr  r   r  r  )r  r  %privatePostAuthRMovementsCurrencyHistr  privatePostAuthRMovementsHistparse_transactions)r6  r<  ri  r   r[  r  r  r\  s           r8  fetch_deposits_withdrawalsz$bitfinex2.fetch_deposits_withdrawalsD	  s     	$GG$GG}}T**H"*="9GJAA$++gW]B^B^__HH99$++gv:V:VWWH: &&x5%HHHr9  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         ||           |                     ||          }|                     |d|i          S )a  
        make a withdrawal
        :see: 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  r1   Nz* withdraw() could not find a network for 'r  r  r   )r  r  rG  r   
payment_idr   r   Fr   
fee_deductr   r  rD  r  r  r   r   r  successr   )r  r  r  rZ  r  r  r   r1   number_to_stringr   r  privatePostAuthWWithdrawr  r	  r   throw_broadly_matched_exceptionr   r   )r6  r<  rG  r   r  r[  r  r  r  r  r  r  r  withdrawOptionsr   r\  statusMessagefeedbackr  textr  s                        r8  r   zbitfinex2.withdraw{	  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,,Xx@@{{;w)
   	r9  c                     |                                   |                     |          }|                     |          }|                     ||          S )ap  
        fetch all open positions
        :see: 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  rK  privatePostAuthRPositionsparse_positions)r6  rH  r[  r\  s       r8  fetch_positionszbitfinex2.fetch_positions	  sU     	%%g..11&99F ##Hg666r9  c                 
   |                      |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  r  trade_pricetrade_amountrX  r1      rK  notionalr  isolatedliquidationPricer   
entryPricerc  unrealizedPnlrd  r   r  	contractsrz  	markPrice	lastPricer/  r   longshorthedgedr  r  r     r  r6  )
lastUpdateTimestampmaintenanceMarginmaintenanceMarginPercentage
collateralinitialMargininitialMarginPercentagerw  marginRatiostopLossPricetakeProfitPrice)
rZ  r  safe_positionrH  r5  r  r-   r(  r  rD  )	r6  positionr   rP  rG  r  meta
tradePricetradeAmounts	            r8  parse_positionzbitfinex2.parse_position	  s   B ##Ha00!!(A..%%h33	"--%%dM::
&&t^<<!! #
H#
$""8R00#
 d&&x88#
 ))&11	#

 *#
  0 01 = =#
 $**8Q77#
 T--h::#
 $**8Q77#
 #
 D#
 #
 #
 g/<<IFF'#
 d#
  !#
" Y//##
$ $(#4#4Xr#B#B!%!1!1(B!?!?+/**8R88!..w/A+z/Z/Z[['+((155!#7#
 #
 #
   	r9  c                 *    |                                  S N)r&  )r6  s    r8  r$  zbitfinex2.nonceB
  s      """r9  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 )Nre  r   r   r   ?r   z/api/zapplication/json)z	bfx-noncez
bfx-apikeyzbfx-signaturezContent-Type)rW  r  bodyheaders)implode_paramsr  extract_paramsr6   r   	urlencodecheck_required_credentialsstrr$  jsonhmacencodesecrethashlibsha384apiKey)r6  pathr   r  r[  rf  re  r  r  rW  r$  auth	signatures                r8  signzbitfinex2.signE
  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Or9  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 )Nr  r  rD  r   r   r  z returned empty responsei    r   r  r  r  )

isinstancer  r  r1   r	  r   r8  r   r%   rZ  )r6  
statusCode
statusTextrW  r  rf  re  r\  requestHeadersrequestBodyr  r;  r  r  s                 r8  handle_errorszbitfinex2.handle_errors^
  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r9  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  r  r  r   paymentpayoutr   r[  r\  )r  )r6  rn  s     r8  parse_ledger_entry_typez!bitfinex2.parse_ledger_entry_typev
  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Kr9  c                    d }|                      |d          }|                      |d          }|                     ||          }|                     |d          }|                     |d          }|                     |d          }	|                      |d          }
|
@|
                    d          }|                     |d          }|                     |          }|d d |d |||||                     |          d |	d d |dS )	Nr   r   rc  r  rd  r   r  )r1   	directionr  referenceIdreferenceAccountrn  r  rG  r  r  beforeafterrT  r  rX  )rZ  r  r  r  r  r  r  r  )r6  itemr  rn  r1   r  r<  r  rG  r  descriptionr  firsts                r8  parse_ledger_entryzbitfinex2.parse_ledger_entry
  s%     dA&&%%dA..
&&z8<<%%dA..	!!$**  q))&&tQ//"%%e,,E**5!44E//66D $"Y//
 
 	
r9  c                    |                                   d}|                     |dd          \  }}|r|                     d||||d          S d}i }|||d<   |||d<   |                     d||          \  }}d}|J|                     |          }|d	         |d
<   |                     |                     ||                    }n)|                     |                     ||                    }|                     ||||          S )a  
        fetch the history of changes, actions done by the user or operations that altered balance of the user
        :see: 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 entrys 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-structure>`
        Fri   rl  i	  Nr  r   ro  r  r  )	r  rp  rq  rr  r  #privatePostAuthRLedgersCurrencyHistr  privatePostAuthRLedgersHistparse_ledger)	r6  r<  ri  r   r[  rl  r  r  r\  s	            r8  fetch_ledgerzbitfinex2.fetch_ledger
  s3    	88PZ[[& 	f44]D%QVX^`deee$GG$GG225'6JJ}}T**H"*="9GJ??GU[@\@\]]HH77GV8T8TUUH    8UEBBBr9  c                 0    |                      |g|          S )an  
        fetch the current funding rate
        :see: https://docs.bitfinex.com/reference/rest-public-derivatives-status
        :param str symbol: unified market symbol
        :param dict [params]: extra parameters specific to the exchange API endpoint
        :returns dict: a `funding rate structure <https://docs.ccxt.com/#/?id=funding-rate-structure>`
        )fetch_funding_rates)r6  rK  r[  s      r8  fetch_funding_ratezbitfinex2.fetch_funding_rate
  s     ''&999r9  c                 0   |t          | j        dz             |                                  |                     |          }dd                    |          i}|                     |                     ||                    }|                     |          S )az  
        fetch the current funding rate
        :see: 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 `funding rate structure <https://docs.ccxt.com/#/?id=funding-rate-structure>`
        Nz0 fetchFundingRates() requires a symbols argumentr  r  )r   r1   r  rL  r  publicGetStatusDerivr  parse_funding_rates)r6  rH  r[  	marketIdsr  r\  s         r8  r  zbitfinex2.fetch_funding_rates
  s     ?#DG.`$`aaaOOG,,	CHHY''
 ,,T[[&-I-IJJ> ''111r9  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 )aV  
        fetches historical funding rate prices
        :see: 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 argumentFrd   rl  8h  rK  r1   r  ro  r   r   )r   r1   r  rp  rz  r   rr  publicGetStatusDerivSymbolHistr  r  r  parse_funding_rate_historyr  filter_by_symbol_since_limit)r6  rK  ri  r   r[  rl  r   r  r\  ratesr  frr  reversedArrayrawRatesratesLengthindexvalueAtIndexs                     r8  fetch_funding_rate_historyz$bitfinex2.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  ....r9  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 S )Nr   r   r   rX  rK  rK     
indexPricerc  interestRateestimatedSettlePricer  r  fundingRater  fundingTimestampfundingDatetimenextFundingRater6  nextFundingTimestampnextFundingDatetimepreviousFundingRatepreviousFundingTimestamppreviousFundingDatetime)rZ  r  rH  r  r  )r6  rp  r   rP  r  r  s         r8  parse_funding_ratezbitfinex2.parse_funding_rateg  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#
 	
r9  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  rX  rK  rK     r  r  r  r  r  r  r  rD  r  r  r  r   r  r  r  r  r  )r  rH  r  r  )r6  rp  r   r  r  s        r8  r  z$bitfinex2.parse_funding_rate_history  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#
 	
r9  c                    |                                   |                     |          }d|d         i}|                     |                     ||                    }|                     |d          }|                     ||          S )at  
        retrieves the open interest of a contract trading pair
        :see: 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  r1   r   )r  r   r  r  r  parse_open_interest)r6  rK  r[  r   r  r\  ois          r8  fetch_open_interestzbitfinex2.fetch_open_interest  s     	V$$F4L
 ,,T[[&-I-IJJ> ^^Ha((''F333r9  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
        :see: 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 bitfinex2
        :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>`
        Frs   rl  r  r  rK  r1   Nr  r   ro  )r  rp  rz  r   rr  r  r  parse_open_interestsr}  s
             r8  fetch_open_interest_historyz%bitfinex2.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< ((65%HHHr9  c           	      @   t          |          }|dk    rdnd}|                     |d          }|                     |d          }|                     |                     ||d d          |                     ||          d ||                     |          |d|          S )N   r  rP  r   r   r>   )rK  openInterestAmountopenInterestValuer  r  rX  )r  r  rZ  safe_open_interestrH  r  r  )r6  r  r   interestLengthopenInterestIndexr  rP  s          r8  r  zbitfinex2.parse_open_interest7  s    v X#1R#7#7BBb%%h22	##Ha00&&&&xvFF"&"2"28=N"O"O!%"Y//(
 (
   	r9  c           	         |                                   d}|                     |dd          \  }}|r|                     d|||d|d          S |                     |          }i }|||d<   |||d<   |                     d	||          \  }}|                     |                     ||                    }|                     ||||          S )
aT  
        retrieves the public liquidations of a trading pair
        :see: 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>`
        Frl   rl  r  rx  Nr  r   ro  )r  rp  rz  r   rr  publicGetLiquidationsHistr  parse_liquidations)	r6  rK  ri  r   r[  rl  r   r  r\  s	            r8  fetch_liquidationszbitfinex2.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Fr9  c                    |d         }|                      |d          }|                     |d          }t          j        |                     |d                    }|                     |d          }t          j        ||          }|                     |d          }	|                     ||                     ||d d          |                     |          |                     |          |                     |	          |                     |          |                     t          j        ||	                    ||                     |          d	          S )	Nr   r  rf  r  rz  rD  rp  )	rX  rK  rJ  rz  rN  	baseValue
quoteValuer  r  )	r  rZ  r-   r'  rD  safe_liquidationrH  r5  r  )
r6  liquidationr   r  r  rP  rJ  rz  r  rN  s
             r8  parse_liquidationzbitfinex2.parse_liquidation  sC   & A%%eQ//	##E1--&t'7'7q'A'ABB	''??&y,??	  ++$$&&xzJJ**955 --l;;&&u--**955++G,>y%,P,PQQ"Y//
&
 
&
 
 
 
	r9  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
        :see: 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>`
        r>   z& setMargin() only support swap marketsr1   )rK  rT  r   )	r  r   r$   r1   r  "privatePostAuthWDerivCollateralSetr  r  parse_margin_modification)r6  rK  rG  r[  r   r  r\  r  s           r8  
set_marginzbitfinex2.set_margin  s     	V$$f~ 	Stw)QQRRRTl//77
 
 ::4;;wPV;W;WXX x++--dF;;;r9  c                 L    |d         }|dk    rdnd}||d         d dd d d |d d d
S )Nr   r   rR  r  rK  rF  )
rX  rK  rn  r  rG  r  r<  rT  r  r  r@  )r6  r  r   marginStatusRawmarginStatuss        r8  r  z#bitfinex2.parse_margin_modification  sR     q' /1 4 4tt8X&$"
 
 	
r9  c                    |                                   d|                     |          gi}d}d}|*|                     |                     ||                    }nI|                     |          }|d         |d<   |                     |                     ||                    }|                     |d          }|                     ||          S )a  
        fetches information on an order made by the user
        :see: https://docs.bitfinex.com/reference/rest-auth-retrieve-orders
        :see: 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>`
        r1   NrK  r   )r  r  r  r  r   r  r  r  )r6  r1   rK  r[  r  r   r\  r-  s           r8  fetch_orderzbitfinex2.fetch_order	  s     	4((,,-
 >224;;w3O3OPPHH[[((F &tGH88Wf9U9UVVHN x++v...r9  c                 0   |                                   |                     |          }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           }|                     ||          S )$a  
        edit a trade order
        :see: 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 that the order is to be fullfilled, in units of the quote currency, ignored in market orders
        :param dict [params]: extra parameters specific to the exchange API endpoint
        :param float [params.stopPrice]: 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>`
        r1   NrX  rG  r  r  r  r  r  Fr  r  r  r  rN  r   r  r  r   r   r  r  r  rw  lev)r  r  r  r  r  r  r  rw  rd  r  r  r  rD  r  r  r  rf  )r  r   r  rL  r-   rZ  r  rZ  r  safe_integer_2rO  r  r  privatePostAuthWOrderUpdater  r   r1   r  r  )r6  r1   rK  rn  r/  rG  rN  r[  r   r  r`  r  r  r  r  r  r  r  r  rw  r\  rT  r  r  r-  s                            r8  
edit_orderzbitfinex2.edit_orderH  s   ( 	V$$$''++
 33FFCCL,0EMM<<@RS_@`@`L ,GH&&v{NKK	))&2BCC&&v}==vz5AA^^FL%@@
++FE?KK%(6G$%%"#66vyIIGGw-1-D-DVU-S-S)*!:kT&9H9#4#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//v...r9  ra  )`__name__
__module____qualname__r4  r=  rA  rE  rL  rO  r^  r   r
   r  r   r  r  r   r  rk  floatr   r   r   r
  r  r  r   r   r0  r   rG  r   r   rQ  rT  r   rh  rv  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   r@  r_  r$  rv  r~  r  r  r  r  r  r  r  r  r  r  r  r  r  r	   r  r  r  r  __classcell__)r7  s   @r8  r/   r/   !   s       i i i i iV- - -  S S Sx x xM M M #% 
 
 
 
* $& x x$v, x x x xt ') v vZ v v v vpD D D( $& %) %)( %) %) %) %)N [] ?7 ?7S ?7% ?7c ?7c ?7an ?7 ?7 ?7 ?7B(
 (
 (
 (
 (
 (
T: : :  , :>b ' 's '3 'Y ' ' ' 'RA A6 AV A A A AF 04B ?G ?GW ?G7 ?G ?G ?G ?GB 02 1 13 1f 1 1 1 1 N N N5 N N N N` 6:UW )> )>3 )>s )># )>\`af\g )> )> )> )>V 26DWZce (L (L# (Lc (LQT (Ljnosjt (L (L (L (LT
 
 
4 
 
 
 
(9 9 9&8 8 8> > >: : :5 : : : :x os{} L, L,3 L,i L,y L,Z_ L,hk L, L, L, L,\ gksu O/ O/3 O/i O/y O/RW O/`c O/ O/ O/ O/b @B 7* 7*D$6 7* 7* 7* 7*r /32 ) ) ) ) ) )  37r ' 's 'C ' ' ' ': 04B F1 F1 F1 F1 F1 F1P 7;2  3     & 9=R  S #    & /3TXac ;A ;A ;A3 ;Ac ;Ahlmrhs ;A ;A ;A ;Az 154VZce GA GA# GAS GAPS GAjnotju GA GA GA GAR 9=4^bkm A AS A# AS AX[ A A A A0 -1tRV_a A Ac A AC A A A A: 8: N N3 N N N N 79 7
 7
# 7
 7
 7
 7
r: : : A
 A
x A
; A
 A
 A
 A
F )+ j j{ j j j jX 6:[_hj 5I 5Is 5I# 5IUX 5Iost  pA 5I 5I 5I 5In ?C2 Q QS Q% Q Q Q Qf 26b -7 -7w -7 -7 -7 -7^C Cv C C C CJ# # # &eBSW P P P P2  0  $,
 ,
 ,
 ,
 ,
 ,
\ (,$TZ\ .C .C .CC .Cs .C .C .C .C` 68 : : : : : : 6:" .2 .27 .2 .2 .2 .2` 8<$]ajl E E EC EWZ E E E EN2
 2
6 2
 2
 2
 2
h0
 0
6 0
 0
 0
 0
d 79 -4 -4# -4 -4 -4 -4^ BFTXgktv 9I 9I# 9Ic 9Iad 9I 9I 9I 9IvF FF F F F FP <@d[] -G -G -GS -G -G -G -G -G^$ $V $ $ $ $L =? < < <e <CU < < < <8
 
>P 
 
 
 
2 26b =/ =/c =/3 =/ =/ =/ =/~ `drv  @B o/ o/S o/# o/Y o/i o/Y\ o/lo o/ o/ o/ o/ o/ o/ o/ o/r9  r/   )4ccxt.base.exchanger   ccxt.abstract.bitfinex2r   rp  ccxt.base.typesr   r   r   r   r	   r
   r   r   r   r   r   r   r   r   r   r   r   r   r   r   typingr   ccxt.base.errorsr   r   r   r   r   r   r    r!   r"   r#   r$   r%   r&   r'   r(   ccxt.base.decimal_to_precisionr)   r*   r+   r,   ccxt.base.preciser-   r/   r@  r9  r8  <module>r     s   ( ' ' ' ' ' / / / / / /  f  f  f  f  f  f  f  f  f  f  f  f  f  f  f  f  f  f  f  f  f  f  f  f  f  f  f  f  f  f  f  f  f  f  f  f  f  f  f  f  f  f  f  f       * * * * * * 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 = = = = = = % % % % % %V6/ V6/ V6/ V6/ V6/+ V6/ V6/ V6/ V6/ V6/r9  