
    !:h                    @   d dl mZ d dlmZ d dlZd dlmZmZmZm	Z	m
Z
mZmZmZmZmZmZmZmZmZmZmZmZmZmZmZmZmZmZmZ 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)AccountAnyBalances
Conversion
CurrenciesCurrencyDepositAddressIntLedgerEntryMarketNumOrder	OrderBook	OrderSide	OrderTypePositionStrStringsTickerTickersTradeTradingFeesTransactionMarketInterface)List)ExchangeError)AuthenticationError)PermissionDenied)ArgumentsRequired)
BadRequest)InvalidOrder)OrderNotFound)NotSupported)RateLimitExceeded)InvalidNonce)	TICK_SIZE)Precisec                   n    e Zd Zdef fdZi fdefdZi fdee   fdZ	i fdee   fdZ
i fdee   fdZi fdee   fdZd Zi fd	edefd
Zdddi fdededefdZdddi fdededefdZdddi fd	ededefdZdddi fd	edededee   fdZdddi fd	edededee   fdZdddi fd	edededee   fdZdefdZd~dededefdZd~dededefdZi fdee   fdZ i fdee   fdZ!i fdee   fdZ"de#fd Z$de#fd!Z%i fd"Z&i fde'fd#Z(di fd$e)de*fd%Z+di fd$e)de*fd&Z,di fd$e)de*fd'Z-i fdede.fd(Z/i fdefd)Z0i fdefd*Z1d~d+edede.fd,Z2i fd-Z3i fde4fd.Z5dddi fd	edededee6   fd/Z7d0 Z8d1 Z9d~d2edede6fd3Z:i fd4Z;di fdefd5Z<ddi fd	edefd6Z=i fded7e>fd8Z?di fded9e@d:eAd;e>d<eBf
d=ZCd~d>ededeDfd?ZEdefd@ZFd9efdAZGdBefdCZHdi fdDedefdEZIdi fdefdFZJddi fdDeded9e@d:eAd;eBd<eBfdGZKdi fdDedefdHZLdddIi fdedededeeD   fdJZMdddi fdededefdKZNdddi fdedededeeD   fdLZOdddi fdedededeeD   fdMZPdddi fdededefdNZQdOddi fdedededeeR   fdPZSd~dedeRfdQZTddi fdedededee   fdRZUdddi fdededefdSZVdi fdededeWfdTZXdi fd$e)fdUZYdi fd	ed;e>dVedefdWZZi fd	edee   fdXZ[d~dedefdYZ\i fd	ed;e>dDefdZZ]di fdDed	efd[Z^i fd\Z_i fdDefd]Z`i fd^Zad_ Zbdi fd`edaed;eBdecfdbZddi fdDed`edaed;eBdecf
dcZedi fdDed	edecfddZfddeedfedgedecfdhZgdi fded:eAdeDfdiZhdi fd$e)deei   fdjZji fdefdkZkd~dledefdmZli fdemfdnZni fdoedee   fdpZodqefdrZpddsedteduefdvZqdw Zrg dxi ddfdyZsd	etdzeduedted{ed|efd}Zu xZvS )coinbasereturnc                 f   | j                  t        t        |          i ddddddgddd	d
ddddd| j                  d   dddi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d0dd1dd2dd3dd4d
d5d
d6di d7dd8dd9dd:d
d;d
d<d
d=dd>dd?d@dAd
dBddCddDddEddFddGd
dHd
i dId
dJd
dKd
dLd
dMd
dNd
dOddPd
dQd
dRd
dSddTd
dUddVddWddXddYd
i dZdd[dd\dd]dd^dd_d
d`ddad
dbd
dcdddddeddfddgd@dhddiddjd
d
d
d
ddkdldmdndoidpdqdrgdsdtgdudvdwdddxdydzd{d{d{d{d{d{d{d{d|ii d}d{d~d{dd{dd{dd{dd{dd{dd{dd{dd{dd{dd{dd{dd{dd{dd{dd{d{d{dd{d{d{d{d{d{d{d{d{d{d{d{d{d{dd{d{dd{d{ddddzdddddddii dddddddddddddddddddddddddddddddddddddddddddddddddddddddddidddddddd| j                  d      | j                  d      dd| j                  d      | j                  d      g| j                  d      | j                  d      g| j                  d      | j                  d      g| j                  d      | j                  d      g| j                  d      | j                  d      g| j                  d      | j                  d      g| j                  d      | j                  d      g| j                  d      | j                  d      g| j                  d      | j                  d      gg	| j                  d      | j                  d      g| j                  d      | j                  d      g| j                  d      | j                  d      g| j                  d      | j                  d«      g| j                  d      | j                  d      g| j                  d      | j                  dë      g| j                  d      | j                  dī      g| j                  d      | j                  dū      g| j                  d      | j                  dū      gg	dƜdǜidt        di dt        dt        dt        dt        dt        dt        dt        dt        dt        dt        dt        dt        dt        dt        dt        dt        dt        t        t        t        t        t        t        dۜt        t        dܜdݜddddddddddddii dd
dddg dd=ddid}ddgdddgdddddddddSddddd
dcd dddd1dd2dde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
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iddid dddid ddd      S (  Nidr+   namezCoinbase Advanced	countriesUSproT	certifiedF	rateLimit"   versionv2	userAgentchromeheadersz
CB-VERSIONz
2018-05-30hasCORSspotmarginswapfutureoption	addMargincancelOrdercancelOrderscloseAllPositionsclosePositioncreateConvertTradecreateDepositAddresscreateLimitBuyOrdercreateLimitSellOrdercreateMarketBuyOrdercreateMarketBuyOrderWithCostcreateMarketOrderWithCostcreateMarketSellOrdercreateMarketSellOrderWithCostcreateOrdercreatePostOnlyOrdercreateReduceOnlyOrdercreateStopLimitOrdercreateStopMarketOrdercreateStopOrderdeposit	editOrderfetchAccountsfetchBalancefetchBidsAsksfetchBorrowRateHistoriesfetchBorrowRateHistoryfetchCanceledOrdersfetchClosedOrdersfetchConvertQuotefetchConvertTradefetchConvertTradeHistoryfetchCrossBorrowRatefetchCrossBorrowRatesfetchCurrenciesfetchDepositfetchDepositAddressemulatedfetchDepositAddressesfetchDepositAddressesByNetworkfetchDepositMethodIdfetchDepositMethodIdsfetchDepositsfetchDepositsWithdrawalsfetchFundingHistoryfetchFundingRatefetchFundingRateHistoryfetchFundingRatesfetchIndexOHLCVfetchIsolatedBorrowRatefetchIsolatedBorrowRatesfetchL2OrderBookfetchLedgerfetchLeveragefetchLeverageTiersfetchMarginModefetchMarketsfetchMarkOHLCVfetchMyBuysfetchMySellsfetchMyTrades
fetchOHLCVfetchOpenInterestHistoryfetchOpenOrders
fetchOrderfetchOrderBookfetchOrdersfetchPositionfetchPositionModefetchPositionsfetchPositionsRiskfetchPremiumIndexOHLCVfetchTickerfetchTickers	fetchTimefetchTradesfetchTradingFeefetchTradingFeesfetchWithdrawalsreduceMargin)setLeveragesetMarginModesetPositionModewithdrawurlszchttps://user-images.githubusercontent.com/1294454/40811661-b6eceae2-653a-11e8-829e-10bfadb078cf.jpgrestzhttps://api.coinbase.comzhttps://www.coinbase.comz&https://developers.coinbase.com/api/v2z;https://docs.cloud.coinbase.com/advanced-trade/docs/welcomezYhttps://support.coinbase.com/customer/portal/articles/2109597-buy-sell-bank-transfer-feesz&https://www.coinbase.com/advanced-feesz6https://www.coinbase.com/join/58cbe25a355148797479dbd2)logoapiwwwdocfeesreferralrequiredCredentials)apiKeysecretr   getg333333%@)
currencieszcurrencies/cryptotimezexchange-rateszusers/{user_id}zprices/{symbol}/buyzprices/{symbol}/sellzprices/{symbol}/spotaccountsaccounts/{account_id}accounts/{account_id}/addressesz,accounts/{account_id}/addresses/{address_id}z9accounts/{account_id}/addresses/{address_id}/transactions"accounts/{account_id}/transactions3accounts/{account_id}/transactions/{transaction_id}accounts/{account_id}/buysz#accounts/{account_id}/buys/{buy_id}accounts/{account_id}/sellsz%accounts/{account_id}/sells/{sell_id}accounts/{account_id}/depositsz+accounts/{account_id}/deposits/{deposit_id}!accounts/{account_id}/withdrawalsz1accounts/{account_id}/withdrawals/{withdrawal_id}zpayment-methodsz#payment-methods/{payment_method_id})userz	user/auth)r   zaccounts/{account_id}/primaryr   r   z<accounts/{account_id}/transactions/{transaction_id}/completez:accounts/{account_id}/transactions/{transaction_id}/resendr   z*accounts/{account_id}/buys/{buy_id}/commitr   z,accounts/{account_id}/sells/{sell_id}/commitr   z2accounts/{account_id}/deposits/{deposit_id}/commitr   z8accounts/{account_id}/withdrawals/{withdrawal_id}/commit)r   r   )zaccounts/{id}r   )r   postputdelete)publicprivate   )zbrokerage/timezbrokerage/market/product_bookzbrokerage/market/productsz&brokerage/market/products/{product_id}z.brokerage/market/products/{product_id}/candlesz-brokerage/market/products/{product_id}/tickerzbrokerage/accounts   z!brokerage/accounts/{account_uuid}z!brokerage/orders/historical/batchz!brokerage/orders/historical/fillsz&brokerage/orders/historical/{order_id}zbrokerage/productszbrokerage/products/{product_id}z'brokerage/products/{product_id}/candlesz&brokerage/products/{product_id}/tickerzbrokerage/best_bid_askzbrokerage/product_bookzbrokerage/transaction_summarybrokerage/portfolios%brokerage/portfolios/{portfolio_uuid}"brokerage/convert/trade/{trade_id}zbrokerage/cfm/balance_summaryzbrokerage/cfm/positions)z$brokerage/cfm/positions/{product_id}brokerage/cfm/sweepsz)brokerage/intx/portfolio/{portfolio_uuid}z)brokerage/intx/positions/{portfolio_uuid}z2brokerage/intx/positions/{portfolio_uuid}/{symbol}zbrokerage/payment_methodsz-brokerage/payment_methods/{payment_method_id})zbrokerage/orderszbrokerage/orders/batch_cancelzbrokerage/orders/editzbrokerage/orders/edit_previewzbrokerage/orders/previewr   zbrokerage/portfolios/move_fundszbrokerage/convert/quoter   zbrokerage/cfm/sweeps/schedulezbrokerage/intx/allocatezbrokerage/orders/close_position)r   r   )r7   v3r   tradingz0.012z0.006010000z0.00450000z0.0025100000z0.0021000000z0.001815000000z0.001675000000z0.0012	250000000z0.0008	400000000z0.0005z0.0015z0.001z0.0006z0.0003z0.0)takermaker)r   r   	tierBased
percentagetiersprecisionMode
exceptionstwo_factor_requiredparam_requiredvalidation_errorinvalid_requestpersonal_details_requiredidentity_verification_requiredjumio_verification_required&jumio_face_match_verification_requiredunverified_emailauthentication_errorinvalid_authentication_methodinvalid_tokenrevoked_tokenexpired_tokeninvalid_scope	not_foundrate_limit_exceeded)internal_server_errorUNSUPPORTED_ORDER_CONFIGURATIONINSUFFICIENT_FUNDPERMISSION_DENIEDINVALID_ARGUMENT)PREVIEW_STOP_PRICE_ABOVE_LAST_TRADE_PRICE)zrequest timestamp expiredz%order with self orderID was not found)exactbroad
timeframes
ONE_MINUTEFIVE_MINUTEFIFTEEN_MINUTETHIRTY_MINUTEONE_HOURTWO_HOURSIX_HOURONE_DAY)1m5m15m30m1h2h6h1dCGLDCELO
usePrivatebrokerIdccxtstablePairs)zBUSD-USDz	CBETH-ETHzDAI-USDzGUSD-USDzGYEN-USDzPAX-USDzPAX-USDTzUSDC-EURzUSDC-GBPzUSDT-EURzUSDT-GBPzUSDT-USDz	USDT-USDCzWBTC-BTCexpiresi  walletfiat
v3AccountsACCOUNT_TYPE_CRYPTOACCOUNT_TYPE_FIATnetworksethereumstellar)ERC20XLM!createMarketBuyOrderRequiresPriceadvancedfetchMarketsV3timeDifferencer   adjustForTimeDifferencefetchTickerV3fetchTickersV3fetchAccountsV3v2PrivateGetAccountsv2PublicGetTimeuser_native_currencyUSD)IOCFOKPOGTD)
marginModetriggerPricetriggerPriceTypetriggerDirectionstopLossPricetakeProfitPriceattachedStopLossTakeProfittimeInForcehedgedtrailingleveragemarketBuyByCostmarketBuyRequiresPriceselfTradePreventionicebergi  i'  )r  limitdaysBack	untilDayssymbolRequired)r  triggerr  r(  )r  r%  r)  r  r(  )r  r%  r&  r'  r)  r  r(  )r  r%  r&  daysBackCanceledr'  r)  r  r(  r%  ,  )	sandboxrP   createOrdersr~   r   r   r   r^   r   extendsdefault)linearinverse)r/  r=   r?   r@   )commonCurrenciesoptionsfeatures)deep_extendsuperr+   describe
userAgentsparse_numberr(   r   r   r&   r"   r    r#   r'   r$   )self	__class__s    G/var/www/html/turnos/venv/lib/python3.12/site-packages/ccxt/coinbase.pyr7  zcoinbase.describe   s   h > @ C
*C
'C
 $C
 4	C

 C
 C
 tC
 2C
 lC
"  ZZZ %Z 	Z
 %Z %Z UZ tZ Z $UZ  Z %dZ 'Z &tZ 'Z  '!Z" /#Z$ ,U%Z& ('Z( 0)Z* t+Z, &t-Z. (/Z0 '1Z2 (3Z4 "45Z6 47Z8 T9Z:  ;Z< =Z>  ?Z@ +EAZB )%CZD &tEZF $TGZH $TIZJ $TKZL +EMZN 'OZP (QZR "4SZT UZV &zWZX (YZZ 1$[Z\ ']Z^ (_Z`  aZb +DcZd &ueZf #EgZh *5iZj $UkZl "5mZn *5oZp +EqZr #EsZt tuZv  wZx %eyZz "5{Z| }Z~ !%Z@ tAZB CZD  EZF dGZH +EIZJ "4KZL dMZN !$OZP tQZR  SZT $UUZV !$WZX %eYZZ )%[Z\ t]Z^ _Z` TaZb tcZd ":eZf #DgZh #DiZj kZl  %!&#( sZ#C
X }6 2<Q
 p< UYC
x "$yC
@  *.15$(.2/3374848	  & 3T  >t  KD	 
 XY]  A$  RSW  9$  B4  :4  DT  =d  J4  @  PQU   .t! " B4# $ %))-' , )-=A?CBF\`Z^:>JN;?LP>BRVAEX\!" 6:$( 
 .2SW#U. <~ ./=>9:FGNOMN 	 0! ?  @  @	 
 Ea  1!  >q  Fq  Ea  5a  5a  <Q  3A  DQ  A!   <Q! " 6q# $ EF45IJIJRS9:MN1 6 12=>56=>8945?@78BC=>78?@!  DQ  FG45#[1 =}|AC
z !..w7!..w7!%"& "..s3T5F5Fw5OP!..w79J9J79ST!..w79J9J89TU!..x8$:K:KG:TU!..y94;L;LX;VW!..z:D<M<Mh<WX!..z:D<M<Mh<WX!..{;T=N=Nx=XY!..{;T=N=Nx=XY
" "..s3T5F5Fw5OP!..w79J9J89TU!..w79J9J89TU!..x8$:K:KG:TU!..y94;L;LX;VW!..z:D<M<Mh<WX!..z:D<M<Mh<WX!..{;T=N=Nu=UV!..{;T=N=Nu=UV
"{C
z Y{C
| )+>$m ' &}	
 01D 56I 23F =>Q '(; +,? 45H $%8 $%8 $%8 $%8   !" *+<#$ .;7A)3)9(2AM/4 2>=J5}C
z	 "#'&   	{	C
P
 !eF    H "t$	  )'  '$!( 4T)* D+,  0-. !!/0 *512 34  056  !278  69: .;< '=D  %&*(,,0,0)-+/6:#'#'"&#'	( #($)$(+/26/4#()$, %)&+!%$(%**/& ',#($)*/	# ',!%#($)*/( ',!%$(%*#($)*/$ ',!%$(,0%*#($)*/	*  #ACJ y
 "9  $	 "9  $	]TUC
  	    c                 &   | j                  | j                  dd      }| j                  |d|      }| j                  |d      }d}|dk(  r%| j                  |      }| j	                  |di       }n| j                  |      }| j                  |dd      S )a  
        fetches the current integer timestamp in milliseconds from the exchange server

        https://docs.cloud.coinbase.com/sign-in-with-coinbase/docs/api-time#http-request

        :param dict [params]: extra parameters specific to the exchange API endpoint
        :param str [params.method]: 'v2PublicGetTime' or 'v3PublicGetBrokerageTime' default is 'v2PublicGetTime'
        :returns int: the current integer timestamp in milliseconds from the exchange server
        r   r  methodNdataepochepochSeconds)safe_stringr3  omitr  	safe_dictv3PublicGetBrokerageTimesafe_timestamp_2)r:  paramsdefaultMethodr?  responses        r<  
fetch_timezcoinbase.fetch_time  s     (({DUV!!&(MB68,&&++F3H ~~h;H44V<H $$XwGGr=  c                     | j                  | j                  dd      }|dk(  r| j                  |      S | j                  |      S )a  
        fetch all the accounts associated with a profile

        https://docs.cloud.coinbase.com/advanced-trade/reference/retailbrokerageapi_getaccounts
        https://docs.cloud.coinbase.com/sign-in-with-coinbase/docs/api-accounts#list-accounts

        :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 [availble parameters](https://github.com/ccxt/ccxt/wiki/Manual#pagination-params)
        :returns dict: a dictionary of `account structures <https://docs.ccxt.com/#/?id=account-structure>` indexed by the account type
        rX   r  )rC  r3  fetch_accounts_v3fetch_accounts_v2r:  rH  r?  s      r<  fetch_accountszcoinbase.fetch_accounts  sH     !!$,,ARS&&))&11%%f--r=  c                    | j                          d}| j                  |dd      \  }}|r| j                  dd d d |ddd d	      S ddi}| j                  | j	                  ||            }| j                  |dg       }| j                  |d	i       }| j                  |d      }| j                  |dg       }t        |      }	|	d
z
  }
| j                  ||
      }||dk7  r
||d<   |||
<   | j                  ||      S )NFrX   paginatenext_starting_afterstarting_afterd   r%  r@  
paginationr    )
load_marketshandle_option_and_paramsfetch_paginated_call_cursorr  extend	safe_listrE  rC  lenparse_accounts)r:  rH  rR  requestrJ  r@  rV  cursorr   length	lastIndexlasts               r<  rN  zcoinbase.fetch_accounts_v2  s4   88R\]&33OT4QUW]_t  wG  IM  OR  S  SS
 ,,T[[&-IJZ ~~h3^^HlB?
!!*.CD>>(FB7XQJ	~~h	2Vr\*0D&'"&HY""400r=  c                    | j                          d}| j                  |dd      \  }}|r| j                  dd d d |ddd d	      S ddi}| j                  | j	                  ||            }| j                  |dg       }t        |      }|dz
  }| j                  ||      }| j                  |d      }	|	|	d	k7  r
|	|d<   |||<   | j                  ||      S )
NFrX   rR  r`     r%  r   r   rW  )
rX  rY  rZ  v3PrivateGetBrokerageAccountsr[  r\  r]  rE  rC  r^  )
r:  rH  rR  r_  rJ  r   ra  rb  rc  r`  s
             r<  rM  zcoinbase.fetch_accounts_v3S  s    88R\]&33OT4QUW]_giqswy|}}S
 55dkk'66RS> >>(J;XQJ	~~h	2!!(H5Vr\#DN"&HY""8V44r=  c                     | j                  |      }| j                  |dg       }g }t        dt        |            D ]=  }||   }|j	                  | j                  |d      | j                  |d      d|d       ? |S )ak  
        fetch all the portfolios

        https://docs.cloud.coinbase.com/advanced-trade/reference/retailbrokerageapi_getportfolios

        :param dict [params]: extra parameters specific to the exchange API endpoint
        :returns dict: a dictionary of `account structures <https://docs.ccxt.com/#/?id=account-structure>` indexed by the account type
        
portfoliosr   uuidtypeNr.   rj  codeinfo)v3PrivateGetBrokeragePortfoliosr\  ranger]  appendrC  )r:  rH  rJ  rh  resulti	portfolios          r<  fetch_portfolioszcoinbase.fetch_portfolios  s     77?^^HlB?
q#j/* 	A"1IMM&&y&9((F;!	 	 r=  c                 v   | j                  |d      }| j                  |d      }| j                  |di       }| j                  |d|      }| j                  |d      }| j                  |d      }|j                  d      }| j	                  |dd      || j                  |d	      n|| j                  |      |d
S )Nactivecurrencyrl  r/   rj   r.   ri  r   rk  )	safe_boolrC  rE  splitsafe_string_2safe_string_lowersafe_currency_code)	r:  accountrv  currencyIdV3rw  
currencyIdtypeV3typeV2partss	            r<  parse_accountzcoinbase.parse_account  s    p 2''<>>':r:%%hE
!!'62!!'62S!$$WdF;9?9KD**5!4RX++J7	
 	
