
    !:hF                    P   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 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,  G d dee      Z-y)    )Exchange)ImplicitAPIN)AnyBalances
CurrenciesCurrencyDepositAddressIntMarketNumOrder	OrderBook	OrderSide	OrderTypeStrStringsTickerTickersTradeTradingFeesTransaction)List)ExchangeError)AuthenticationError)PermissionDenied)ArgumentsRequired)
BadRequest)InsufficientFunds)InvalidOrder)OrderNotFound)NotSupported)RateLimitExceeded)ExchangeNotAvailable)OnMaintenance)InvalidNonce)	TICK_SIZE)Precisec                   8    e Zd Zdef fdZi fdefdZi fdZi fdee	   fdZ
i fdZd Zi fdZi fd	Zde	fd
Zdi fdededefdZi fdefdZi fdefdZi fdefdZi fdedefdZdEdede	defdZdi fdedefdZdEdede	defdZddi fdedededee   fdZ de!fdZ"i fde#fdZ$i fde!fdZ%dEdede	de&fd Z'di fd!ede(fd"Z)dddi fde(dededee&   fd#Z*di fded$e+d%e,d&e-d'e.f
d(Z/di fd!ede(fd)Z0dddi fde(dedefd*Z1di fd+ed&e-d,ede2fd-Z3d. Z4dddi fd+e(dededee2   fd/Z5dEd0ed1e6de2fd2Z7d3e(fd4Z8dEd1e6fd5Z9i fd+ede:fd6Z;i fd+edee:   fd7Z<d8d9i ddfd:Z=d;e>d<ed=ed>ed?ed@efdAZ?i fd+ede:fdBZ@dCddi fdedededeeA   fdDZB xZCS )Fgeminireturnc                 :   | j                  t        t        |          i ddddddgddd	d
dddi dd ddddddddddddddddddddddddddddddddi d dd!dd"dd#dd$dd%dd&dd'dd(dd)dd*dd+dd,dd-dd.dd/dd0di d1dd2dd3dd4dd5dd6dd7dd8dd9dd:dd;dd<dd=dd>dd?dd@ddAddddddBddddddddCdDdEdFdFdGdHdIdJdKdLgdMdMdGdHdIg dNdOdPdQdRgidQdSgidQdTdTdTdTdTdTdTdTdTdTdTdTdUidVi dWdXdYdXdZdXd[dXd\dXd]dXd^dXd_dXd`dXdadXdbdXdcdXdddXdedXdfdXdgdXdhdXi didXdjdXdkdXdldXdmdXdndXdodXdpdXdqdXdrdXdsdXdtdXdudXdvdXdwdXdxdXdydXdXdXdXdXdXdXdXdzid{d|t        d}d~dddidt
        t        t        t        t        t        t        t        dddddddddddi dt
        dt
        dt
        dt
        dt
        dt
        dt
        dt        dt
        dt        dt        dt        dt        dt        dt        dt        dt
        t
        t        t        t        t        t        t        t        t        t
        t        t        t        t
        dt        t        t        ddddddg dddddddgddTdddddddddddddddddddddid
ddddd dddd dddddddddddddd ddd d ddÜdddddĜdd ddddŜd d dd idǜ	ddiddid dʜd d dʜd˜      S )Nidr)   nameGemini	countriesUS	rateLimitd   versionv1proThasCORSspotmarginFswapfutureoption	addMargincancelOrdercloseAllPositionsclosePositioncreateDepositAddresscreateMarketOrdercreateOrdercreateReduceOnlyOrderfetchBalancefetchBidsAsksfetchBorrowRateHistoriesfetchBorrowRateHistoryfetchClosedOrdersfetchCrossBorrowRatefetchCrossBorrowRatesfetchCurrenciesfetchDepositAddressfetchDepositAddressesfetchDepositAddressesByNetworkfetchDepositsWithdrawalsfetchFundingHistoryfetchFundingRatefetchFundingRateHistoryfetchFundingRatesfetchIndexOHLCVfetchIsolatedBorrowRatefetchIsolatedBorrowRatesfetchLeveragefetchLeverageTiersfetchMarginModefetchMarketsfetchMarkOHLCVfetchMyTrades
fetchOHLCVfetchOpenInterestHistoryfetchOpenOrders
fetchOrderfetchOrderBookfetchOrdersfetchPositionfetchPositionModefetchPositionsfetchPositionsRiskfetchPremiumIndexOHLCVfetchTickeremulated)fetchTickersfetchTradesfetchTradingFeefetchTradingFeesfetchTransactionspostOnlyreduceMarginsandboxsetLeveragesetMarginModesetPositionModewithdrawurlszchttps://user-images.githubusercontent.com/1294454/27816857-ce7be644-6096-11e7-82d6-3c257263229c.jpgzhttps://api.gemini.comzhttps://docs.gemini.comzhttps://exchange.gemini.com)publicprivatewebwebExchangezhttps://gemini.com/z https://docs.gemini.com/rest-apizhttps://docs.sandbox.gemini.comzhttps://api.sandbox.gemini.com)z#https://gemini.com/api-fee-schedulezhttps://gemini.com/trading-feesz https://gemini.com/transfer-fees)logoapiwwwdoctestfeesr}   get zrest-api   )z
v1/symbolszv1/symbols/details/{symbol}zv1/staking/rateszv1/pubticker/{symbol}zv2/ticker/{symbol}zv2/candles/{symbol}/{timeframe}zv1/trades/{symbol}zv1/auction/{symbol}zv1/auction/{symbol}/historyzv1/pricefeedzv1/book/{symbol}zv1/earn/ratespostzv1/staking/unstake   zv1/staking/stakezv1/staking/rewardszv1/staking/historyzv1/order/newzv1/order/cancelzv1/wrap/{symbol}zv1/order/cancel/sessionzv1/order/cancel/allzv1/order/statusz	v1/orderszv1/mytradeszv1/notionalvolumezv1/tradevolumezv1/clearing/newzv1/clearing/statuszv1/clearing/cancelzv1/clearing/confirmzv1/balanceszv1/balances/stakingzv1/notionalbalances/{currency}zv1/transferszv1/addresses/{network}zv1/deposit/{network}/newAddressz v1/deposit/{currency}/newAddresszv1/withdraw/{currency}zv1/account/transfer/{currency}zv1/payments/addbankzv1/payments/methodszv1/payments/sen/withdrawzv1/balances/earnzv1/earn/interestzv1/earn/historyz&v1/approvedAddresses/{network}/request)z&v1/approvedAddresses/account/{network}z%v1/approvedAddresses/{network}/removez
v1/accountzv1/account/createzv1/account/listzv1/heartbeatzv1/roles)r{   rz   rx   ry   precisionModer   tradinggMbp?gMb`?)takermakerhttpExceptions)400403404406429500502503
timeframes1m5m15m30m1hr6hr1day)r   r   r   r   1h6h1d
exceptionsAuctionNotOpenClientOrderIdTooLongClientOrderIdMustBeStringConflictingOptionsEndpointMismatchEndpointNotFoundIneligibleTimingr   InvalidJsonr%   InvalidApiKeyInvalidOrderTypeInvalidPriceInvalidQuantityInvalidSideInvalidSignatureInvalidSymbol)InvalidTimestampInPayloadMaintenanceMarketNotOpenMissingApikeyHeaderMissingOrderFieldMissingRoleMissingPayloadHeaderMissingSignatureHeaderNoSSLOptionsMustBeArrayr    	RateLimitSystemUnsupportedOption)z8The Gemini Exchange is currently undergoing maintenance.z?We are investigating technical issues with the Gemini Exchange.zInternal Server Error)exactbroadoptionsfetch_markets_from_api
   )USDTGUSDUSDDAIEURGBPSGDBTCETHLTCBCHSOL)fetchDetailsForAllSymbolsquoteCurrencies)webApiEnablewebApiRetriesbtcusdtethusdt)r   r   webApiMuteFailurefetchTickerV1bitcoinethereumbitcoincashlitecoinzcashfilecoindogecointezos	avalanchesolanacosmospolkadot)r   ERC20r   r   ZECFILDOGEXTZAVAXXr   ATOMDOTmillisecondspaxgusdPAXGr   )basequote)
fetchMarketsMethodfetchMarketFromWebRetriesfetchMarketsFromAPIr[   fetchUsdtMarketsrL   fetchTickerMethodnetworksnonceconflictingMarketsfeatures)IOCFOKPOGTD)
marginModetriggerPricetriggerPriceTypetriggerDirectionstopLossPricetakeProfitPriceattachedStopLossTakeProfittimeInForcehedgedtrailingleveragemarketBuyByCostmarketBuyRequiresPriceselfTradePreventioniceberg  )r   limitdaysBack	untilDayssymbolRequired)r   triggerr  r  )r   r  r  r  r  r  )	rr   rC   createOrdersr]   ra   r`   rc   rI   r^   extendsdefault)linearinverse)r  r8   r:   r;   )deep_extendsuperr)   describer&   r   r   r    r   r"   r   r#   r$   r%   r   r   )self	__class__s    E/var/www/html/turnos/venv/lib/python3.12/site-packages/ccxt/gemini.pyr  zgemini.describe   s	   fd < > \A
(\A
H\A
 $\A
 \A
 t\A
 4\A
  @@@ %@ 	@
 %@ %@ U@ t@ $U@  @ '@ $U@ t@ (@ @   !@" +E#@$ )%%@& $U'@( ')@* (+@, "4-@. &t/@0 (1@2 1$3@4 +D5@6 &u7@8 #E9@: *5;@< $U=@> "5?@@ *5A@B +EC@D  E@F %eG@H "5I@J K@L !%M@N  O@P dQ@R +ES@T "4U@V dW@X !$Y@Z u[@\  ]@^ $U_@` !%a@b %ec@d )%e@f tg@h !%##($(%/  %$!&#( @\A
T }674#@	 -65
 ??
 5#@	/U\A
N   " &'78,-12./;<.//078(),-)*"  *,a**A* -a* -a	*
 '* *1* +A* 21* .q* *1* $Q* &q* ,Q* )!* *1*  -a!*" -a#*$ .q%*& &q'*( .q)** 9!+*, '-*. 1!/*0 :11*2 ;A3*4 1!5*6 9!7*8 .q9*: .q;*< 3A=*> +A?*@ +AA*B *1C*D A!E*F CDAB&'-.+,()$%S*,7HO\A
` Ya\A
b ""c\A
n !'$(($+$	o\A
B C\A
T  $j *J  0  )*	 
 '
  '
  '
  ():  ":  #L  $%8  '  #L  &|  "<   '(;! " $Z# $ 2<#0%1+>)5#6,?.A0*4%2!2+)3? D Q^Wk-AE'U\A
d &>-/16'}(
 %)%'! &/	$:$(%&)-$
 &5$'(%"%&"(#$% ( &!& 'C'e\A
t #&+(,,0,1).+06:#'#'"&#(	( #($)$)+/27/4#()$, %)&+!$$(%)*.& ',#($)*/	# ',!%#($)*/( $()-#_2h y
 "9  $	 ##{Au\A
 \ \	    c                 $    | j                  |      S )z
        fetches all available currencies on an exchange
        :param dict [params]: extra parameters specific to the endpoint
        :returns dict: an associative dictionary of currencies
        )fetch_currencies_from_web)r  paramss     r  fetch_currencieszgemini.fetch_currencies}  s     --f55r  c                    | j                  ddddd      }|yi }| j                  |d      | j                  d<   | j                  |dg       }t	        d	t        |            D ]  }||   }| j                  |d	      }| j                  |      }| j                  |d
      rdnd}	| j                  | j                  | j                  |d                  }
i }| j                  |d      }d}|)| j                  |      }|||dddd|
dddddddd	||<   | j                  |||| j                  |d      dddd|	|
ddddddd|d      ||<    |S )z
 @ignore
        fetches all available currencies on an exchange
        :param dict [params]: extra parameters specific to the endpoint
        :returns dict: an associative dictionary of currencies
        rL   webExchangeGetTz="currencyData">z	</script>NtradingPairs
currenciesr      fiatcryptor   	   minmax)depositrv   )	infor,   networkactiver+  rv   fee	precisionlimitsr   )r,  r,   coder-   r.  r+  rv   r/  typer0  r1  r   )fetch_web_endpoint	safe_listr   
safe_valuerangelensafe_stringsafe_currency_codeparse_numberparse_precisionnetwork_id_to_codesafe_currency_structure)r  r  dataresultcurrenciesArrayicurrencyr,   r2  r3  r0  r   	networkIdnetworkCodes                 r  r  z gemini.fetch_currencies_from_web  s    &&'8:JDRdfqr<* '+~~dN'K^$//$bAq#o./ 5	A&q)H!!(A.B**2.D!--h:6D))$*>*>t?O?OPXZ[?\*]^IH((15IK$"55i@$#*"# $!* $(#'$
 $(#'%	)%(  77 ((15 &  $# 
  $#!	 %+9 F4L?5	l r  c                     | j                  | j                  dd      }|dk(  r\g }|j                  | j                  |             |j                  | j	                  |             |}| j                  |d   |d         S | j                  |      S )a	  
        retrieves data on all markets for gemini

        https://docs.gemini.com/rest-api/#symbols

        :param dict [params]: extra parameters specific to the exchange API endpoint
        :returns dict[]: an array of objects representing market data
        r   r   fetch_markets_from_webr   r   )r6  r   appendrG  fetch_usdt_marketsarray_concatr   )r  r  methodpromisespromisesResults        r  fetch_marketszgemini.fetch_markets  s     /CE]^--HOOD77?@OOD33F;<%N$$^A%6q8IJJ**622r  c                    | j                  dddd      }| j                  dz   }|j                  d      }t        |      }|dk  rt	        |      |d   j                  d	      }t        |      }|dk  rt	        |      g }t        d|      D ]  }	||	   }
|
j                  d
      }t        |      }|dk  rt	        |      |d   j                  dd      }|j                  dd      }|d   j                  dd      }|j                  d      }| j                  |d      }|d   j                  dd      }|j                  d      }t        |      dz
  }|dz
  }|d   j                  dd      }|j                  d      }| j                  |d|||       }| j                  |d|j                  |d            }| j                  |      }| j                  |      }|j                  i d|d|dz   |z   d|d|dd d|d|dd ddddddddd dd!dd"d d#dd$d d d d d d d | j                  |d      | j                  |d      d%d d d&|d d&d d d&d d d&d'd |
d(
        |S ))Nr[   webGetRestApiFz7<h1 id="symbols-and-minimums">Symbols and minimums</h1>z fetchMarketsFromWeb() the API doc HTML markup has changed, breaking the parser of order limits and precision info for markets.ztbody>   r   z
<tr>
z</td>
r   r   z<td>r   *    r,   symbol/r   r   settlebaseIdquoteIdsettleIdr3  r8   Tr9   r:   r;   r<   r.  contractr  )amountpricer(  r  r\  r]  cost
r  contractSizeexpiryexpiryDatetimestrike
optionTyper0  r1  createdr,  )r4  r,   splitr8  r!   r7  replacesafe_numbersafe_string_lowerr:  rH  )r  r  r?  errortables	numTablesrowsnumRowsr@  rB  rowcellsnumCellsmarketIdminAmountStringminAmountParts	minAmountamountPrecisionStringamountPrecisionPartsidLengthstartingIndexpricePrecisionStringpricePrecisionPartsrY  rX  r   r   s                              r  rG  zgemini.fetch_markets_from_web  sp   &&~  PI  J  \  \H%K	q=u%%ayz*d)Q;u%%q'" M	Aq'CIIi(E5zH!|"5)) Qx''3H''R0H#Ah..vr:O,2237N((;I$)!H$4$4VR$@!#8#>#>s#C 8}q(H$qLM#(8#3#3FB#? "6"<"<S"A,,-@!Xm\dEefG++,@!XEUEUV]_aEbcF**62D++G4EMM 0h0$*u,0 0 	0
 $0 &0 70 D0 0 0 %0 0 %0 %0 $0  E!0" $#0$   $"&""../CQG!--.A1E  $#!
  )#
  $#
  $#$  _0 0;M	\ r  c                 >    dddddd}|y| j                  ||d      S )NTF)openclosedcancel_only	post_only
limit_only)	safe_boolr  statusstatusess      r  parse_market_activezgemini.parse_market_activeM  s5    
 >~~h55r  c                 ,   d| j                   v rg S | j                  | j                  dg       }g }t        dt	        |            D ]L  }||   }d|i}| j                  | j                  ||            }|j                  | j                  |             N |S )Nr   r   r   rU  )	rw   r6  r   r7  r8  publicGetV1SymbolsDetailsSymbolextendrH  parse_market)r  r  r   r@  rB  rs  requestrawResponses           r  rI  zgemini.fetch_usdt_marketsY  s     TYYI??4<<9KRPq#./0 	:A'*H(G >>t{{7TZ?[\KMM$++K89	: r  c           	         | j                  |      }g }| j                  | j                  di       }d}g }t        dt	        |            D ]  }||   |k7  s|j                  ||          ! | j                  |dd      rg }t        dt	        |            D ];  }||   }	d|	i}
|j                  | j                  | j                  |
|                   = |}t        dt	        |            D ]%  }|j                  | j                  ||                ' |S | j                  | j                  d      }|v| j                  |d      }t        dt	        |            D ]J  }||   }	| j                  ||	j                               }|+|j                  | j                  |             L |S t        dt	        |            D ]%  }|j                  | j                  ||                ' |S )Nr   efilfilr   r   FrU  r"  )publicGetV1Symbols	safe_dictr   r7  r8  rH  r  r  r  r  r5  index_byupper)r  r  marketIdsRawr@  r   	bugSymbol	marketIdsrB  rL  rs  r  	responsesr"  indexedTradingPairstradingPairs                  r  r   zgemini.fetch_markets_from_apij  s   ..v6 ../DbI		q#l+, 	2AA)+  a1	2 >>'#>FH1c)n- d$Q<h!  D DT[[QXZ`Ea bcd$ !I1c)n- ?d//	!=>?   >>$,,GL'&*mmL!&D#q#i.1 FA(|H"&..1DhnnFV"WK".d&7&7&DE	F  q#i.1 CAMM$"3"3IaL"ABCr  c                    d }d }d }d }d }d }d }d }	d}
d }d }d }t        |t              }t        |t              }|s|s| j                  |d      }| j	                  |d      }| j	                  |d      }| j	                  |d      }| j                  | j                  |d            }	| j                  |d      }| j                  |d      }| j                  |d	      }nt|r|}n| j                  |d
      }| j                  | j                  | j                  |d                  }| j                  | j                  | j                  |d                  }| j	                  |d      }|j                         }|j                  d      d