r=  rl  c                    | j                  |d      }| j                  |d      }|[| j                          t        dt	        | j
                              D ])  }| j
                  |   }|d   |k(  s|d   dk(  s$|d   } n |t        | j                  dz   |z   d	z         d|i}| j                  | j                  ||            }| j                  |d
i       }| j                  |d      }	| j                  |d      }
||	|
d|dS )a  
        create a currency deposit address

        https://docs.cloud.coinbase.com/sign-in-with-coinbase/docs/api-addresses#create-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>`
        
account_idNr   rl  rj  r   r.   zO createDepositAddress() could not find the account with matching currency code z?, specify an `account_id` extra param to target specific walletr@  destination_tagaddress)rw  tagr  networkrm  )rC  rD  load_accountsro  r]  r   r   r.   'v2PrivatePostAccountsAccountIdAddressesr[  rE  )r:  rl  rH  	accountIdrr  r~  r_  rJ  r@  r  r  s              r<  create_deposit_addresszcoinbase.create_deposit_address  sB    $$V\:	6<0 1c$--01 --*6?d*wv(/J 'I	
 *{ {  C  !C  FG  !G  H  H)
 ??GU[@\]J ~~h3t%67""43
 	
r=  Nsymbolsincer%  c                     | j                  ||      }| j                          | j                  |ddg      }| j                  | j	                  ||            }| j                  |d   d||      S )a  
 @ignore
        fetch sells

        https://docs.cloud.coinbase.com/sign-in-with-coinbase/docs/api-sells#list-sells

        :param str symbol: not used by coinbase fetchMySells()
        :param int [since]: timestamp in ms of the earliest sell, default is None
        :param int [limit]: max number of sells to return, default is 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>`
        r  r  r@  N)prepare_account_requestrX  rD  "v2PrivateGetAccountsAccountIdSellsr[  parse_trades)r:  r  r  r%  rH  r_  querysellss           r<  fetch_my_sellszcoinbase.fetch_my_sells)  sm     ..uf=		&<"=>77GU8ST  veUCCr=  c                     | j                  ||      }| j                          | j                  |ddg      }| j                  | j	                  ||            }| j                  |d   d||      S )a  
 @ignore
        fetch buys

        https://docs.cloud.coinbase.com/sign-in-with-coinbase/docs/api-buys#list-buys

        :param str symbol: not used by coinbase fetchMyBuys()
        :param int [since]: timestamp in ms of the earliest buy, default is None
        :param int [limit]: max number of buys to return, default is 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>`
        r  r  r@  N)r  rX  rD  !v2PrivateGetAccountsAccountIdBuysr[  r  )r:  r  r  r%  rH  r_  r  buyss           r<  fetch_my_buyszcoinbase.fetch_my_buys=  sm     ..uf=		&<"=>55dkk'56QR  ftUEBBr=  c                     d }| j                  |||      \  }}| j                           t        | |      | j                  ||            }| j	                  |d   d ||      S )Nr@  )*prepare_account_request_with_currency_coderX  getattrr[  parse_transactions)r:  r?  rl  r  r%  rH  r_  rJ  s           r<  fetch_transactions_with_methodz'coinbase.fetch_transactions_with_methodQ  sg    II$PUW]^(74(Wf)EF&&x'7ueLLr=  c                     d}| j                  |dd      \  }}|dk(  r)| j                  d||||      }| j                  |ddd      S | j                  d	||||      S )
a  
        Fetch all withdrawals made from an account. Won't return crypto withdrawals. Use fetchLedger for those.

        https://docs.cdp.coinbase.com/coinbase-app/docs/api-withdrawals#list-withdrawals

        :param str code: unified currency code
        :param int [since]: the earliest time in ms to fetch withdrawals for
        :param int [limit]: the maximum number of withdrawals structures to retrieve
        :param dict [params]: extra parameters specific to the exchange API endpoint
        :param str [params.currencyType]: "fiat" or "crypto"
        :returns dict[]: a list of `transaction structures <https://docs.ccxt.com/#/?id=transaction-structure>`
        Nr   currencyTypecrypto)v2PrivateGetAccountsAccountIdTransactionsrj  