k\  }|j                  dd      }| j                  | j                  di       }|j                         }||v r||   }|d   }|d   }|rs|d   }nm| j                  ddg       }t!        d
t#        |            D ]B  }||   }|j%                  |      s| j'                  dt#        |      z        }|d
| }|}|r|} n | j)                  |      }| j)                  |      }| j)                  |      }|dz   |z   }||dz   |z   }d}
|}d}d}|
rdnd}i d|d|d|d|d|d|d|d|d |d|
 d!dd|
d"dd#dd$|	d%|
d&|||d d d d ||d'd d d(|d d(d d d(d d d(d)d |d*
S )+NFrU  	tick_sizequote_incrementmin_order_sizer  base_currencyquote_currencycontract_price_currencyr   r   rQ  rT  PERPr   r   r   r   r   r   rV  :Tr:   r8   r,   rW  rX  rY  rZ  r3  r9   r;   r<   r.  r[  r  )r]  r\  r(  r^  r`  )
isinstancestrlistrj  ri  r  r9  r;  r<  r  findrh  r  r   lowerhandle_optionr7  r8  endswithparse_to_intr:  )r  responsers  rX  rY  rZ  tickSizeamountPrecisionminSizer  r:   ra  r  r  isStringisArraymarketIdUpperisPerpmarketIdWithoutPerpr   lowerCaseIdconflictingMarketr   rB  quoteCurrencyquoteLengthr   r   rW  rU  r3  s                                  r  r  zgemini.parse_market  s:   B x-h---hAH"..xEO''2CDH&&x1ABG--d.>.>x.RSF%%h@F&&x1ABG''2KLH #11(A>,,T-A-A$BRBRS[]^B_-`a"&"3"3D4H4HIYIYZbdeIf4g"h**8Q7$NN,M#((0A5F"/"7"7"C!%>RTV!W-335K00$6{$C!*62+G409H"&"4"45JL]_a"bq#o"67 A$3A$6M*33MB&*&7&7S=O8O&P!4Q{!C"/!'4H &&v.''0((2e#c\F*FD#LFGv60
(0
f0
 D0
 U	0

 f0
 f0
 w0
 0
 D0
 H0
 e0
 D0
 e0
 e0
 f0
  !0
" f#0
$ ("!)  
 #
  
  $ _0
 0	
r  NrU  r  c           	          | j                          | j                  |      }d|d   i}|
||d<   ||d<   | j                  | j                  ||            }| j	                  ||d   ddddd	      S )
a2  
        fetches information on open orders with bid(buy) and ask(sell) prices, volumes and other data

        https://docs.gemini.com/rest-api/#current-order-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
        :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
        rU  r,   N
limit_bids
limit_asksbidsasksr]  r\  )load_marketsmarketpublicGetV1BookSymbolr  parse_order_book)r  rU  r  r  r  r  r  s          r  fetch_order_bookzgemini.fetch_order_book4  s     	V$fTl
 $)GL!$)GL!--dkk'6.JK$$Xvh/?vvW^`hiir  c                     | j                          | j                  |      }d|d   i}| j                  | j                  ||            }| j	                  ||      S NrU  r,   )r  r  publicGetV1PubtickerSymbolr  parse_tickerr  rU  r  r  r  r  s         r  fetch_ticker_v1zgemini.fetch_ticker_v1J  s^    V$fTl
 224;;w3OP   622r  c                     | j                          | j                  |      }d|d   i}| j                  | j                  ||            }| j	                  ||      S r  )r  r  publicGetV2TickerSymbolr  r  r  s         r  fetch_ticker_v2zgemini.fetch_ticker_v2_  s^    V$fTl
 //GV0LM   622r  c                     | j                  ||      }| j                  ||      }||g\  }}| j                  ||d   |d   |d   |d   |d   |d   |d   d      S )	Nr~  highlowchange
percentageaverager,  )r~  r  r  r  r  r  r,  )r  r  r  )r  rU  r  tickerPromiseAtickerPromiseBtickerAtickerBs          r  fetch_ticker_v1_and_v2zgemini.fetch_ticker_v1_and_v2u  s    --ff=--ff=*N;FOFO5>h'!,/y)FO*
  	r  c                     | j                  | j                  dd      }|dk(  r| j                  ||      S |dk(  r| j                  ||      S | j	                  ||      S )a  
        fetches a price ticker, a statistical calculation with the information calculated over the past 24 hours for a specific market

        https://docs.gemini.com/rest-api/#ticker
        https://docs.gemini.com/rest-api/#ticker-v2

        :param str symbol: unified symbol of the market to fetch the ticker for
        :param dict [params]: extra parameters specific to the exchange API endpoint
        :param dict [params.fetchTickerMethod]: 'fetchTickerV2', 'fetchTickerV1' or 'fetchTickerV1AndV2' - 'fetchTickerV1' for original ccxt.gemini.fetchTicker - 'fetchTickerV1AndV2' for 2 api calls to get the result of both fetchTicker methods - default = 'fetchTickerV1'
        :returns dict: a `ticker structure <https://docs.ccxt.com/#/?id=ticker-structure>`
        r   r   fetchTickerV2)r6  r   r  r  r  )r  rU  r  rK  s       r  fetch_tickerzgemini.fetch_ticker  sd     /BOT_$''77_$''77**66::r  tickerr  c                    | j                  |di       }| j                  |d      }d }| j                  |d      }| j                  ||      }d }d }d }	d }