withdrawalF(v2PrivateGetAccountsAccountIdWithdrawalsrY  r  filter_by_arrayr:  rl  r  r%  rH  r  resultss          r<  fetch_withdrawalszcoinbase.fetch_withdrawalsX  s     #<<VEWYghf8#99:egkmrty  |B  CG''uMM223]_cejlqsyzzr=  c                     d}| j                  |dd      \  }}|dk(  r)| j                  d||||      }| j                  |ddd      S | j                  d	||||      S )
a  
        Fetch all fiat deposits made to an account. Won't return crypto deposits or staking rewards. Use fetchLedger for those.

        https://docs.cdp.coinbase.com/coinbase-app/docs/api-deposits#list-deposits

        :param str code: unified currency code
        :param int [since]: the earliest time in ms to fetch deposits for
        :param int [limit]: the maximum number of deposits structures to retrieve
        :param dict [params]: extra parameters specific to the exchange API endpoint
        :param str [params.currencyType]: "fiat" or "crypto"
        :returns dict[]: a list of `transaction structures <https://docs.ccxt.com/#/?id=transaction-structure>`
        Nr   r  r  r  rj  rV   F%v2PrivateGetAccountsAccountIdDepositsr  r  s          r<  fetch_depositszcoinbase.fetch_depositsl  s     #<<VEWYghf8#99:egkmrty  |B  CG''EJJ223Z\`bginpvwwr=  c                 x    | j                          | j                  d||||      }| j                  |dddgd      S )a~  
        fetch history of deposits and withdrawals

        https://docs.cdp.coinbase.com/coinbase-app/docs/api-transactions

        :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 = 50, Min: 1, Max: 100
        :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>`
        r  rj  rV   r  F)rX  r  r  )r:  rl  r  r%  rH  r  s         r<  fetch_deposits_withdrawalsz#coinbase.fetch_deposits_withdrawals  sJ     	556acginpuw}~##GVi5NPUVVr=  statusc                 4    dddd}| j                  |||      S )Npendingokcanceled)created	completedr  rC  r:  r  statusess      r<  parse_transaction_statusz!coinbase.parse_transaction_status  s)     "

 &&99r=  transactionrw  c                    | j                  |d      }d }d }| j                  |di       }|dk(  r&| j                  |d      }| j                  |di       }n%| j                  |d      }| j                  |di       }|| j                  |d      }| j                  |d      }t        j                  |      }| j	                  | j                  |d	            }	|	| j                  |d
      }
|
rdnd}	| j                  |d      }| j                  |d      }| j                  |d      }| j                  |d      }| j                  |d      }|}| j                  |ddg      s1t        j                  |d      rd}nt        j                  |d      rd}| j                  |d      }| j                  |d      }| j                  |d      }i d|d|d| j                  |d|      d| j                  |      d|d| j                  |      d|d|dd dd dd d d d|d| j                  |      d| j                  ||      d	|	d!| j                  | j                  |d"            d| j                  |d      | j                  |      d#iS )$Nrj  r  sendtransaction_amounttransaction_feesubtotalfeeamountr  	committedr  r  r.   rw  
created_atresourcerV   r  r   tor  network_namerm  txidhash	timestampdatetime	addressToaddressFromr  tagTotagFromupdated
updated_atcostrw  )rC  rE  r)   
string_absr  ry  in_array	string_gt	string_lt	parse8601network_id_to_coder9  r}  safe_number)r:  r  rw  transactionTypeamountAndCurrencyObject	feeObjectr  amountStringamountStringAbsr  r  r.   r  feeCurrencyIdr  r  rj  toObjectr  	networkIds                       r<  parse_transactionzcoinbase.parse_transaction  s   t **;?"&	..i<f$&*nnW>R&S#w0A2FI&*nn[*&M#{E2>I"*&*nn[(&K#''(?J!,,\:..t/?/?X/VW>{K@I&TIFk40%%&=zJ
((J?##K>##K<}}TI|#<=  s3 ""<5#>>+t4$$Xy9	$$Wn=	
K
"
 D$$Wfb9
 1	

 
 t..y9
 y
 
 4
 4
 T
 t
 D
 d''8
 //
HE
  f!
" t~~d&6&6{L&QR#
$ ((H= 33MB%
 	
r=  trademarketc                    d }| j                  |di       }| j                  |di       }| j                  |di       }| j                  |di       }| j                  |d      }| j                  ||d      }||d   }nR| j                  |d      }	| j                  |d      }
|	,|
*| j                  |	      }| j                  |
      }|d	z   |z   }| j	                  |d
      }| j                  |d      }d }| j                  |d      }|r|}t        j                  ||      }| j                  |d      }| j                  |d|      }| j                  |d|      }d }d }||t        j                  ||      }n|}||t        j                  ||      }n|}| j                  |d      }| j                  |d| j                  |            }|	|||d   }| j                  |g d      }| j                  |dd      }| j                  |d      }| j                  || j                  |dd      | j                  |d      | j                  |      ||d |dk(  rd n||dk(  rd n|||||| j                  |      dd      S )Ntotalr  r  r  
product_id-r  rw  /size_in_quotepricesize
commissionquote)r  
trade_timer   r  sideliquidity_indicatorr.   trade_idorder_idunknown_order_sideunknown_liquidity_indicatorr  )rm  r.   orderr  r  r  rj  r  takerOrMakerr  r  r  r  )rE  rC  safe_marketr}  ry  r)   
string_div
string_mulr  r9  safe_string_nsafe_string_lower_2r|  
safe_trader{  r  )r:  r  r  r  totalObjectamountObjectsubtotalObjectr  marketIdbaseIdquoteIdbaser  sizeInQuotev3Pricev3Costv3Amount	v3FeeCostr  
costStringpriceStringr  r  feeCostr  r  r  s                              r<  parse_tradezcoinbase.parse_tradej  s   | nnUGR8~~eXr:z2>NN5%4	##E<8!!(FC8H%F%%lJ?F&&{J?G")<..v6//8e+nnUO<""5'2##E62F))(G<H$$UL9	''hI%%nhG
")A!,,ZFK!K#,*B%%k<@DD((J?""9h8I8I)8TU!(:AT"7OM%%e-QR''z6B--e5JK$$UD*=%%eZ81 !%99D%15R%RDYe " 33MB 
  	r=  c                     | j                   d   r| j                          | j                  | j                   dd      }|dk(  r| j                  |      S | j	                  |      S )ad  

        https://docs.cloud.coinbase.com/advanced-trade/reference/retailbrokerageapi_getpublicproducts
        https://docs.cloud.coinbase.com/sign-in-with-coinbase/docs/api-currencies#get-fiat-currencies
        https://docs.cloud.coinbase.com/sign-in-with-coinbase/docs/api-exchange-rates#get-exchange-rates

        retrieves data on all markets for coinbase
        :param dict [params]: extra parameters specific to the exchange API endpoint
        :param boolean [params.usePrivate]: use private endpoint for fetching markets
        :returns dict[]: an array of objects representing market data
        r
  rz   r  )r3  load_time_differencerC  fetch_markets_v3fetch_markets_v2rO  s      r<  fetch_marketszcoinbase.fetch_markets  sa     <<12%%'!!$,,@PQ%%((00$$V,,r=  c                 Z   | j                  |      }| j                  |di       }| j                  |di       }| j                  |dg       }| j                  |d      }| j                  | j                  |di       di       }t	        |j                               }g }	t        dt        |            D ]  }
||
   }| j                  |      }||v rdnd}|dk(  s't        dt        |            D ]  }||   }| j                  |d      }| j                  |      }|	j                  | j                  i d|d	z   |z   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 d d dd d dd d dd d d| j                  |d      d dd |d!	               |	S )"Nr   exchangeRatesr@  r.   ratesr   r   r  r  r  r  r  r  settler  r  settleIdrj  r=   Tr>   Fr?   r@   rA   rv  contractr0  r  r  minmaxmin_sizer   r  r  r  )	r1  contractSizeexpiryexpiryDatetimestrike
optionType	precisionlimitsrm  )fetch_currencies_from_cacherE  r\  index_bylistkeysro  r]  r}  rC  rp  safe_market_structurer  )r:  rH  rJ  r   r  r@  dataByIdr  baseIdsrq  rr  r  r  rj  jquoteCurrencyr  r  s                     r<  r  zcoinbase.fetch_markets_v2  s   33F;^^HlB?
x"E~~j&"5==t,t~~mVRH'SUVuzz|$q#g,' 9	AQZF**62D$06xDxq#d), 3A$(GM"..}dCG 33G<EMM$"<"< />fslW4/> $*u"4/> />  	/>
 !$/> !&/> "7/> #D/> /> /> !%/> /> !%/> !%/> !$/>  #E!/>" !$#/>$ $((,"&*."&&*&*%)& (,'+)
 (,'+'
 (,'+&
 (,'7'7z'R'+%#$ !.]/> /# /	39	t r=  c           	      V   d}| j                  |ddd      \  }}g }|r!|j                  | j                  |             n |j                  | j                  |             | j	                  d      r |j                  | j                  |             g }	 | j                  | j                  |ddi            | j                  | j                  |ddd            g}|}d }	 |}| j                  |di       }| j                  |d	i       }	| j                  |di       }
| j                  |d	i       }| j                  |di       }| j                  |d	i       }| j                  |	d
i       }| j                  |d
i       }| j                  |d
i       }| j                  |dg       }g }t        dt        |            D ]&  }|j                  | j                  ||   |             ( | j                  |
dg       }t        dt        |            D ]&  }|j                  | j                  ||   |             ( | j                  |dg       }t        dt        |            D ]&  }|j                  | j                  ||   |             ( g }t        dt        |            D ]\  }||   }| j                  |di       }| j                  |dg       }t        |      }|dkD  r	|d   |d<   nd |d<   |j                  |       ^ |S # t        $ r}g }Y d }~0d }~ww xY w# t        $ r}g }Y d }~Bd }~ww xY w)NFrz   r   product_typeFUTURE	PERPETUAL)r2  contract_expiry_typer   r   fee_tierproductsrm  alias_toalias)rY  rp  v3PrivateGetBrokerageProducts"v3PublicGetBrokerageMarketProductscheck_required_credentials'v3PrivateGetBrokerageTransactionSummaryr[  	ExceptionrE  r\  ro  r]  parse_spot_marketparse_contract_market
safe_value)r:  rH  r   spotUnresolvedPromisesunresolvedContractPromisesepromisescontractPromisesr=   r   expiringFuturesperpetualFuturesexpiringFeesperpetualFeesfeeTierexpiringFeeTierperpetualFeeTierr@  rq  rr  
futureDataperpetualData
newMarketsr  rm  realMarketIdsra  s                              r<  r  zcoinbase.fetch_markets_v3?  sU   
!::6>S_afg
F!#"))$*L*LV*TU"))$*Q*QRX*YZ\ **51"))$*V*VW]*^_0 &("	,77F^]eLf8gh77F]e  @K  ML  9M  N*& *	"9 ~~h2.~~h2...)91bA>>*:ArB~~&62>'7B?( ..z26..z2F>>-RH~~dJ3q#d)$ 	DAMM$00a'BC	D^^OZD
q#j/* 	VAMM$44Z]OTU	V'7RHq#m,- 	ZAMM$44]15EGWXY	Z
q#f+& 		&AAYF??6626D NN4R@M'Fz"/"2w"&wf%		& s  	,)+&	,  	"!	"s1   AK9 L 9	LL

L	L(L##L(c                    | j                  |d      }| j                  |d      }| j                  |d      }| j                  |      }| j                  |      }| j                  |d      }| j                  |d      }	| j	                  | j
                  dg       }
| j                  | j                  d   d      }| j                  | j                  d   d	      }| j                  ||
      rd
n| j                  |d|      }| j                  ||
      rdn| j                  |d|      }| j                  i d|d|dz   |z   d|d|dd d|d|dd d|d|dk(  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%| j                  |d&      | j                  |d'      d%d d d%| j                  |d(      | j                  |d)      d%d*d |d+      S ),Nr  base_currency_idquote_currency_idr2  trading_disabledr   r   r   r   gh㈵>taker_fee_rateg        maker_fee_rater.   r  r  r  r  r  r  r  r  rj  r=   r>   r?   Fr@   rA   rv  r  r0  base_incrementprice_incrementquote_incrementr  r  base_min_sizebase_max_sizequote_min_sizequote_max_sizer   r1  r   r   r!  r"  r#  r$  r%  r&  r'  r  rm  )rC  r}  r|  ry  r\  r3  r  r   r  r,  safe_number_2)r:  r  rK  r.   r  r  r  r  
marketTypetradingDisabledr   defaultTakerFeedefaultMakerFeetakerFeemakerFees                  r<  r?  zcoinbase.parse_spot_market  s   @ fl3!!&*<=""6+>?&&v.''0++FNC
..1CDnnT\\="E**499Y+?I**499Y+?I"mmB<7$BRBRSZ\ln}B~--K83d>N>NwXhjy>z)) 2+
"2+
dSj5(2+
 D2+
 U	2+

 d2+
 f2+
 w2+
 2+
 J2+
 Z6)2+
 d2+
 E2+
 e2+
 e2+
 /)2+
  !2+
" d#2+
$  "**63CD++F4EGXY  
  ++FOD++FOD
  
  ++F4DE++F4DE$ c2+
 2 2	r=  c                 R   | j                  |d      }| j                  |di       }| j                  |d      }| j                  |d      }| j                  |d      }| j                  |      }| j	                  |      }	|dk(  }
| j                  |d      }| j                  |d      }| j                  |      }| j                  |      }| j                  |d	      }|d
z   |z   }d }|
rd}|dz   |z   }nd}|dz   |z   dz   | j                  |      z   }| j                  |d      }| j                  |d      }|r|n| j                  d      }|r|n| j                  d      }| j                  i d|d|d|d|d|d|d|d|d|ddddd|
d|
 ddd | d!d"d#d"d|||||	d d | j                  |d$      | j                  |d%d&      d'd d d(| j                  |d)      | j                  |d*      d(d d d(| j                  |d+      | j                  |d,      d(d-d |d.      S )/Nr  future_product_detailsr5  contract_sizecontract_expiryr4  contract_root_unitrT  is_disabledr  r?   :r@   r  rV  rW  z0.06z0.04r.   r  r  r  r  r  r  r  rj  r=   Fr>   rA   rv  r  Tr0  rX  rY  rZ  r  r  r[  r\  r]  r^  r   r_  )rC  rE  r  r  iso8601r}  ry  yymmddr9  r,  r`  )r:  r  rK  r.   futureProductDetailscontractExpiryTyper!  contractExpireexpireTimestampexpireDateTimeisSwapr  r  r  r  rb  r  rj  takerFeeRatemakerFeeRater   r   s                         r<  r@  zcoinbase.parse_contract_market.  s(   l fl3#~~f6NPRS!--.BDZ[''(<oN))*>@QR..8o6$3!!"68LM""6+>?&&v.''0..?e#Dc\E)FDc\E)C/$++o2NNF''1AB''1AB ,$2C2CF2K ,$2C2CF2K)) 2+
"2+
f2+
 D2+
 U	2+

 e2+
 f2+
 w2+
 2+
 D2+
 E2+
 e2+
 F2+
 &j2+
 e2+
 /)2+
  !2+
" d#2+
$ (%,**63CD++F4EGXY  
  ++FOD++FOD
  
  ++F4DE++F4DE$ c2+
 2 2	r=  c                 \   | j                  | j                  di       }| j                  |d      }| j                  |dd      }| j                         }|||z
  |kD  r| j	                  |      | j                  |      g}|}| j                  |di       }| j                  |di       }	| j                  |dg       }
| j                  |	dg       }| j                  |      }| j                  || j                  |
|      ||d      | j                  d<   | j                  | j                  di       S )	Nrd   r  r     r   r   r@  )r   r  r  )
rE  r3  safe_integermillisecondsv2PublicGetCurrenciesv2PublicGetCurrenciesCryptor\  v2PublicGetExchangeRatesr[  array_concat)r:  rH  r3  r  r   nowrE  promisesResultfiatResponsecryptoResponsefiatData
cryptoDatar  s                r<  r(  z$coinbase.fetch_currencies_from_cache  s4   ../@"E%%g{;	##GY=!C)Ow#>**62008H &N>>.!R@L "^^NArBN ~~lFB?HCJ 99&AM.2kk'"//*E!. D /DLL*+
 ~~dll,=rBBr=  c                 0   | j                  |      | j                  |      | j                  |      g}|}| j                  |di       }| j                  |di       }| j                  |di       }| j	                  |dg       }| j	                  |dg       }| j                  |di       }	| j                  |	di       }
t        |
j                               }| j                  ||      }i }i }i }t        dt        |            D ]  }||   }| j                  |d      }| j                  |dd      }| j                  |      }| j                  |d	      }|j                         | j                  d
   |<   |j                         | j                  d   |<   |dnd}| j                  |||||dddddi | j!                  |d      ddddddd      ||<   ||j                         }|||<   |||<    t        dt        |            D ]7  }||   }| j                  |      }||vs| j                  i ||di d      ||<   9 | j#                  || j                  d
         | j                  d
<   | j#                  || j                  d         | j                  d<   |S )a  
        fetches all available currencies on an exchange

        https://docs.cloud.coinbase.com/sign-in-with-coinbase/docs/api-currencies#get-fiat-currencies
        https://docs.cloud.coinbase.com/sign-in-with-coinbase/docs/api-exchange-rates#get-exchange-rates

        :param dict [params]: extra parameters specific to the exchange API endpoint
        :returns dict: an associative dictionary of currencies
        r   r      r@  r  asset_idr.   rl  r/   r  networksByIdNr  r   Tr  r  )r  r   )rm  r.   rl  rj  r/   rv  rV   r   r  r&  r  r'  )rm  r.   rl  rj  r  )r|  r}  r~  rE  r\  r*  r+  r  ro  r]  rC  r{  r}  lowerr3  safe_currency_structurer  r[  )r:  rH  rE  r  r  r  ratesResponser  r  	ratesDatar  ratesIdsr   rq  r  r  rr  rw  assetIdr.   rl  r/   rj  lowerCaseNamer  s                            r<  fetch_currencieszcoinbase.fetch_currencies  s    &&v.,,V4))&1

 "~~na< 2>  ~q"=>>,;^^NFB?
NN=&"=	y'26

%&&x<
q#j/* #	3A!!}H&&x<G##HdF;B**2.D##Hf5D-1ZZ\DLL$T*15DLL(. ' 38&D77  !  $//*E#
  $#!	9 F4L. " $