|T|Rt	        |      dz
  }|dk(  r|dd }|dd }n
|dd }|dd }| j                  |      }	| j                  |      }
|	d	z   |
z   }|+|)|d
   }| j                  |d      }| j                  |d      }| j                  |d      }| j                  |dd|      }| j                  |d      }| j                  |d      }| j                  ||      }| j                  ||      }| j                  i d
|d|d| j                  |      d| j                  |d      d| j                  |d      d| j                  |d      dd d| j                  |d      dd dd d|d|d|dd dd d|dd |||d|      S )Nvolume	timestamppairr   r$     rT     rV  rU  rX  rY  r]  lastclosepercentChange24hr~  datetimer  r  bid	bidVolumeask	askVolumevwappreviousCloser  r  r  )
baseVolumequoteVolumer,  )r6  safe_integerrj  safe_marketr8  r:  safe_string_upperr9  safe_string_2safe_tickeriso8601)r  r  r  r  r  rU  rs  rX  rY  r   r   ry  r]  r  r  r~  r  r  s                     r  r  zgemini.parse_ticker  s   J 26%%fk:	))&&9!!(F3 v~8}q(H1}!!A"1Q-!!A"1Q-**62D++G4ECZ%'FN!3H%F++FH=F,,VY?G  1!!&&'5A%%f.@A
/%%ff5
&&vw7 !
f!
!
 Y/!
 D$$VV4	!

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

        https://docs.gemini.com/rest-api/#price-feed

        :param str[]|None symbols: unified symbols of the markets to fetch the ticker for, all market tickers are returned if not assigned
        :param dict [params]: extra parameters specific to the exchange API endpoint
        :returns dict: a dictionary of `ticker structures <https://docs.ccxt.com/#/?id=ticker-structure>`
        )r  publicGetV1Pricefeedparse_tickers)r  r  r  r  s       r  fetch_tickerszgemini.fetch_tickers  s5     	,,V4 !!(G44r  tradec                    | j                  |d      }| j                  |d      }| j                  |d      }| j                  |d      }| j                  |      }| j                  |d      |d}| j                  |d      }	| j                  |d      }
| j                  |d	      }| j	                  d |      }| j                  ||||| j                  |      |d |d |	d |
|d
|      S )Ntimestampmstidorder_idfee_currency
fee_amountr_  rC  r]  r\  r3  )r,   orderr,  r  r  rU  r3  sidetakerOrMakerr]  r_  r\  r/  )r  r9  r:  rj  safe_symbol
safe_trader  )r  r  r  r  r,   orderIdfeeCurrencyIdfeeCurrencyCoder/  priceStringamountStringr  rU  s                r  parse_tradezgemini.parse_trade  s   D %%e];	eU+""5*5((?11-@$$UL9'
 &&ug6''x8%%eV4!!$/"Y/  " 
  	r  sincec                     | j                          | j                  |      }d|d   i}|t        |d      |d<   |||d<   | j                  | j	                  ||            }| j                  ||||      S )a  
        get the list of most recent trades for a particular symbol

        https://docs.gemini.com/rest-api/#trade-history

        :param str symbol: unified symbol of the market to fetch trades for
        :param int [since]: timestamp in ms of the earliest trade to fetch
        :param int [limit]: the maximum amount of trades to fetch
        :param dict [params]: extra parameters specific to the exchange API endpoint
        :returns Trade[]: a list of `trade structures <https://docs.ccxt.com/#/?id=public-trades>`
        rU  r,   r
  limit_tradesr  )r  r  r)  publicGetV1TradesSymbolr  parse_tradesr  rU  r  r  r  r  r  r  s           r  fetch_tradeszgemini.fetch_tradesK  s     	V$fTl
 &)%oGN##(GK //GV0LM   65%@@r  c                 .   d|i}t        dt        |            D ]i  }||   }| j                  |d      }| j                  |      }| j	                         }| j                  |d      |d<   | j                  |d      |d<   |||<   k | j                  |      S )Nr,  r   rC  	availablefreer\  total)r7  r8  r9  r:  accountsafe_balance)r  r  r@  rB  balance
currencyIdr2  r  s           r  parse_balancezgemini.parse_balancep  s    )q#h-( 	#AqkG))':>J**:6DllnG"..wDGFO#//BGG"F4L	#   ((r  c                    | j                          | j                  |      }| j                  |d      }| j                  |d      }t        j                  |d      }t        j                  |d      }| j                  |      }| j                  |      }i }	t        dt        | j                              D ]  }
| j                  |
   }||||ddd|	|<    |	S )aP  
        fetch the trading fees for multiple markets

        https://docs.gemini.com/rest-api/#get-notional-volume

        :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
        api_maker_fee_bpsapi_taker_fee_bps10000r   T)r,  rU  r   r   r  	tierBased)	r  privatePostV1Notionalvolumer9  r'   