!..2]+G#	3J q#h-( 
	A!!J**:6DFN#;;$ $ "=  t	
	 $(;;xj9Q#RZ '+{{<nA]'^^$r=  symbolsc                     | j                  | j                  dd      }|dk(  r| j                  ||      S | j                  ||      S )a  
        fetches price tickers for multiple markets, statistical information calculated over the past 24 hours for each market

        https://docs.cloud.coinbase.com/advanced-trade/reference/retailbrokerageapi_getproducts
        https://docs.cloud.coinbase.com/sign-in-with-coinbase/docs/api-exchange-rates#get-exchange-rates

        :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
        :param boolean [params.usePrivate]: use private endpoint for fetching tickers
        :returns dict: a dictionary of `ticker structures <https://docs.ccxt.com/#/?id=ticker-structure>`
        r   r  )rC  r3  fetch_tickers_v3fetch_tickers_v2)r:  r  rH  r?  s       r<  fetch_tickerszcoinbase.fetch_tickers  sL     !!$,,@PQ%%((&99$$Wf55r=  c                    | j                          | j                  |      }i }| j                  | j                  ||            }| j	                  |di       }| j	                  |di       }| j                  |d      }i }t        |j                               }	d}
t        dt        |	            D ]?  }|	|   }||
z   |z   }| j                  |d |
      }|d   }| j                  ||   |      ||<   A | j                  |d|      S )Nr@  r  rw  r  r   r  )rX  market_symbolsr~  r[  rE  rC  r*  r+  ro  r]  r  parse_tickerfilter_by_array_tickers)r:  r  rH  r_  rJ  r@  r  r  rq  r.  	delimiterrr  r  r  r  r  s                   r<  r  zcoinbase.fetch_tickers_v2  s   %%g.
 00Wf1MN ~~h3tWb1""44uzz|$	q#g,' 	FAQZF	)G3H%%hi@FH%F!..uV}fEF6N	F ++FHgFFr=  c                    | j                          | j                  |      }i }|| j                  |      |d<   d }| j                  d| j	                  |      |d      \  }}||dk7  r|dk(  rdnd|d<   d }d}| j                  |dd	d      \  }}|r"| j                  | j                  ||            }n!| j                  | j                  ||            }| j                  |d
g       }i }t        dt        |            D ]F  }	||	   }
| j                  |
d      }| j                  |d d      }|d   }| j                  |
|      ||<   H | j                  |d|      S )Nproduct_idsr   r/  r?   r3  SPOTr2  Fr   r7  r   r  r  r  )rX  r  
market_idshandle_market_type_and_paramsget_market_from_symbolsrY  r:  r[  r;  r\  ro  r]  rC  r  r  r  )r:  r  rH  r_  ra  rJ  r   r@  rq  rr  entryr  r  r  s                 r<  r  zcoinbase.fetch_tickers_v3  s   %%g.%)__W%=GM"
!??PTPlPlmtPuw}  @I  J
F!jI&=3=3GhfGN#
!::6>S_afg
F99$++gv:VWH>>t{{7TZ?[\HL ~~h
B7q#d)$ 	>AGE''|<H%%hc:FH%F!..uf=F6N	> ++FHgFFr=  c                     | j                  | j                  dd      }|dk(  r| j                  ||      S | j                  ||      S )at  
        fetches a price ticker, a statistical calculation with the information calculated over the past 24 hours for a specific market

        https://docs.cloud.coinbase.com/advanced-trade/reference/retailbrokerageapi_getmarkettrades
        https://docs.cloud.coinbase.com/sign-in-with-coinbase/docs/api-prices#get-spot-price
        https://docs.cloud.coinbase.com/sign-in-with-coinbase/docs/api-prices#get-buy-price
        https://docs.cloud.coinbase.com/sign-in-with-coinbase/docs/api-prices#get-sell-price

        :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 boolean [params.usePrivate]: whether to use the private endpoint for fetching the ticker
        :returns dict: a `ticker structure <https://docs.ccxt.com/#/?id=ticker-structure>`
        r   r  )rC  r3  fetch_ticker_v3fetch_ticker_v2)r:  r  rH  r?  s       r<  fetch_tickerzcoinbase.fetch_ticker  sJ     !!$,,O_$''77##FF33r=  c                    | j                          | j                  |      }| j                  d|d   i|      }| j                  |      }| j	                  |      }| j                  |      }| j                  |di       }| j                  |di       }	| j                  |di       }
| j                  |
d      | j                  |	d      | j                  |d      d}| j                  ||      S )Nr  r.   r@  r  )bidaskr  )	rX  r  r[  v2PublicGetPricesSymbolSpotv2PublicGetPricesSymbolBuyv2PublicGetPricesSymbolSellrE  r  r  )r:  r  rH  r  r_  r=   r  r  spotDataaskDatabidData
bidAskLasts               r<  r  zcoinbase.fetch_ticker_v2  s    V$++fTl
 //8 --g6 ..w7 >>$3..fb1..fb1##GX6##GX6%%h9


   V44r=  c                    | j                          | j                  |      }|d   dd}d}| j                  |ddd      \  }}d }|r"| j                  | j	                  ||            }n!| j                  | j	                  ||            }| j                  |dg       }| j                  |d   |      }| j                  |d	      |d
<   | j                  |d      |d<   |S )Nr.   r   )r  r%  Fr   r   tradesr   best_bidr  best_askr  )	rX  r  rY  ,v3PrivateGetBrokerageProductsProductIdTickerr[  1v3PublicGetBrokerageMarketProductsProductIdTickerr\  r  r  )	r:  r  rH  r  r_  r   rJ  r@  tickers	            r<  r  zcoinbase.fetch_ticker_v3(  s    V$ ,
 
!::6=R^`ef
FHHU\^dIefHMMdkkZaciNjkH& ~~h"5""47F3((:>u((:>ur=  r  c                    | j                  |d      }| j                  |d      }d }d }d|v rz| j                  |dg       }| j                  |dg       }| j                  |d   d      }| j                  |d   d      }| j                  |d   d      }| j                  |d   d      }| j                  |d      }	| j                  |	|      }| j                  |d      }
| j                  |d	      }| j	                  i d
|d
   d| j                  |      d|d|d|d|
dd dd d|d|dd dd d|
dd dd d| j                  |d      dd d d |d|      S )Nr  r  bidsasksr   r  r  r  r   r  r  r  rc  highlow	bidVolume	askVolumevwapopenclosepreviousClosechanger   price_percentage_change_24haverage)
baseVolumequoteVolumerm  )r  r\  rC  r  safe_tickerr  )r:  r  r  r  r  r  r  r  r  r  rc  r  s               r<  r  zcoinbase.parse_tickerN  s   b vu-vu-		f>>&&"5D>>&&"5D""47G4C((a&9I""47G4C((a&9I##FL9!!(F30##FF3 !
fX&!
1!
 !
 3	!

 3!
 D!
 D!
 4!
 !
 !
 D!
 D!
 T!
 T!
 d!
  $**63PQ!!
" t#!
$ )!
* + 	r=  c                 "   | j                  |ddg       }| j                  |d| j                  d         }| j                  |d| j                  d         }d|i}t        dt	        |            D ]  }||   }| j                  |d      }	| j                  |	|      r| j                  |d      }
|
B| j                  |
d      }| j                  |      }| j                  |
d	      }|}| j                  ||      }|| j                         }||d
<   ||d<   n8t        j                  |d
   |      |d
<   t        j                  |d   |      |d<   |||<   | j                  |	|      s| j                  |d      }| j                  |d      }|!|%| j                  |d      }| j                  |      }| j                  |d      }| j                  |d      }t        j                  ||      }| j                  ||      }| | j                         }||d
<   ||d<   ||d<   nTt        j                  |d
   |      |d
<   t        j                  |d   |      |d<   t        j                  |d   |      |d<   |||<    | j                  |      S )Nr@  r   rj  r   rm  r   balancerw  r  freer  available_balanceholdvalueused)safe_list_2r\  r3  ro  r]  rC  r  rE  r}  r~  r)   
string_addsafe_balance)r:  rJ  rH  balancesr   r   rq  br  rj  r  r  rl  r  r  r~  	availabler  r  s                      r<  parse_custom_balancezcoinbase.parse_custom_balance  s   ##Hfj"E>>&&$,,z2JK^^FFDLL4NO
)q#h-( &	+AqkG##GV4D}}T8,w	:$!%!1!1%!DJ22:>D ,,UH=E D"nnVT:G"&,,.*.+0(*1*<*<WV_e*T+2+=+=gg>NPU+V(#*F4LtZ0 NN74GH	~~gv6(T-=!%!1!1)Z!HJ22:>D++D':D++Iw?D#..tT:E"nnVT:G"&,,.*.*.+0(*1*<*<WV_d*S*1*<*<WV_d*S+2+=+=gg>NPU+V(#*F4LM&	+N   ((r=  c                    | j                          i }d}| j                  |dd      }| j                  |dg      }d}| j                  dd|      \  }}| j	                  | j
                  dd      }|dk(  r"| j                  | j                  ||            }nT|s|dk(  r'd|d<   | j                  | j                  ||            }n&d|d<   | j                  | j                  ||            }||d	<   | j                  ||      S )
a:  
        query for balance and get the amount of funds available for trading or funds locked in orders

        https://docs.cloud.coinbase.com/advanced-trade/reference/retailbrokerageapi_getaccounts
        https://docs.cloud.coinbase.com/sign-in-with-coinbase/docs/api-accounts#list-accounts
        https://docs.cloud.coinbase.com/advanced-trade/reference/retailbrokerageapi_getfcmbalancesummary

        :param dict [params]: extra parameters specific to the exchange API endpoint
        :param boolean [params.v3]: default False, set True to use v3 api endpoint
        :param str [params.type]: "spot"(default) or "swap" or "future"
        :param int [params.limit]: default 250, maximum number of accounts to return
        :returns dict: a `balance structure <https://docs.ccxt.com/#/?id=balance-structure>`
        Nr   FrY   rf  r@   re  r%  rj  )rX  ry  rD  r  rC  r3  &v3PrivateGetBrokerageCfmBalanceSummaryr[  rf  r  r  )r:  rH  r_  rJ  isV3ra  r?  s          r<  fetch_balancezcoinbase.fetch_balance  s    	~~fdE26D6*
!??PTV\]
F!!$,,@_`!BB4;;wX^C_`H"AA"GG99$++gv:VWH"GG00Wf1MNHP $v((6::r=  c                    | j                          d}| j                  |dd      \  }}|r| j                  d||||dddd	      S d}|| j                  |      }d}| j	                  |||      \  }}| j                  | j                  ||            }| j                  |d   |||      }	t        |	      }
|
d	k(  r|	S |
d
z
  }| j                  |	|      }| j                  |di       }| j                  |d      }||dk7  r||d   d<   ||	|<   |	S )a  
        Fetch the history of changes, i.e. actions done by the user or operations that altered the balance. Will return staking rewards, and crypto deposits or withdrawals.

        https://docs.cdp.coinbase.com/coinbase-app/docs/api-transactions#list-transactions

        :param str [code]: unified currency code, default is None
        :param int [since]: timestamp in ms of the earliest ledger entry, default is None
        :param int [limit]: max number of ledger entries to return, default is None
        :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)
        :returns dict: a `ledger structure <https://docs.ccxt.com/#/?id=ledger>`
        Frv   rR  rS  rT  NrU  r@  r   r   rV  rW  rm  )rX  rY  rZ  rw  r  r  r[  parse_ledgerr]  rE  rC  )r:  rl  r  r%  rH  rR  rw  r_  rJ  ledgerra  rb  rc  rV  r`  s                  r<  fetch_ledgerzcoinbase.fetch_ledger[	  sY    	88PZ[&33M4PUW]_t  wG  IM  OR  S  S}}T*HII$PUW]^ AA$++gW]B^_""8F#3XueLVQ;MQJ	~~fi0^^HlB?
!!*.CDVr\28DL./ $F9r=  c                 0    ddi}| j                  |||      S )Nr  r  r  )r:  r  typess      r<  parse_ledger_entry_statusz"coinbase.parse_ledger_entry_status	  s%    
 vv66r=  c           
      @    dddddddddd	}| j                  |||      S )Nr  r  )	buysellfiat_depositfiat_withdrawalexchange_depositexchange_withdrawalr  pro_depositpro_withdrawalr  r:  rj  r  s      r<  parse_ledger_entry_typez coinbase.parse_ledger_entry_type	  s;    ), -#0!(+

 tT22r=  itemc                    | j                  |di       }| j                  |d      }d }t        j                  |d      rd}t        j                  |      }nd}| j                  |d      }| j                  ||      }| j                  ||      }d }| j                  |di       }	| j                  |	d      }
|
;| j                  |
d      }| j                  ||      }| j                  |
d      }||d}| j                  | j                  |d	            }| j                  |d
      }| j                  | j                  |d            }| j                  | j                  |d            }| j                  |d      }d }|&|j                  d      }t        |      }|dkD  r|d   }| j                  |||| j                  |      ||d d ||| j                  |      d d ||d|      S )Nr  r   outinrw  r  r  r  r  r.   rj  r  resource_pathr  r   )rm  r.   r  r  	directionr~  referenceIdreferenceAccountrj  rw  r  beforeafterr  r  )rE  rC  r)   r  
string_negr}  safe_currencyr  r  r  r  rz  r]  safe_ledger_entryrn  r9  )r:  r  rw  
amountInfor  r  r  rl  r  networkInfofeeInfor  feeCurrencyCode	feeAmountr  r.   rj  r  pathr  r  numPartss                         r<  parse_ledger_entryzcoinbase.parse_ledger_entry	  s   h ^^D(B7
!!*h7	VS)I''/FI%%j*=
&&z8<%%j(; nnT9b9...?@ ,,WjAM"55mXNO(((;I!+C NN4#3#3D,#GH	dD)++D,<,<T6,JK//0@0@x0PQo6	JJsOE5zH!|!!H	%%"Y/"  $''/'
  ! 	r=  c                     | j                          | j                  d|       t        dt        | j                              D ]   }| j                  |   }|d   |k(  s|d   c S  y )NFr   rl  r.   )rX  r  ro  r]  r   )r:  rl  rH  rr  r~  s        r<  find_account_idzcoinbase.find_account_id
  sf    5&)q#dmm,- 	%AmmA&Gv$&t}$	% r=  c                 v    | j                  |dd      }|t        | j                  dz         d|i}|||d<   |S )Nr  r  zN prepareAccountRequest() method requires an account_id(or accountId) parameterr%  )r{  r!   r.   )r:  r%  rH  r  r_  s        r<  r  z coinbase.prepare_account_request
  sT    &&v|[I	#DGG.~$~)
 $GGr=  c                    | j                  |dd      }| j                  |ddg      }|I|t        | j                  dz         | j	                  ||      }|t        | j                  dz   |z         d|i}|||d<   ||gS )Nr  r  zz prepareAccountRequestWithCurrencyCode() method requires an account_id(or accountId) parameter OR a currency code argumentzG prepareAccountRequestWithCurrencyCode() could not find account id for r%  )r{  rD  r!   r.   r  r   )r:  rl  r%  rH  r  r_  s         r<  r  z3coinbase.prepare_account_request_with_currency_code
  s    &&v|[I	6L+#>?|'  3o  )o  p  p,,T6:I #DGG.w$wz~$~)
 $GG  r=  r  c                     | j                          | j                  |      }|d   st        | j                  dz         d|d<   | j	                  |dd|d|      S )a  
        create a market buy order by providing the symbol and cost

        https://docs.cloud.coinbase.com/advanced-trade/reference/retailbrokerageapi_postorder

        :param str symbol: unified symbol of the market to create an order in
        :param float cost: how much you want to trade in units of the quote currency
        :param dict [params]: extra parameters specific to the exchange API endpoint
        :returns dict: an `order structure <https://docs.ccxt.com/#/?id=order-structure>`
        r=   z9 createMarketBuyOrderWithCost() supports spot orders onlyFr  r  r  N)rX  r  r%   r.   create_order)r:  r  r  rH  r  s        r<  !create_market_buy_order_with_costz*coinbase.create_market_buy_order_with_cost
  s`     	V$f~tww)ddee6;23  5$fMMr=  rj  r  r  r  c                 &   | j                          | j                  |      }| j                  | j                  dd      }|dz   | j	                         z   |d   |j                         d}	| j                  |g d      }
| j                  |d      }| j                  |d      }|
d	u}|d	u}|d	u}| j                  |d
      }|dk(  rdn| j                  |ddd      }| j                  |d      }| j                  |d      }|dk(  r|r|	|dk(  rdnd}|dk(  s|Y|t        | j                  dz         d| j                  ||      | j                  ||      | j                  ||
      ||di|	d<   nd| j                  ||      | j                  ||      | j                  ||
      |di|	d<   ng|s|rmd	}|r|	|dk(  rdnd}| j                  ||      }n|	|dk(  rdnd}| j                  ||      }d| j                  ||      | j                  ||      ||di|	d<   n|dk(  s|H|t        | j                  dz         d| j                  ||      | j                  ||      ||di|	d<   n|dk(  r,d | j                  ||      | j                  ||      d!i|	d<   nv|d"k(  r,d#| j                  ||      | j                  ||      d!i|	d<   nEd$| j                  ||      | j                  ||      |d%i|	d<   n|s|s|rt        | j                  d&z         |d'   r|dk(  rd	}d}| j                  |d(d)d      \  }}| j                  |d*      }| j                  |d*      }|| j!                  ||      }ny|re|t#        | j                  d+z         | j%                  |      }| j%                  |      }t'        j(                  ||      }| j!                  ||      }n| j!                  ||      }d,d-|ii|	d<   nd,d.| j                  ||      ii|	d<   | j                  |d/      }||d0k(  rd1|	d2<   n
|d3k(  rd4|	d2<   | j                  |g d5      }| j                  |d6d7d      }d	}|rH| j                  |d6d7g      }| j                  |	d8      }	| j+                  | j-                  |	|            }n!| j/                  | j-                  |	|            }| j1                  |d9      }|dur| j3                  |d:      }| j                  |d;      } | j                  |d<      }!|K| j5                  | j6                  d=   | |!       | j9                  | j6                  d>   | |!       t        |!      | j3                  |d?i       }"| j;                  |"|      S )@a  
        create a trade order

        https://docs.cloud.coinbase.com/advanced-trade/reference/retailbrokerageapi_postorder

        :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, quote currency for 'market' 'buy' orders
        :param float [price]: the price to fulfill 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]: price to trigger stop orders
        :param float [params.triggerPrice]: price to trigger stop orders
        :param float [params.stopLossPrice]: price to trigger stop-loss orders
        :param float [params.takeProfitPrice]: price to trigger take-profit orders
        :param bool [params.postOnly]: True or False
        :param str [params.timeInForce]: 'GTC', 'IOC', 'GTD' or 'PO', 'FOK'
        :param str [params.stop_direction]: 'UNKNOWN_STOP_DIRECTION', 'STOP_DIRECTION_STOP_UP', 'STOP_DIRECTION_STOP_DOWN' the direction the stopPrice is triggered from
        :param str [params.end_time]: '2023-05-25T17:01:05.092Z' for 'GTD' orders
        :param float [params.cost]: *spot market buy only* the quote quantity that can be used alternative for the amount
        :param boolean [params.preview]: default to False, wether to use the test/preview endpoint or not
        :param float [params.leverage]: default to 1, the leverage to use for the order
        :param str [params.marginMode]: 'cross' or 'isolated'
        :param str [params.retail_portfolio_id]: portfolio uid
        :param boolean [params.is_max]: Used in conjunction with tradable_balance to indicate the user wants to use their entire tradable balance
        :param str [params.tradable_balance]: amount of tradable balance
        :returns dict: an `order structure <https://docs.ccxt.com/#/?id=order-structure>`
        r   r   r  r.   )client_order_idr  r  )	stopPrice
stop_pricer  r  r  Nr  r  TpostOnly	post_onlyFend_timestop_directionr%  r  STOP_DIRECTION_STOP_DOWNSTOP_DIRECTION_STOP_UPr  z= createOrder() requires an end_time parameter for a GTD orderstop_limit_stop_limit_gtd)	base_sizelimit_pricer  r  r  order_configurationstop_limit_stop_limit_gtc)r  r  r  r  limit_limit_gtd)r  r  r  r  r  sor_limit_ioc)r  r  r  limit_limit_foklimit_limit_gtc)r  r  r  z3 createOrder() only stop limit orders are supportedr=   rP   r  r  a	   createOrder() requires a price argument for market buy orders on spot markets to calculate the total amount to spend(amount * price), alternatively set the createMarketBuyOrderRequiresPrice option or param to False and pass the cost to spend in the amount argumentmarket_market_ioc
quote_sizer  r  isolatedISOLATEDmargin_typecrossCROSS)r  r  r  r  r  r  stopDirectionr  clientOrderIdr  r  r  r  previewtestr
  successerror_responseerrormessager   r   success_response)rX  r  rC  r3  ri  uppersafe_number_nr  safe_bool_2r   r.   amount_to_precisionprice_to_precisionr%   rY  rD  cost_to_precisionr#   number_to_stringr)   r  #v3PrivatePostBrokerageOrdersPreviewr[  v3PrivatePostBrokerageOrdersry  rE  throw_exactly_matched_exceptionr   throw_broadly_matched_exceptionparse_order)#r:  r  rj  r  r  r  rH  r  r.   r_  r  r  r  isStop
isStopLossisTakeProfitr  r  endTimer#  	tpslPricer  r  r  r  r  costRequestr  r%  rJ  r'  errorResponse
errorTitleerrorMessager@  s#                                      r<  r  zcoinbase.create_order
  s   : 	V$dllJ?!Cx$))+5 ,JJL

 ))&2]^((A**63DET)"$.
&d2&&v}='4/4d6F6Fvz[fhm6n""6:6((1AB7? (CG5=$>WoM5(g.A+DGG6u,uvv3)-)A)A&&)Q+/+B+B65+Q*.*A*A&,*W.;(/66G12 4)-)A)A&&)Q+/+B+B65+Q*.*A*A&,*W.;	66G12 | 	$,EIU](@Ys $ 7 7 NI$,GKu}(B[s $ 7 7 PI/%)%=%=ff%M'+'>'>vu'M&/*7	22-.  5(g.A+DGG6u,uvv))-)A)A&&)Q+/+B+B65+Q(/)1	,6G12 !E)')-)A)A&&)Q+/+B+B65+Q*6G12 !E)))-)A)A&&)Q+/+B+B65+Q,6G12 *)-)A)A&&)Q+/+B+B65+Q)1,6G12 |"477-b#bccf~45=481<@<Y<YZ`bo  rU  W[  =\916''7662# 2264@E6}*477  6A  ,A  B  B'+'<'<V'D&*&;&;E&B&-&8&8{&S $ 6 6v{ K 2266BE'$e*2-. (#T%=%=ff%M*2-.
 %%fl;
!Z')3&w&)0&6  $i  j""69feDYYv	6':;Fii):;G??GU[@\]H88Wf9UVHL ..95$ NN85EFM))-AJ++M9EL(44T__W5Mz[gh44T__W5Mz[gh#L11~~h(:B?f--r=  r  c           
         | j                  |d      }| j                  ||d      }|| j                  ||      }| j                  |di       }| j                  |d      }| j                  |d      }| j                  |d      }| j                  |d      }	| j                  |d      }
| j                  |d	      }|d uxs
 |d uxs |d u}|	d uxs |
d u}d }d }d }d }|rEd }||}n||}n|}| j                  |d
      }| j                  |d      }| j	                  |d      }nc|rO|	|	n|
}| j                  |d
      }| j                  |d      }| j	                  |d      }| j                  |d      }n| j                  |d      }| j                  |d      }| j                  |d      }d }|||d   }| j                  i d|d| j                  |d      d| j                  |d      d| j                  |      d|dd d|d| j                  | j                  |d            d| j                  | j                  |d            d|d| j                  |d      d |d!|d"|d#| j                  |d$      d%d d&d | j                  |d'      | j                  | j                  |d(            | j                  |d      |d)d d*|      S )+Nr  r  r  r  r  r  r  r  r  r  r  r  r  created_time
total_feesr  rm  r.   r  r$  r
  r  r  lastTradeTimestampr  rj  
order_typer  time_in_forcer  r  r  r  r  filledfilled_size	remainingr  average_filled_pricer  r  )r  r  r  r  )rC  safe_symbolr  rE  ry  
safe_orderr  parse_order_typeparse_time_in_forcer|  parse_order_status)r:  r  r  r  r  orderConfigurationlimitGTClimitGTDlimitIOCstopLimitGTCstopLimitGTD	marketIOCisLimitr8  r  r  r  r  target
stopTargetr  	totalFeescurrencyFees                          r<  r7  zcoinbase.parse_order  s   ~ ##E<8!!(FC8%%ff5F!^^E3H"M>>"46GH>>"46GH>>"4oF~~&8:UV~~&8:UVNN#57JK	D(]hd.B]X\H\t+JT1IF#!%!!$$V];E%%fk:F~~fk:H*6*BJ$$Z?E%%j+>F~~j+>H++JEL%%i=F##E>:$$UL9	!(: /K  
E 
$""5*5 
 T--e5FG 
 1	 

  
 !$ 
 f 
 D))$*:*:5,*OP 
 433D4D4DUO4\] 
  
 D**5&9 
 U 
 L 
 f 
 d&&um< 
  ! 
" D# 
$ ''/EF--d.>.>uh.OP((=' 1 
2 3 	r=  c                 :    dddddd d}| j                  |||      S )Nr  closedr  )OPENFILLED	CANCELLEDEXPIREDFAILEDUNKNOWN_ORDER_STATUSr  r  s      r<  rO  zcoinbase.parse_order_status]  s2    #! $(
 &&99r=  c                 B    |dk(  ry ddddd}| j                  |||      S )NUNKNOWN_ORDER_TYPEr  r%  )MARKETLIMITSTOP
STOP_LIMITr  r  s      r<  rM  zcoinbase.parse_order_typeh  s8    ''!	
 tT22r=  r  c                 8    ddddd d}| j                  |||      S )NGTCr  r  r  )GOOD_UNTIL_CANCELLEDGOOD_UNTIL_DATE_TIMEIMMEDIATE_OR_CANCELFILL_OR_KILLUNKNOWN_TIME_IN_FORCEr  )r:  r  timeInForcess      r<  rN  zcoinbase.parse_time_in_forces  s/    $)$)#(!%)
 k;GGr=  r.   c                 p    | j                          | j                  |g||      }| j                  |di       S )a  
        cancels an open order

        https://docs.cloud.coinbase.com/advanced-trade/reference/retailbrokerageapi_cancelorders

        :param str id: order id
        :param str symbol: not used by coinbase 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   )rX  cancel_ordersrE  )r:  r.   r  rH  orderss        r<  cancel_orderzcoinbase.cancel_order}  s9     	##RD&&9~~fa,,r=  c                 v   | j                          d}|| j                  |      }d|i}| j                  | j                  ||            }| j	                  |dg       }t        dt        |            D ]3  }| j                  ||   d      }	|	dust        | j                  dz          | j                  ||      S )a  
        cancel multiple orders

        https://docs.cloud.coinbase.com/advanced-trade/reference/retailbrokerageapi_cancelorders

        :param str[] ids: order ids
        :param str symbol: not used by coinbase cancelOrders()
        :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>`
        N	order_idsr  r   r'  Tz? cancelOrders() has failed, check your arguments and parameters)rX  r  'v3PrivatePostBrokerageOrdersBatchCancelr[  r\  ro  r]  ry  r"   r.   parse_orders)
r:  idsr  rH  r  r_  rJ  rt  rr  r'  s
             r<  rs  zcoinbase.cancel_orders  s     	[[(F
 ??GU[@\] )R8q#f+& 	nAnnVAY	:Gd" +l!lmm	n   00r=  c                    | j                          | j                  |      }d|i}	|| j                  ||      |	d<   || j                  ||      |	d<   | j	                  |ddd      }
d}|
r6| j                  |ddg      }| j                  | j                  |	|            }n!| j                  | j                  |	|            }| j                  ||      S )aN  
        edit a trade order

        https://docs.cloud.coinbase.com/advanced-trade/reference/retailbrokerageapi_editorder

        :param str id: cancel order id
        :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 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
        :param boolean [params.preview]: default to False, wether to use the test/preview endpoint or not
        :returns dict: an `order structure <https://docs.ccxt.com/#/?id=order-structure>`
        r  Nr  r  r%  r&  F)