string_divr;  r7  r8  r  )r  r  r  makerBpstakerBpsmakerStringtakerStringr   r   r@  rB  rU  s               r  fetch_trading_feeszgemini.fetch_trading_fees|  s     	33F;: ##H.AB##H.AB((7;((7;!!+.!!+.q#dll+, 		A\\!_F  "!F6N		 r  c                 f    | j                          | j                  |      }| j                  |      S )ad  
        query for balance and get the amount of funds available for trading or funds locked in orders

        https://docs.gemini.com/rest-api/#get-available-balances

        :param dict [params]: extra parameters specific to the exchange API endpoint
        :returns dict: a `balance structure <https://docs.ccxt.com/#/?id=balance-structure>`
        )r  privatePostV1Balancesr  )r  r  r  s      r  fetch_balancezgemini.fetch_balance  s1     	--f5!!(++r  r   c                 H   | j                  |d      }| j                  |d      }| j                  |d      }| j                  |d      }d}|d   rd}|d   rd	}| j                  |d
      }| j                  |d      }	| j                  |d      }
|
dk(  rd}
n|
dk(  s|
dk(  rd}
n|d   }
d }| j                  |d      }| j                  ||      }| j                  |d      }| j                  |d      }| j                  |d      }| j	                  |dg       }| j                  |d      }d}d}||dk(  rd}n|dk(  rd}n	|dk(  rd}d }| j                  i d!|d"|d#|d$|d%| j                  |      d&d d'|d|d|
d(|d)|d|d
|d*d d+|	d,d d-||||d d.|      S )/Nr  original_amountremaining_amountexecuted_amountr  is_liver~  is_cancelledcanceledr]  avg_execution_pricer3  exchange limitr  z
market buyzmarket sellr  rU  r  r  client_order_idr   r   GTCFimmediate-or-cancelr   fill-or-killr   maker-or-cancelr   Tr,   clientOrderIdr,  r  r  lastTradeTimestampr  r  rp   r   r  r_  r\  )filled	remainingr/  trades)r  r9  r  rj  r6  
safe_orderr  )r  r   r  r  r\  r;  r:  r  r]  r  r3  r/  rs  rU  r,   r  r8  optionsArrayr<   r  rp   s                        r  parse_orderzgemini.parse_order  s   F %%e];	!!%):;$$U,>?	!!%):;F F  0""5*?@v.##D\!T]%:D=D##E84!!(F3eZ0%%eV4((0ABui<!!,2..#>)#,,"  
" 
] 
 E 
 	 

 Y/ 
 !$ 
 f 
 f 
 D 
 ; 
  
 D 
 U 
 D 
 w 
  D! 
" f# 
$ "+ 
, - 	r  r,   c                     | j                          d|i}| j                  | j                  ||            }| j                  |      S )a  
        fetches information on an order made by the user

        https://docs.gemini.com/rest-api/#order-status

        :param str id: order id
        :param str symbol: unified symbol of the market the order was made in
        :param dict [params]: extra parameters specific to the exchange API endpoint
        :returns dict: An `order structure <https://docs.ccxt.com/#/?id=order-structure>`
        r  )r  privatePostV1OrderStatusr  r?  r  r,   rU  r  r  r  s         r  fetch_orderzgemini.fetch_orderb  sL     	
 00Wf1MN0 ))r  c                     | j                          | j                  |      }d}|| j                  |      }| j                  ||||      S )a  
        fetch all unfilled currently open orders

        https://docs.gemini.com/rest-api/#get-active-orders

        :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>`
        N)r  privatePostV1Ordersr  parse_orders)r  rU  r  r  r  r  r  s          r  fetch_open_orderszgemini.fetch_open_orders  sR     	++F34 [[(F  65%@@r  r3  r  r\  r]  c                    | j                          |dk7  rt        | j                  dz         | j                  |dd      }| j	                  |ddg      }|t        | j                               }| j                  |      }| j                  ||      }	| j                  ||      }
||d   |	|
|dd}| j                  |d|      }| j	                  |d      }| j                  |g d	      }| j	                  |g d
      }|dk(  rt        | j                  dz   |z   dz         || j                  ||      |d<   d|d<   n| j                  |d      }| j	                  |d      }|-|dk(  s|dk(  rdg|d<   n|dk(  s|dk(  rdg|d<   n|dk(  rdg|d<   | j                  |dd      }| j	                  |d      }|rdg|d<   | j                  |d      }||g|d<   | j                  | j                  ||            }| j!                  |      S )a  
        create a trade order

        https://docs.gemini.com/rest-api/#new-order

        :param str symbol: unified symbol of the market to create an order in
        :param str type: must be 'limit'
        :param str side: 'buy' or 'sell'
        :param float amount: how much of currency you want to trade in units of base currency
        :param float [price]: the price at which the order is to be fulfilled, in units of the quote currency, ignored in market orders
        :param dict [params]: extra parameters specific to the exchange API endpoint
        :returns dict: an `order structure <https://docs.ccxt.com/#/?id=order-structure>`
        r  z' createOrder() allows limit orders onlyr8  r3  r,   r2  )r3  rU  r\  r]  r  r3  r3  )r   