rX  r  r/  r0  r.  rD  'v3PrivatePostBrokerageOrdersEditPreviewr[   v3PrivatePostBrokerageOrdersEditr7  )r:  r.   r  rj  r  r  r  rH  r  r_  r%  rJ  s               r<  
edit_orderzcoinbase.edit_order  s      	V$
 "66vvFGFO#66vuEGG""69feDYYv	6':;FCCDKKPWY_D`aH<<T[[RX=YZH &11r=  c                     | j                          d}|| j                  |      }d|i}| j                  | j                  ||            }| j	                  |di       }| j                  ||      S )a  
        fetches information on an order made by the user

        https://docs.cloud.coinbase.com/advanced-trade/reference/retailbrokerageapi_gethistoricalorder

        :param str id: the order id
        :param str symbol: unified market symbol that the order was made in
        :param dict [params]: extra parameters specific to the exchange API endpoint
        :returns dict: An `order structure <https://docs.ccxt.com/#/?id=order-structure>`
        Nr  r  )rX  r  ,v3PrivateGetBrokerageOrdersHistoricalOrderIdr[  rE  r7  )r:  r.   r  rH  r  r_  rJ  r  s           r<  fetch_orderzcoinbase.fetch_order  s|     	[[(F
 DDT[[QXZ`EabP x"5v..r=  rU  c                 v   | j                          d}| j                  |dd      \  }}|r| j                  d||||dddd	      S d}|| j                  |      }i }||d   |d<   |||d	<   || j	                  |      |d
<   | j                  |dg      }|'| j                  |dg      }| j	                  |      |d<   | j                  | j                  ||            }	| j                  |	dg       }
| j                  |
d      }| j                  |	d      }||dk7  r
||d<   ||
d<   | j                  |
|||      S )a  
        fetches information on multiple orders made by the user

        https://docs.cloud.coinbase.com/advanced-trade/reference/retailbrokerageapi_gethistoricalorders

        :param str symbol: unified market symbol that the orders were made in
        :param int [since]: the earliest time in ms to fetch orders
        :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 trades 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   rR  r`  Nry  r.   r  r%  
start_dateuntilend_datert  r   rW  )rX  rY  rZ  r  rn  safe_integer_nrD  *v3PrivateGetBrokerageOrdersHistoricalBatchr[  r\  rE  rC  ry  )r:  r  r  r%  rH  rR  r  r_  r  rJ  rt  firstr`  s                r<  fetch_orderszcoinbase.fetch_orders  s    	88PZ[&33M65RWY_aiksuy{  A  A[[(F$*4LGL!$GG$(LL$7GL!##FWI6YYvy1F"&,,u"5GJBB4;;wX^C_`V (B7vq)!!(H5Vr\$E(OF1I  >>r=  c                    | j                          d }|| j                  |      }d|i}||d   |d<   |d}||d<   || j                  |      |d<   | j                  |dg      }|'| j	                  |dg      }| j                  |      |d<   | j                  | j                  ||            }	| j                  |	d	g       }
| j                  |
d
      }| j                  |	d      }||dk7  r
||d<   ||
d
<   | j                  |
|||      S )Norder_statusr.   r  rU  r%  r  r  r  rt  r   r`  rW  )rX  r  rn  r  rD  r  r[  r\  rE  rC  ry  )r:  r  r  r  r%  rH  r  r_  r  rJ  rt  r  r`  s                r<  fetch_orders_by_statuszcoinbase.fetch_orders_by_statusm  s=   [[(FF
 $*4LGL!=E $(LL$7GL!##FWI6YYvy1F"&,,u"5GJBB4;;wX^C_`V (B7vq)!!(H5Vr\$E(OF1I  >>r=  c                     | j                          d}| j                  |dd      \  }}|r| j                  d||||dddd	      S | j                  d||||      S )a  
        fetches information on all currently open orders

        https://docs.cloud.coinbase.com/advanced-trade/reference/retailbrokerageapi_gethistoricalorders

        :param str symbol: unified market symbol of the orders
        :param int [since]: timestamp in ms of the earliest order, default is None
        :param int [limit]: the maximum number of open order structures to retrieve
        :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 [availble parameters](https://github.com/ccxt/ccxt/wiki/Manual#pagination-params)
        :param int [params.until]: the latest time in ms to fetch trades for
        :returns Order[]: a list of `order structures <https://docs.ccxt.com/#/?id=order-structure>`
        Fr   rR  r`  NrU  r^  rX  rY  rZ  r  r:  r  r  r%  rH  rR  s         r<  fetch_open_orderszcoinbase.fetch_open_orders  s~     	88ART^_&334EvuV[]cemowy}  @C  D  D**665%PPr=  c                     | j                          d}| j                  |dd      \  }}|r| j                  d||||dddd	      S | j                  d||||      S )a  
        fetches information on multiple closed orders made by the user

        https://docs.cloud.coinbase.com/advanced-trade/reference/retailbrokerageapi_gethistoricalorders

        :param str symbol: unified market symbol of the orders
        :param int [since]: timestamp in ms of the earliest order, default is None
        :param int [limit]: the maximum number of closed order structures to retrieve
        :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 [availble parameters](https://github.com/ccxt/ccxt/wiki/Manual#pagination-params)
        :param int [params.until]: the latest time in ms to fetch trades for
        :returns Order[]: a list of `order structures <https://docs.ccxt.com/#/?id=order-structure>`
        Fr^   rR  r`  NrU  r_  r  r  s         r<  fetch_closed_orderszcoinbase.fetch_closed_orders  s     	88ATV`a&334GQVX]_egoqy{  BE  F  F**8VUE6RRr=  c                 ,    | j                  d||||      S )a]  
        fetches information on multiple canceled orders made by the user

        https://docs.cloud.coinbase.com/advanced-trade/reference/retailbrokerageapi_gethistoricalorders

        :param str symbol: unified market symbol of the orders
        :param int [since]: timestamp in ms of the earliest order, default is None
        :param int [limit]: the maximum number of canceled order structures to retrieve
        :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>`
        r`  )r  )r:  r  r  r%  rH  s        r<  fetch_canceled_orderszcoinbase.fetch_canceled_orders  s     **;ufUUr=  r   c           
         | j                          d}||nt        ||      }d}| j                  |ddd      \  }}|r| j                  d||||||dz
        S | j	                  |      }|d   | j                  | j                  ||      d}	| j                  |d	d
g      }
| j                  |d	g      }| j                  |      }||z  }d}|$| j                  | j                  |dz              }n8t        | j                               }t        j                  |t        |            }||	d<   |
'| j                  | j                  |
dz              |	d
<   n"t        j                   |t        |            |	d
<   d}d}| j                  |ddd      \  }}|r"| j#                  | j%                  |	|            }n!| j'                  | j%                  |	|            }| j)                  |dg       }| j+                  |||||      S )a  
        fetches historical candlestick data containing the open, high, low, and close price, and the volume of a market

        https://docs.cloud.coinbase.com/advanced-trade/reference/retailbrokerageapi_getpubliccandles

        :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, not used by coinbase
        :param dict [params]: extra parameters specific to the exchange API endpoint
        :param int [params.until]: the latest time in ms to fetch trades 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)
        :param boolean [params.usePrivate]: default False, when True will use the private endpoint to fetch the candles
        :returns int[][]: A list of candles ordered, open, high, low, close, volume
        r+  NFr   rR  r   r.   )r  granularityr  endry  startr   candles)rX  r  rY  "fetch_paginated_call_deterministicr  rC  r   r  rD  parse_timeframer2  parse_to_intstrsecondsr)   
string_subr  -v3PrivateGetBrokerageProductsProductIdCandlesr[  2v3PublicGetBrokerageMarketProductsProductIdCandlesr\  parse_ohlcvs)r:  r  	timeframer  r%  rH  maxLimitrR  r  r_  r  durationrequestedDurationsinceStringr  rJ  r   r  s                     r<  fetch_ohlcvzcoinbase.fetch_ohlcv  s     	"]UH1E88z[`a&::<QVX]_hjprz}~r~V$ ,++DOOY	R
 ##FWe,<=6G9-''	2!H,//0A0A%$,0OPKdlln%C!,,S#6G2HIK&!2243D3DUT\3RSGEN %//SAR=STGEN
!::6<Q]_de
FII$++V]_eJfgHNNt{{[bdjOklH ..9b9  &)UEJJr=  c           	          | j                  |d      | j                  |d      | j                  |d      | j                  |d      | j                  |d      | j                  |d      gS )Nr  r  r  r  r  volume)safe_timestampr  )r:  ohlcvr  s      r<  parse_ohlcvzcoinbase.parse_ohlcv/  sn     w/UF+UF+UE*UG,UH-
 	
r=  c                    | j                          | j                  |      }d|d   i}|&| j                  | j                  |dz              |d<   |t	        |d      |d<   d}| j                  |dd      \  }}|'| j                  | j                  |dz              |d	<   n|t        | j                  d
z         d}d}	| j                  |ddd      \  }	}|	r"| j                  | j                  ||            }n!| j                  | j                  ||            }| j                  |dg       }
| j                  |
|||      S )a  
        get the list of most recent trades for a particular symbol

        https://docs.cloud.coinbase.com/advanced-trade/reference/retailbrokerageapi_getpublicmarkettrades

        :param str symbol: unified market symbol of the trades
        :param int [since]: not used by coinbase fetchTrades
        :param int [limit]: the maximum number of trade structures to fetch
        :param dict [params]: extra parameters specific to the exchange API endpoint
        :param boolean [params.usePrivate]: default False, when True will use the private endpoint to fetch the trades
        :returns Trade[]: a list of `trade structures <https://docs.ccxt.com/#/?id=public-trades>`
        r  r.   Nry  r  r%  r   r  r  zI fetchTrades() requires a `until` parameter when you use `since` argumentFr   r  )rX  r  r2  r  r  rY  r!   r.   r  r[  r  r\  r  )r:  r  r  r%  rH  r  r_  r  rJ  r   r  s              r<  fetch_tradeszcoinbase.fetch_tradesE  sa    	V$&,
 #44T5F5Fut|5TUGG"5$/GG55fmWUv!2243D3DUT\3RSGEN#DGG.y$yzz
!::6=R^`ef
FHHU\^dIefHMMdkkZaciNjkH" (B7  >>r=  c                 v   | j                          d}| j                  |dd      \  }}|r| j                  d||||dddd	      S d}|| j                  |      }i }||d   |d<   |||d	<   || j	                  |      |d
<   | j                  |dg      }|'| j                  |dg      }| j	                  |      |d<   | j                  | j                  ||            }	| j                  |	dg       }
| j                  |
d      }| j                  |	d      }||dk7  r
||d<   ||
d<   | j                  |
|||      S )ai  
        fetch all trades made by the user

        https://docs.cloud.coinbase.com/advanced-trade/reference/retailbrokerageapi_getfills

        :param str symbol: unified market symbol of the trades
        :param int [since]: timestamp in ms of the earliest order, default is None
        :param int [limit]: the maximum number of trade structures to fetch
        :param dict [params]: extra parameters specific to the exchange API endpoint
        :param int [params.until]: the latest time in ms to fetch trades 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 Trade[]: a list of `trade structures <https://docs.ccxt.com/#/?id=trade-structure>`
        Fr~   rR  r`  Nre  r.   r  r%  start_sequence_timestampr  end_sequence_timestampfillsr   rW  )rX  rY  rZ  r  rn  r  rD  *v3PrivateGetBrokerageOrdersHistoricalFillsr[  r\  rE  rC  r  )r:  r  r  r%  rH  rR  r  r_  r  rJ  r  r  r`  s                r<  fetch_my_tradeszcoinbase.fetch_my_trades{  s    	88R\]&33OVUTY[ackmuw{  ~A  B  B[[(F$*4LGL!$GG26,,u2EG./##FWI6YYvy1F04U0CG,-BB4;;wX^C_`0 '26vq)!!(H5Vr\$E(OF1I  >>r=  c           	         | j                          | j                  |      }d|d   i}|||d<   d}d}| j                  |ddd      \  }}|r"| j                  | j	                  ||            }n!| j                  | j	                  ||            }| j                  |di       }| j                  |d	      }	| j                  |	      }
| j                  |||
d
ddd      S )a  
        fetches information on open orders with bid(buy) and ask(sell) prices, volumes and other data

        https://docs.cloud.coinbase.com/advanced-trade/reference/retailbrokerageapi_getpublicproductbook

        :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
        :param boolean [params.usePrivate]: default False, when True will use the private endpoint to fetch the order book
        :returns dict: A dictionary of `order book structures <https://docs.ccxt.com/#/?id=order-book-structure>` indexed by market symbols
        r  r.   Nr%  Fr   r   	pricebookr   r  r  r  r  )
rX  r  rY   v3PrivateGetBrokerageProductBookr[  %v3PublicGetBrokerageMarketProductBookrE  rC  r  parse_order_book)r:  r  r%  rH  r  r_  rJ  r   r@  r   r  s              r<  fetch_order_bookzcoinbase.fetch_order_book  s     	V$&,
 $GG
!::6CSUachi
F<<T[[RX=YZHAA$++gW]B^_H* ~~hR8f-NN4(	$$T69ffgW]^^r=  c                     | j                          | j                  |      }i }|| j                  |      |d<   | j                  | j	                  ||            }| j                  |dg       }| j                  ||      S )a  
        fetches the bid and ask price and volume for multiple markets

        https://docs.cloud.coinbase.com/advanced-trade/reference/retailbrokerageapi_getbestbidask

        :param str[] [symbols]: unified symbols of the markets to fetch the bids and asks for, all markets 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  
pricebooks)rX  r  r  v3PrivateGetBrokerageBestBidAskr[  r\  parse_tickers)r:  r  rH  r_  rJ  tickerss         r<  fetch_bids_askszcoinbase.fetch_bids_asks  s     	%%g.%)__W%=GM"77GV8TU. ..<<!!'733r=  r  c                 $   | j                  ||      \  }}| j                  |       | j                          | j                  |      }| j	                  |dd      }| j                  |ddg      }|I|t        | j                  dz         | j                  ||      }|t        | j                  dz   |z         |d|||d   d}|||d<   | j                  | j                  ||            }	| j                  |	d	i       }
| j                  |
|      S )
a  
        make a withdrawal

        https://docs.cloud.coinbase.com/sign-in-with-coinbase/docs/api-transactions#send-money

        :param str code: unified currency code
        :param float amount: the amount to withdraw
        :param str address: the address to withdraw to
        :param str [tag]: an optional tag for the withdrawal
        :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  zV withdraw() requires an account_id(or accountId) parameter OR a currency code argumentz* withdraw() could not find account id for r  r.   )r  rj  r  r  rw  r  r@  )handle_withdraw_tag_and_paramscheck_addressrX  rw  r{  rD  r!   r.   r  r   *v2PrivatePostAccountsAccountIdTransactionsr[  rE  r  )r:  rl  r  r  r  rH  rw  r  r_  rJ  r@  s              r<  r   zcoinbase.withdraw  s:    99#vFV7#==&&&v|[I	6L+#>?|'  3K  )K  L  L,,T6:I #DGG.Z$Z]a$abb# 
 ?),G%&BB4;;wX^C_`j ~~h3%%dH55r=  c                 ,   | j                          | j                  |      }d}| j                  |d   d|      \  }}| j                  | j	                  ||            }| j                  |dg       }| j                  |dd      }| j                  |d      S )a  
        fetch the deposit address for a currency associated with self account

        https://docs.cloud.coinbase.com/exchange/reference/exchangerestapi_postcoinbaseaccountaddresses

        :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>`
        Nrl  r@  Fr  )rX  rw  r  &v2PrivateGetAccountsAccountIdAddressesr[  r\  parse_deposit_addressesr)  )r:  rl  rH  rw  r_  rJ  r@  addressStructuress           r<  "fetch_deposit_addresses_by_networkz+coinbase.fetch_deposit_addresses_by_networkr  s     	==&II(SYJZ\`bhi>>t{{7TZ?[\p ~~h3 88tUK}}.	::r=  c                    | j                  |d      }| j                  |       | j                  |d      }| j                  d |      }| j                  |d      }d }|#|j                  d      }| j                  |d      }| j	                  |d      }	|| j                  ||      | j                  ||      || j                  |	d      dS )	Nr  r  address_labelrx  r   address_infor  )rm  rw  r  r  r  )rC  r  r}  rz  rE  r  )