stop_price	stopPrice)r   rI  rJ  r3  	stopLimitzO createOrder() requires a triggerPrice parameter or a stop_price parameter for z ordersrI  zexchange stop limitr  r   r5  r   r   r6  r   r7  rp   F)r  r   r,   r  omitr  r   r  amount_to_precisionprice_to_precisionr9  safe_string_nr   r  privatePostV1OrderNewr  r?  )r  rU  r3  r  r\  r]  r  r8  r  r	  r  r  r   r  rp   r   r  s                    r  create_orderzgemini.create_order  sh    	7?*S STT**6?DUV6O5F#GH  1 1 34MV$//?--fe<,Tl" $
 566*))&2]^6#VW;#DGG.$  CG  %G  JS  %S  T  T#$($;$;FL$QGL!3GFO **6=AKYYv}5F&5(k=R.R*?)@GI&!U*~0M*8)9GI& D(*;)<GI&~~fj%@HYYvz2F&7%8	"&&vy9G"&-Y	"--dkk'6.JK0 ))r  c                     | j                          d|i}| j                  | j                  ||            }| j                  |      S )a}  
        cancels an open order

        https://docs.gemini.com/rest-api/#cancel-order

        :param str id: order id
        :param str symbol: unified symbol of the market the order was made in
        :param dict [params]: extra parameters specific to the exchange API endpoint
        :returns dict: An `order structure <https://docs.ccxt.com/#/?id=order-structure>`
        r  )r  privatePostV1OrderCancelr  r?  rB  s         r  cancel_orderzgemini.cancel_order  sL     	
 00Wf1MN2 ))r  c                 0   |t        | j                  dz         | j                          | j                  |      }d|d   i}|||d<   || j	                  |dz        |d<   | j                  | j                  ||            }| j                  ||||      S )a  
        fetch all trades made by the user

        https://docs.gemini.com/rest-api/#get-past-trades

        :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>`
        z+ fetchMyTrades() requires a symbol argumentrU  r,   r  i  r  )r   r,   r  r  r  privatePostV1Mytradesr  r  r  s           r  fetch_my_tradeszgemini.fetch_my_trades8  s     >#DGG.[$[\\V$fTl
 &+GN##'#4#4UT\#BGK --dkk'6.JK  65%@@r  r2  addressc                    | j                  ||      \  }}| j                  |       | j                          | j                  |      }|d   ||d}| j	                  | j                  ||            }| j                  |d      }	|	dk(  r*t        | j                  dz   | j                  |      z         | j                  ||      S )a  
        make a withdrawal

        https://docs.gemini.com/rest-api/#withdraw-crypto-funds

        :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,   )rC  r\  rX  r@  rk  z withdraw() failed: )handle_withdraw_tag_and_paramscheck_addressr  rC  privatePostV1WithdrawCurrencyr  r9  r   r,   jsonparse_transaction)
r  r2  r\  rX  tagr  rC  r  r  r@  s
             r  rv   zgemini.withdrawR  s     99#vFV7#==& 

 55dkk'66RS0 !!(H5W*@ @499XCV VWW%%h99r  c                     | j                  | j                  dd      }|dk(  r| j                         S | j                         S )Nr   r   )r9  r   r   seconds)r  nonceMethods     r  r   zgemini.nonce  s=    &&t||WnM.($$&&||~r  c                     | j                          i }|||d<   |||d<   | j                  | j                  ||            }| j                  |      S )aZ  
        fetch history of deposits and withdrawals

        https://docs.gemini.com/rest-api/#transfers

        :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>`
        limit_transfersr  )r  privatePostV1Transfersr  parse_transactions)r  r2  r  r  r  r  r  s          r  fetch_deposits_withdrawalsz!gemini.fetch_deposits_withdrawals  sb     	).G%&#(GK ..t{{7F/KL&&x00r  transactionrC  c                 D   | j                  |d      }| j                  |d      }| j                  ||      }| j                  |d      }| j                  |d      }| j                  |d      }d }	| j	                  |d      }
|
|
|d}	i d|d	| j                  |d
d      d| j                  |d      d|d| j                  |      dd d|dd dd dd dd dd d|d| j	                  |d      d|d| j                  |      dd d | j                  |d      |	dS )Nr  rC  destinationr3  r  	feeAmountr  r,  r,   eidwithdrawalIdtxidtxHashr  r  r-  rX  	addressToaddressFromr_  tagTotagFromr\  updatedmessage)internalcommentr/  )r  r9  r:  rj  ri  r  r  parse_transaction_status)r  rh  rC  r  r  r2  rX  r3  	statusRawr/  rk  s              r  r^  zgemini.parse_transaction  s   & %%k=A	%%k:>
&&z8<"";>%%k6:$$[(;	$$[+>	 ! C
K
$$$[%H
 D$$[(;
 	

 Y/
 t
 w
 
 4
 4
 T
 t
 D
 d&&{H=
 
  d33I>!
" t#
$ ''Y?)
 	
r  r  c                 2    ddd}| j                  |||      S )Nok)AdvancedComplete)r9  r  s      r  rx  zgemini.parse_transaction_status  s&    
 &&99r  c                 Z    | j                  |d      }| j                  d |      }|d |d |dS )NrX  )rC  r-  rX  r_  r,  )r9  r:  )r  depositAddressrC  rX  r2  s        r  parse_deposit_addresszgemini.parse_deposit_address  sA     "">9=&&tX6"
 	
r  c                     | j                          | j                  ||      }d}| j                  |      \  }}| j                  | j	                  ||      d      }| j	                  ||      S )a  

        https://docs.gemini.com/rest-api/#get-deposit-addresses

        fetch the deposit address for a currency associated with self account
        :param str code: unified currency code
        :param dict [params]: extra parameters specific to the endpoint
        :param str [params.network]:  *required* The chain of currency
        :returns dict: an `address structure <https://docs.ccxt.com/#/?id=address-structure>`
        NrC  )r  "fetch_deposit_addresses_by_networkhandle_network_code_and_paramsr  r6  )r  r2  r  groupedByNetworkrE  networkGroups         r  fetch_deposit_addresszgemini.fetch_deposit_address  sk     	BB4P"AA&IV}}T__5E{%SU_`|T22r  c                 n   | j                          | j                  |      }|d   }d}| j                  |      \  }}|t        | j                  dz         | j                  |      }d|i}| j                  | j                  ||            }| j                  ||gd||d      }| j                  |d      S )a  
        fetch a dictionary of addresses for a currency, indexed by network

        https://docs.gemini.com/rest-api/#get-deposit-addresses

        :param str code: unified currency code of the currency for the deposit address
        :param dict [params]: extra parameters specific to the exchange API endpoint
        :param str [params.network]:  *required* The chain of currency
        :returns dict: a dictionary of `address structures <https://docs.ccxt.com/#/?id=address-structure>` indexed by the network
        r2  Nz5 fetchDepositAddresses() requires a network parameterr-  F)r-  rC  )
r  rC  r  r   r,   network_code_to_idprivatePostV1AddressesNetworkr  parse_deposit_addressesgroup_by)	r  r2  r  rC  rE  rD  r  r  resultss	            r  r  z)gemini.fetch_deposit_addresses_by_network  s     	==&"AA&IV#DGG.e$eff++K8	y
 55dkk'66RS..x$T_mqHrs}}Wi00r  rx   GETc                    d| j                  ||      z   }| j                  || j                  |            }|dk(  r| j                          | j                  }	|	j                  d      dk  rt        | j                  dz         t        | j                               }
| j                  ||
d|      }| j                  |      }| j                  |      }| j                  | j                  |      | j                  | j                        t         j"                        }d| j                  ||d}n|r|d	| j%                  |      z   z  }| j&                  d
   |   |z   }|dk(  s|dk(  r| j                  |      }||||dS )NrV  ry   r  r   z> sign() requires an account-key, master-keys are not-supported)r  r   z
text/plain)zContent-TypezX-GEMINI-APIKEYzX-GEMINI-PAYLOADzX-GEMINI-SIGNATURE?r}   POSTDELETE)urlrK  bodyheaders)implode_paramsrL  extract_paramscheck_required_credentialsapiKeyr  r   r,   r  r   r  r]  string_to_base64hmacencodesecrethashlibsha384	urlencoderw   )r  pathr}   rK  r  r  r  r  queryr  r   r  payload	signatures                 r  signzgemini.sign  sl   D''f55		&$"5"5d";<)++-[[F{{9%))$''4t*tuu

%Ekk# G ii(G++G4G		$++g"6DKK8PRYR`R`aI ,#';;$+&/	G sT^^E222iis#c)f&H"499U#DfdwOOr  httpCodereasonr  rK  r  r  c
                    |Ct        |t              r2| j                  dz   |z   }
| j                  | j                  d   ||
       y | j                  |d      }|dk(  r| j                  |d      }| j                  |d      }| j                  dz   |z   }
| j                  | j                  d   ||
       | j                  | j                  d   ||
       | j                  | j                  d   ||
       t        |
      y )NrS  r   r@  rk  r  ru  r   )r  r  r,   throw_broadly_matched_exceptionr   r9  throw_exactly_matched_exceptionr   )r  r  r  r  rK  r  r  r  requestHeadersrequestBodyfeedbackr@  reasonInnerru  s                 r  handle_errorszgemini.handle_errors;  s    $$77S=4/44T__W5MtU]^ !!(H5W**8X>K&&x;Gww}w.H001I;X`a001I7T\]001I7T\]))r  c                     | j                          | j                  |      }d|d   i}| j                  | j                  ||            }| j	                  |d      }| j                  |       ||dd|dS )a}  
        create a currency deposit address

        https://docs.gemini.com/rest-api/#new-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>`
        rC  r,   rX  N)rC  rX  r_  r-  r,  )r  rC  &privatePostV1DepositCurrencyNewAddressr  r9  r[  )r  r2  r  rC  r  r  rX  s          r  create_deposit_addresszgemini.create_deposit_addressS  s     	==&
 >>t{{7TZ?[\""8Y77#
 	
r  r   c                     | j                          | j                  |      }| j                  | j                  ||      }||d   d}| j	                  | j                  ||            }	| j                  |	||||      S )a  
        fetches historical candlestick data containing the open, high, low, and close price, and the volume of a market

        https://docs.gemini.com/rest-api/#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
        :param dict [params]: extra parameters specific to the exchange API endpoint
        :returns int[][]: A list of candles ordered, open, high, low, close, volume
        r,   )	timeframerU  )r  r  r9  r   !publicGetV2CandlesSymbolTimeframer  parse_ohlcvs)
r  rU  r  r  r  r  r  timeframeIdr  r  s
             r  fetch_ohlcvzgemini.fetch_ohlcvm  s     	V$&&t	9M$Tl
 99$++gv:VW   69eUKKr  )N)D__name__
__module____qualname__r   r  r   r  r  r   r   rN  rG  r  rI  r   r  r  r
   r   r  r  r  r  r   r  dictr  r   r   r  r   r
  r  r   r  r   r&  r)  r   r?  r   rC  rG  r   r   floatr   rQ  rT  rW  r   rv   r   rg  r   r^  rx  r  r	   r  r  r  intr  r  r  r  __classcell__)r  s   @r  r)   r)      s	   ]# ]~
 ') 6Z 6 02 Wr $& 3$v, 3$ -/ [z
6 )+ " -/ 4lR
 R
h :>b js j3 jY j, 35 3c 3* 35 3c 3, :< S  02 ;3 ;f ;&X4 X X6 Xt 04B 5W 57 58= =v = =~ 6:UW #A3 #As #A# #A\`af\g #AJ
) 
) )+ 8{ 8t $& ,( ,] ]v ] ]~ 26b '*c '*3 '*R /3TXac *A *A3 *Ac *Ahlmrhs *AX gksu U*3 U*i U*y U*RW U*`c U*n 37r (*s (*C (*T -1tRV_a Ac A AC A4 DHPR 1:S 1:% 1:# 1:Wb 1:f 6:[_hj 1s 1# 1UX 1ost  pA 1*6
T 6
X 6
Q\ 6
p:s :
h 
$ 79 3# 3^ 3$ DF 1s 1$~J^ 14 &eBSW P<c 3 S # X\ dg 0 8: 
3 
n 
4 26DW[df L# Lc LQT Lkoptku Lr  r)   ).ccxt.base.exchanger   ccxt.abstract.geminir   r  ccxt.base.typesr   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%   ccxt.base.decimal_to_precisionr&   ccxt.base.preciser'   r)    r  r  <module>r     sv    ( ,  J  J  J  J  J  J  * 0 - . ' . ) * ) . 1 * ) 4 %mLX{ mLr  