r:  depositAddressrw  r  r  rl  addressLabelr  splitAddressLabeladdressInfos
             r<  parse_deposit_addresszcoinbase.parse_deposit_address  s    X "">9=7#$$^Y?	&&tX6''H
# , 2 23 7))*;Q?Jnn^^D"//
HE..y$?##K1BC
 	
r=  c                    | j                          | j                  |dd      }| j                  |ddg      }|I|t        | j                  dz         | j                  ||      }|t        | j                  dz   |z         || j                  |      |j                         |dd}| j                  | j                  ||            }| j                  |ddi       }| j                  |      S )	ac  
        make a deposit

        https://docs.cloud.coinbase.com/sign-in-with-coinbase/docs/api-deposits#deposit-funds

        :param str code: unified currency code
        :param float amount: the amount to deposit
        :param str id: the payment method id to be used for the deposit, can be retrieved from v2PrivateGetPaymentMethods
        :param dict [params]: extra parameters specific to the exchange API endpoint
        :param str [params.accountId]: the id of the account to deposit into
        :returns dict: a `transaction structure <https://docs.ccxt.com/#/?id=transaction-structure>`
        r  r  zU deposit() requires an account_id(or accountId) parameter OR a currency code argumentz) deposit() could not find account id for T)r  r  rw  payment_methodcommitr@  transfer)rX  r{  rD  r!   r.   r  r   r2  r,  &v2PrivatePostAccountsAccountIdDepositsr[  safe_dict_2r  )	r:  rl  r  r.   rH  r  r_  rJ  r@  s	            r<  rV   zcoinbase.deposit  s    	&&v|[I	6L+#>?|'  3J  )J  K  K,,T6:I #DGG.Y$Y\`$`aa#++F3

 
 >>t{{7TZ?[\L &*bA%%d++r=  c                    | j                          | j                  |dd      }| j                  |ddg      }|I|t        | j                  dz         | j                  ||      }|t        | j                  dz   |z         ||d}| j                  | j                  ||            }| j                  |ddi       }| j                  |      S )a0  
        fetch information on a deposit, fiat only, for crypto transactions use fetchLedger

        https://docs.cloud.coinbase.com/sign-in-with-coinbase/docs/api-deposits#show-deposit

        :param str id: deposit id
        :param str [code]: unified currency code
        :param dict [params]: extra parameters specific to the exchange API endpoint
        :param str [params.accountId]: the id of the account that the funds were deposited into
        :returns dict: a `transaction structure <https://docs.ccxt.com/#/?id=transaction-structure>`
        r  r  zZ fetchDeposit() requires an account_id(or accountId) parameter OR a currency code argumentz. fetchDeposit() could not find account id for )r  
deposit_idr@  r  )rX  r{  rD  r!   r.   r  r   .v2PrivateGetAccountsAccountIdDepositsDepositIdr[  r  r  )r:  r.   rl  rH  r  r_  rJ  r@  s           r<  fetch_depositzcoinbase.fetch_deposit@  s     	&&v|[I	6L+#>?|'  3O  )O  P  P,,T6:I #DGG.^$^ae$eff#
 FFt{{SZ\bGcdL &*bA%%d++r=  c                     | j                          | j                  |      }| j                  |dg       }| j                  |      S )a  
        fetch the deposit id for a fiat currency associated with self account

        https://docs.cdp.coinbase.com/advanced-trade/reference/retailbrokerageapi_getpaymentmethods

        :param dict [params]: extra parameters specific to the exchange API endpoint
        :returns dict: an array of `deposit id structures <https://docs.ccxt.com/#/?id=deposit-id-structure>`
        payment_methods)rX  #v3PrivateGetBrokeragePaymentMethodsr\  parse_deposit_method_ids)r:  rH  rJ  rq  s       r<  fetch_deposit_method_idsz!coinbase.fetch_deposit_method_ids  sF     	;;FC( *;R@,,V44r=  c                     | j                          d|i}| j                  | j                  ||            }| j                  |di       }| j	                  |      S )a  
        fetch the deposit id for a fiat currency associated with self account

        https://docs.cdp.coinbase.com/advanced-trade/reference/retailbrokerageapi_getpaymentmethod

        :param str id: the deposit payment method id
        :param dict [params]: extra parameters specific to the exchange API endpoint
        :returns dict: a `deposit id structure <https://docs.ccxt.com/#/?id=deposit-id-structure>`
        payment_method_idr  )rX  2v3PrivateGetBrokeragePaymentMethodsPaymentMethodIdr[  rE  parse_deposit_method_id)r:  r.   rH  r_  rJ  rq  s         r<  fetch_deposit_method_idz coinbase.fetch_deposit_method_id  sa     	
 JJ4;;W^`fKgh$ *:B?++F33r=  c                     g }t        dt        |            D ]7  }| j                  | j                  ||         |      }|j	                  |       9 |S )Nr   )ro  r]  r[  r  rp  )r:  rz  rH  rq  rr  r.   s         r<  r  z!coinbase.parse_deposit_method_ids  sS    q#c(# 	AT99#a&A6JBMM"	 r=  c                     || j                  |d      | j                  |d      | j                  |d      | j                  |d      dS )Nr.   rw  verifiedr/   )rm  r.   rw  r  r  )rC  ry  )r:  	depositIds     r<  r  z coinbase.parse_deposit_method_id  sM    ""9d3((J?y*=##Iv6
 	
r=  fromCodetoCodec                     | j                          ||| j                  |      d}| j                  | j                  ||            }| j	                  |di       }| j                  |      S )a  
        fetch a quote for converting from one currency to another

        https://docs.cloud.coinbase.com/advanced-trade/reference/retailbrokerageapi_createconvertquote

        :param str fromCode: the currency that you want to sell and convert from
        :param str toCode: the currency that you want to buy and convert into
        :param float [amount]: how much you want to trade in units of the from currency
        :param dict [params]: extra parameters specific to the exchange API endpoint
        :param dict [params.trade_incentive_metadata]: an object to fill in user incentive data
        :param str [params.trade_incentive_metadata.user_incentive_id]: the id of the incentive
        :param str [params.trade_incentive_metadata.code_val]: the code value of the incentive
        :returns dict: a `conversion structure <https://docs.ccxt.com/#/?id=conversion-structure>`
        )from_account
to_accountr  r  )rX  r2  "v3PrivatePostBrokerageConvertQuoter[  rE  parse_conversion)r:  r  r  r  rH  r_  rJ  r@  s           r<  fetch_convert_quotezcoinbase.fetch_convert_quote  sl     	$ ++F3

 ::4;;wPV;WX~~h4$$T**r=  c                     | j                          |||d}| j                  | j                  ||            }| j                  |di       }| j	                  |      S )a  
        convert from one currency to another

        https://docs.cloud.coinbase.com/advanced-trade/reference/retailbrokerageapi_commitconverttrade

        :param str id: the id of the trade that you want to make
        :param str fromCode: the currency that you want to sell and convert from
        :param str toCode: the currency that you want to buy and convert into
        :param float [amount]: how much you want to trade in units of the from currency
        :param dict [params]: extra parameters specific to the exchange API endpoint
        :returns dict: a `conversion structure <https://docs.ccxt.com/#/?id=conversion-structure>`
        r  r  r  r  )rX  )v3PrivatePostBrokerageConvertTradeTradeIdr[  rE  r  )	r:  r.   r  r  r  rH  r_  rJ  r@  s	            r<  create_convert_tradezcoinbase.create_convert_trade  sa     	$ 

 AA$++gW]B^_~~h4$$T**r=  c                 h   | j                          |t        | j                  dz         | j                  |d      }|t        | j                  dz         | j	                  |d      }|||d}| j                  | j                  ||            }| j                  |di       }| j                  |      S )a<  
        fetch the data for a conversion trade

        https://docs.cloud.coinbase.com/advanced-trade/reference/retailbrokerageapi_getconverttrade

        :param str id: the id of the trade that you want to commit
        :param str code: the unified currency code that was converted from
        :param dict [params]: extra parameters specific to the exchange API endpoint
        :param strng params['toCode']: the unified currency code that was converted into
        :returns dict: a `conversion structure <https://docs.ccxt.com/#/?id=conversion-structure>`
        z- fetchConvertTrade() requires a code argumentr  z0 fetchConvertTrade() requires a toCode parameterr  r  )	rX  r!   r.   rC  rD  (v3PrivateGetBrokerageConvertTradeTradeIdr[  rE  r  )r:  r.   rl  rH  r  r_  rJ  r@  s           r<  fetch_convert_tradezcoinbase.fetch_convert_trade  s     	<#DGG.]$]^^!!&(3>#DGG.`$`aa68,  

 @@WV\A]^~~h4$$T**r=  
conversionfromCurrency
toCurrencyc                 x   | j                  |d      }| j                  ||      }| j                  |d      }| j                  ||      }| j                  |d      }| j                  |d      }	| j                  |	d      }
|d d | j                  |d      || j                  |d      |d d | j                  |
d      d
S )	Nsource_currencytarget_currencyuser_entered_amount	total_feer  r.   r  )
rm  r  r  r.   r  
fromAmountr  toAmountr  r  )rC  r}  rE  r  )r:  r  r  r  fromCoinr  r  r  fromAmountStructurefeeStructurefeeAmountStructures              r<  r  zcoinbase.parse_conversion"  s    ##J0AB**8\Bj*;<((Z8"nnZ9NO~~j+>!^^L(C"":t4$**+>H ##$6@
 	
r=  c                    | j                          | j                  |      }|d   st        | j                  dz         | j	                  |dd      }| j                  |d      }d|d   i}|t        | j                  dz         ||d<   | j                  | j                  ||            }| j                  |di       }| j                  |      S )	au  
        *futures only* closes open positions for a market

        https://coinbase-api.github.io/docs/#/en-us/swapV2/trade-api.html#One-Click%20Close%20All%20Positions

        :param str symbol: Unified CCXT market symbol
        :param str [side]: not used by coinbase
        :param dict [params]: extra parameters specific to the coinbase api endpoint
 @param {str}  params.clientOrderId *mandatory* the client order id of the position to close
        :param float [params.size]: the size of the position to close, optional
        :returns dict: an `order structure <https://docs.ccxt.com/#/?id=order-structure>`
        r@   z3 closePosition() only supported for futures marketsr
  r$  r  r.   z3 closePosition() requires a clientOrderId parameterr+  )rX  r  r%   r.   r{  rD  r!   )v3PrivatePostBrokerageOrdersClosePositionr[  rE  r7  )	r:  r  r  rH  r  r$  r_  rJ  r  s	            r<  close_positionzcoinbase.close_position7  s     	V$htww)^^__**63DoV6?3&,
  #DGG.c$cdd%2!"AA$++gW]B^_x);R@&&r=  c                    | j                          | j                  |      }d}|| j                  |d         }d}| j                  d||      \  }}d}|dk(  r| j	                  |      }nWd}| j                  |dd      \  }}|t        | j                  dz         d|i}| j                  | j                  ||            }| j                  |dg       }| j                  ||      S )	aC  
        fetch all open positions

        https://docs.cloud.coinbase.com/advanced-trade/reference/retailbrokerageapi_getfcmpositions
        https://docs.cloud.coinbase.com/advanced-trade/reference/retailbrokerageapi_getintxpositions

        :param str[] [symbols]: list of unified market symbols
        :param dict [params]: extra parameters specific to the exchange API endpoint
        :param str [params.portfolio]: the portfolio UUID to fetch positions for
        :returns dict[]: a list of `position structure <https://docs.ccxt.com/#/?id=position-structure>`
        Nr   r   r@   rs  z fetchPositions() requires a "portfolio" value in params(eg: dbcb91e7-2bc9-515), or set.options["portfolio"]. You can get a list of portfolios with fetchPortfolios()portfolio_uuid	positions)rX  r  r  r  !v3PrivateGetBrokerageCfmPositionsrY  r!   r.   /v3PrivateGetBrokerageIntxPositionsPortfolioUuidr[  r\  parse_positions)	r:  r  rH  r  rj  rJ  rs  r_  r  s	            r<  fetch_positionszcoinbase.fetch_positionsT  s    	%%g.[[,F99:JFTZ[f8==fEHI $ = =fFVXc dIv '  3Z  )Z  [  [ )G KKDKKX_agLhiHNN8["=	##Iw77r=  c                    | j                          | j                  |      }d}|d   rR| j                  |d      }|t        | j                  dz         d|i}| j                  | j                  ||            }n[d}| j                  |dd      \  }}|t        | j                  dz         |d   |d	}| j                  | j                  ||            }| j                  |d
i       }	| j                  |	|      S )aB  
        fetch data on a single open contract trade position

        https://docs.cloud.coinbase.com/advanced-trade/reference/retailbrokerageapi_getintxposition
        https://docs.cloud.coinbase.com/advanced-trade/reference/retailbrokerageapi_getfcmposition

        :param str symbol: unified market symbol of the market the position is held in, default is None
        :param dict [params]: extra parameters specific to the exchange API endpoint
        :param str [params.product_id]: *futures only* the product id of the position to fetch, required for futures markets only
        :param str [params.portfolio]: *perpetual/swaps only* the portfolio UUID to fetch the position for, required for perpetual/swaps markets only
        :returns dict: a `position structure <https://docs.ccxt.com/#/?id=position-structure>`
        Nr@   r  z2 fetchPosition() requires a "product_id" in paramsr   rs  z fetchPosition() requires a "portfolio" value in params(eg: dbcb91e7-2bc9-515), or set.options["portfolio"]. You can get a list of portfolios with fetchPortfolios()r.   )r  r  position)rX  r  rC  r!   r.   *v3PrivateGetBrokerageCfmPositionsProductIdr[  rY  5v3PrivateGetBrokerageIntxPositionsPortfolioUuidSymbolrE  parse_position)
r:  r  rH  r  rJ  	productIdfutureRequestrs  r_  r  s
             r<  fetch_positionzcoinbase.fetch_positionv  s"    	V$(((>I '2f(fggi#M FFt{{S`bhGijHI $ = =fFVXc dIv '  3Y  )Y  Z  Z ,"+G QQRVR]R]^egmRnoH>>(J;""8V44r=  r  c                 L   | j                  |dd      }| j                  ||      }| j                  |d      }d }|	|dk(  rdnd}| j                  |di       }| j                  |d      }|d	k(  rd
nd}| j                  |di       }	| j                  |di       }
| j                  |
d      }| j                  |di       }| j                  |di       }| j	                  i d|d| j                  |d      d| j                  ||      d| j                  |d      d|d|d| j                  |d      d| j                  |	d      dd dd d| j                  |d      d|d   dd dd d |d!d d"d d d d d | j                  |d#      d d | j                  |d$      d d d d%      S )&Nr  rW  r   MARGIN_TYPE_CROSSr!  r  position_notionalposition_sidePOSITION_SIDE_LONGlongshortunrealized_pnlliquidation_pricer  r  portfolio_summaryrm  r.   r  notionalr  liquidationPrice
entryPriceunrealizedPnlrealizedPnlr   	contractsnet_sizer!  	markPrice	lastPricer  r  r  
collateralr   )r  lastUpdateTimestampmaintenanceMarginmaintenanceMarginPercentager-  initialMargininitialMarginPercentager   marginRatior  r  )rC  r  rE  r  safe_positionrK  )r:  r  r  r  	rawMarginr  notionalObjectpositionSider  unrealizedPNLObjectliquidationPriceObjectr%  
vwapObjectsummaryObjects                 r<  r  zcoinbase.parse_position  sc   t ##Hh;!!(F3$$X}=	
 %.2E%EJJ2ErJ''/B&*>>vW"nnX7GL!%:Mr!R++,BGL^^Hfb9
x1DbI!! #
H#
$""8\:#
 d&&x8#
 ((A	#

 *#
  0#
 $**:w?#
 T--.A7K#
 4#
 $#
 ))(J?#
 F>2#
 #
 #
 D#
  d!#
" ##
$ #'!%+/**=,G!'+((:>!#9#
  	r=  c                    | j                          d}| j                  dd|      \  }}|dk(  }|rdnd}d|i}| j                  | j                  ||            }| j	                  |di       }| j                  |d      }| j                  |d	      }	i }
t        d
t        | j                              D ]=  }| j                  |   }| j                  |      }|r|d   s	|r-|d   r3||||	dd|
|<   ? |
S )a  

        https://docs.cdp.coinbase.com/advanced-trade/reference/retailbrokerageapi_gettransactionsummary/

        fetch the trading fees for multiple markets
        :param dict [params]: extra parameters specific to the exchange API endpoint
        :param str [params.type]: 'spot' or 'swap'
        :returns dict: a dictionary of `fee structures <https://docs.ccxt.com/#/?id=fee-structure>` indexed by market symbols
        Nr   r=   r  r3  r2  r6  rV  rW  r   T)rm  r  r   r   r   )
rX  r  r=  r[  rE  r  ro  r]  r  r  )r:  rH  rj  isSpotproductTyper_  rJ  r@  	taker_fee
marker_feerq  rr  r  r  s                 r<  fetch_trading_feeszcoinbase.fetch_trading_fees"  s    	99:LdTZ[f&. &fHK
 ??GU[@\]0 ~~h
B7$$T+;<	%%d,<=
q#dll+, 
	A\\!_F[[(F6&>6&.$$&'"&"v	
	 r=  portfolioUuidc                     | j                          d|i}| j                  | j                  ||            }| j                  |      }|S )a  
        Fetch details for a specific portfolio by UUID

        https://docs.cloud.coinbase.com/advanced-trade/reference/retailbrokerageapi_getportfolios

        :param str portfolioUuid: The unique identifier of the portfolio to fetch
        :param Dict [params]: Extra parameters specific to the exchange API endpoint
        :returns any[]: An account structure <https://docs.ccxt.com/#/?id=account-structure>
        r  )rX  ,v3PrivateGetBrokeragePortfoliosPortfolioUuidr[  parse_portfolio_details)r:  rB  rH  r_  rJ  rq  s         r<  fetch_portfolio_detailsz coinbase.fetch_portfolio_details]  sP     	m
 DDT[[QXZ`Eab--h7r=  portfolioDatac                    |d   }| j                  |di       }| j                  |dd      }| j                  |dd      }| j                  |dg       }g }t        dt	        |            D ]w  }||   }	| j                  |	d	d      }
| j                  |	d
d      }| j                  |      }| j                  |	dd      }| j                  |      }||z
  }| j                  |	di       }| j                  |dd      }| j                  |	di       }| j                  |dd      }i d|
d|ddd|d|d| j                  |	dd      d|d| j                  | j                  |	dd            d
| j                  | j                  |	d
d            d| j                  | j                  |	dd            d| j                  | j                  |	dd            d| j                  | j                  |	dd            d| j                  | j                  |	dd            d| j                  |      d| j                  |dd      d| j                  |	dd      d| j                  |      | j                  |dd      | j                  |	dd      | j                  | j                  |	d d            | j                  |	d!d      | j                  |	d"d      d#}|j                  |       z |S )$N	breakdownrs  r/   Unknownri  rW  spot_positionsr   assetavailable_to_trade_fiatr   total_balance_fiat
cost_basisr  average_entry_pricerw  r  hold_amountwallet_namer  account_uuidtotal_balance_cryptoavailable_to_trade_cryptoavailable_to_transfer_fiatavailable_to_transfer_crypto
allocationcost_basis_currencyr  is_cashF
asset_uuidr!  asset_coloraccount_type)average_entry_price_currencyr[  r!  r\  r]  )rE  rC  r\  ro  r]  r9  ry  rp  )r:  rG  rI  portfolioInfoportfolioNamerB  spotPositionsparsedPositionsrr  r  currencyCodeavailableBalanceStravailableBalancetotalBalanceFiatStrtotalBalanceFiat
holdAmountcostBasisDictcostBasisStraverageEntryPriceDictaverageEntryPriceStrpositionDatas                        r<  rE  z coinbase.parse_portfolio_detailso  s   !+.	y+rB((	J((Cy2BBGq#m,- $	1A*1-H++HgyIL"&"2"28=VX["\#001DE"&"2"28=QSV"W#001DE),<<J NN8\2FM++M7CHL$(NN8=RTV$W!#'#3#34I7TW#X "L"#%5" " }	"
 m"  0 0>2 N" %&6" '(9(9$:J:J8Ukmp:q(r" *4+<+<T=M=MhXqsv=w+x" ,T->->t?O?OPXZuwz?{-|" -d.?.?@P@PQY[wy|@}.~" /0A0A$BRBRS[]xz}B~0" d//0@0@<Y\0]^" d//=" &t'7'7zSX'Y"  4>>(IuE!"" &t'8'89M'N#"$ 150@0@AVXbdi0j"..xrJ"&"3"3D4D4DXO_ad4e"f#//-L $ 0 0>2 N-"L0 ""<0I$	1J r=  r  r?  urlc           
      J   d }|3|dz   |j                  dd      z   }|j                  d      }|dkD  r|d| }| j                  d      }dgd||d	z   | j                  |d
}|||d<   | j	                  || j                  | j                        dd| j                  |dd      }|S )Nrx  zhttps://rW  ?r      retail_rest_api_proxyzcoinbase-cloudx   )audissnbfexpsubiaturisha256FES256)kidnoncealg)replacefindrandom_bytesr   jwtencoder   )	r:  r  r?  rn  rz  quesPosr~  r_  tokens	            r<  create_auth_tokenzcoinbase.create_auth_token  s    ?3,Z!<<ChhsmG {!Gn!!"%+,#S=;;
 ? GEN$++dkk":HeUYU`U`kp  zA  NB  Cr=  c                 B    | j                         | j                  d   z
  S )Nr	  )r{  r3  )r:  s    r<  r~  zcoinbase.nonce  s       "T\\2B%CCCr=  GETc                    |d   }|d   dk(  }|dk(  }	|	rdnd}
d|
z   dz   | j                  ||      z   }| j                  || j                  |            }|}|dk(  r|r|d	| j                  |      z   z  }| j                  d
   d   |z   }|r| j                  | j                  d      }d }||}n| j                  r"| j                  d      sd| j                  z   }nu| j                          | j                         }d}|dk7  r|r/| j                  |      }|}n|	s|r|d	| j                  |      z   z  }| j                  j                  d      dk\  xs | j                  j                  d      }|rL| j                  j                  d      rt!        | j"                  dz         | j%                  |||      }d|z   }n| j'                         }| j)                  |dz        }t+        |      }||z   |z   |z   }| j-                  | j/                  |      | j/                  | j                        t0        j2                        }| j                  ||dd}||dd}|dk7  r|r| j                  |      }||||dS )Nr   r   r   r   zapi/v3r7   r  r  rp  r   r   AuthorizationFzBearer rW  zorganizations/z
-----BEGINzV apiKey should contain the name(eg: organizations/3b910e93....) and not the public keyry  zapplication/json)zCB-ACCESS-KEYzCB-ACCESS-SIGNzCB-ACCESS-TIMESTAMPContent-Type)r  r  )rn  r?  bodyr:   )implode_paramsrD  extract_paramsurlencode_with_array_repeatr   rC  r:   r  r<  r  json	urlencoder   r  r   
startswithr!   r.   r  r~  r  r  hmacr  hashlibr{  )r:  r  r   r?  rH  r:   r  r6   signedr  pathPartfullPathr  	savedPathrn  authorizationauthorizationStringr  payloadisCloudAPiKeyr  r~  r  timestampStringauth	signatures                             r<  signzcoinbase.sign  s   a&Q9$$ $84>C'$*=*=dF*KK		&$"5"5d";<	U?C$"B"B5"IIIiiv&1 ,,T\\?KM"&(&3#D$C$CE$J&/$**&<#//1,,.U?#yy/"& #sT^^E-B'BBG
 "&!1!12B!Cq!H sdkkNdNdeqNr {{--l;/  ;S  1S  T  T& !227FCHE*3e*;' JJLE $ 1 1%$, ?I&))nO*V3i?'ID $		$++d*;T[[=UW^WeWe fI)-*3/>(:	G #.%8$6 U?#yy/fdwOOr=  reasonr:   r  c
                    |y | j                   dz   |z   }
| j                  |d      }|^| j                  |dd      }| j                  | j                  d   ||
       | j                  | j                  d   ||
       t        |
      | j                  |d      }|^| j                  |dd      }| j                  | j                  d   ||
       | j                  | j                  d   ||
       t        |
      | j                  |d      }|t        |t              rt        |      }|d	kD  rw| j                  |d	   d
      }| j                  |d	   d      }|K| j                  | j                  d   ||
       | j                  | j                  d   ||
       t        |
      | j                  d   }d|vr,|s*t        | j                   dz   | j                  |      z         y )Nrx  r)  error_descriptionr   r   r(  preview_failure_reasonerrorsr   r.   r*  r  r@  z$ failed due to a malformed response )r.   rC  r{  r5  r   r6  r   rE  r\  
isinstancer*  r]  r3  r  )r:  rl  r  rn  r?  r:   r  rJ  requestHeadersrequestBodyfeedback	errorCoder@  r>  errorMessageInnerr  	numErrorsadvancedTrades                     r<  handle_errorszcoinbase.handle_errors
  s   77S=4'D $$Xw7	 --h8KWUL001I9V^_001I<Yab))x1AB$ $ 2 2=BZ\t u001IK\^fg001IK\^fg))(3&$'K	q= $ 0 0D AI#'#3#3F1Iy#IL ,<<T__W=UW`bjk<<T__W=UWcemn+H55Z0("]*P PSWS\S\]eSf fggr=  )N)NN)w__name__
__module____qualname__r   r7  r   rK  r   r   rP  rN  rM  rt  r  r  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   r   r  r  r  r   r  r  r  r  r  r   r  r   r  r  r  r  r  r  r  floatr  r   r   r   r  r   r7  rO  rM  rN  ru  rs  r~  r  r  r  r  r  r  r*  r  r  r  r  r   r  r  r   r  r  rV   r  r  r  r  r  r   r  r  r  r  r
  r   r  r  r  r   rA  rF  rE  r  r~  r  intr  __classcell__)r;  s   @r<  r+   r+      s	   @# @D !# "Hs "HH %' .4= .  (* @1d7m @1D (* 05d7m 05d ') T'] ,D
L 8: F
3 F
n F
P ,0dQU^` DS D D3 D( +/TPT]_ CC Cs C# C( BFTXgktv M3 Mc Mad M -1tRV_a {c { {C {fjkvfw {( *.Dt\^ x3 xc x xcghsct x( 6:[_hj Ws W# WUX Wost  pA W :s :P
T P
X P
Q\ P
d{ {v { {z $& -$v, -& ') CT&\ CJ ') MT&\ M^^O ^@A AF 24 +CZ ') gZ gR 04B 6W 67 6" 37r G Gg GB 37r >G >Gg >G@ 02 43 4f 4& 35 5c 58 35 $c $Lu4 u u6 un 57 ,)\ $& f;( f;P (,$TZ\ & &C &s &aefqar &P73ot ox o; ob	 ,.  48 	S 	 FJX\eg !s !RU !  RT N N5 N$ gksu Z.3 Z.i Z.y Z.RW Z.`c Z.xA Av A AF	: 	:	3S 	3Hs H 37r -s -C - 04B #1 #1J `drv  @B )2S )2# )2Y )2i )2Y\ )2lo )2V 26b ;/c ;/3 ;/z *.Ds[] R?3 R?c R? R?bfglbm R?h <@daenp D?S D? D?[^ D?L /3TXac Q Q3 Qc Qhlmrhs Q* 154VZce S# SS SPS Sjnotju S* 37TX\eg VC Vs VRU V 26DW[df BK# BKc BKQT BKkoptku BKH
 
4 
, 6:UW 4?3 4?s 4?# 4?\`af\g 4?l -1tRV_a ??c ?? ??C ??B :>b 1_s 1_3 1_Y 1_f 26b '4w '4R DHPR X6S X6% X6# X6Wb X6t DF H;s H;$~J^ H;T<
h <
R` <
| AC D,C D, D,C D,L 26b @, @,3 @,D /1 5B 79 !4# !4F 46 
 MQY[ +C + +c +`j +2 W[ce +s +c +3 +PS +jt +. 8<B +c + +: +8
4 
x 
\d 
pz 
* =A 'S '	 'PU ': 26b  8w  8T(^  8D 24 #5S #5JEt EV EN )+ 9{ 9v BD S S	 $,T ,\ c s 0D  b$T PPd?# ?s ? ?c ?TX ?`c ?r=  r+   )0ccxt.base.exchanger   ccxt.abstract.coinbaser   r  ccxt.base.typesr   r   r   r   r	   r
   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   typingr   ccxt.base.errorsr   r   r    r!   r"   r#   r$   r%   r&   r'   ccxt.base.decimal_to_precisionr(   ccxt.base.preciser)   r+    r=  r<  <module>r     ss    ( .  G  G  G  G  G  G  G  * 0 - . ' ) * ) . ) 4 %pLx pLr=  