
    ":h)w                         d dl 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 d dlmZ d dlmZ d dlmZ  G d dej(                  j*                        Zy)	    N)ArrayCacheBySymbolById)	AnyIntOrder	OrderBookStrStringsTickerTickersTrade)List)ExchangeError)ArgumentsRequiredc            
           e Zd Zdef fdZdi fdedefdZdi fdededefdZ	ded	e
e   fd
Zi fdedefdZdi fdedefdZd Zd dZddi fdededede
e   fdZddi fde
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i fdededefdZdi fde
e   dedefdZd Zd Zd dZd Zd Z d Z!d Z"d Z#d Z$ xZ%S )!coinbasereturnc                     | j                  t        t        |          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iidddddddd      S )NwsTcancelAllOrdersWsFcancelOrdersWscancelOrderWscreateOrderWseditOrderWsfetchBalanceWsfetchOpenOrdersWsfetchOrderWsfetchTradesWswatchBalancewatchMyTrades
watchOHLCVwatchOrderBookwatchOrderBookForSymbolswatchOrderswatchTicker)watchTickerswatchTradeswatchTradesForSymbolsapiz$wss://advanced-trade-ws.coinbase.com  bidsasks)bidoffer)tradesLimitordersLimitmyTradesLimitsides)hasurlsoptions)deep_extendsuperr   describe)self	__class__s    K/var/www/html/turnos/venv/lib/python3.12/site-packages/ccxt/pro/coinbase.pyr7   zcoinbase.describe   s5   h > @d#U !%  	
   u !% $U       e !$ +D  t!" t#$ !%#)-). @  $#!%!#	9%C
 % %	    Nname	isPrivatec                   K   | j                          d{    d}|}g }t        |t              r<| j                  |      }| j	                  |      }	|	}|dz   dj                  |      z   }n!|| j                  |      }|dz   |z   }|d   g}| j                  d   d   }
d||d}|r"| j                  || j                  ||            }| j                  |
|||       d{   S 7 7 w)	a  
 @ignore
        subscribes to a websocket channel

        https://docs.cloud.coinbase.com/advanced-trade-api/docs/ws-overview#subscribe

        :param str name: the name of the channel
        :param boolean isPrivate: whether the channel is private or not
        :param str [symbol]: unified market symbol
        :param dict [params]: extra parameters specific to the exchange API endpoint
        :returns dict: subscription to a websocket channel
        N::,idr(   r   	subscribetypeproduct_idschannel)load_markets
isinstancelistmarket_symbols
market_idsjoinmarketr3   extendcreate_ws_authwatch)r8   r<   r=   symbolparamsrM   messageHash
productIdssymbols	marketIdsurlrB   s               r:   rB   zcoinbase.subscribe9   s     !!!
fd#))&1G0I"J%,sxx/??K[[(F+.K ,Jiit$%
	 It/B/B4/TUIZZ[)[III1 	"0 Js"   C*C&C
C*!C("C*(C*rU   c                   K   | j                          d{    g }g }| j                  |dd      }t        dt        |            D ]E  }||   }| j	                  |      }	|	d   }
|j                  |
       |j                  |dz   |z          G | j                  d   d   }d||d	}|r"| j                  || j                  ||            }| j                  ||||       d{   S 7 7 w)
a  
 @ignore
        subscribes to a websocket channel

        https://docs.cloud.coinbase.com/advanced-trade-api/docs/ws-overview#subscribe

        :param str name: the name of the channel
        :param boolean isPrivate: whether the channel is private or not
        :param str[] [symbols]: unified market symbol
        :param dict [params]: extra parameters specific to the exchange API endpoint
        :returns dict: subscription to a websocket channel
        NFr   rA   r?   r(   r   rB   rC   )
rG   rJ   rangelenrM   appendr3   rN   rO   watch_multiple)r8   r<   r=   rU   rR   rT   messageHashesirQ   rM   marketIdrW   rB   s                r:   subscribe_multiplezcoinbase.subscribe_multiple`   s     !!!
%%gtU;q#g,' 	7AQZF[[(Fd|Hh'  v!56	7 iit$%
	
 It/B/B4/TUI((mYVVV% 	"$ Ws"   C+C'CC+"C)#C+)C+rT   c                 |   i }| j                  | j                               }| j                          | j                  j	                  d      dk\  xs | j
                  j                  d      }||z   dj                  |      z   }|sb| j                  |d<   ||d<   | j                  | j                  |      | j                  | j
                        t        j                        |d<   |S | j                  j                  d      rt        | j                  dz         | j                  | j                  d	      }| j!                  | j                  d
d      }| j                         }	||dz   |	k  r/| j#                  |	      }
|
| j                  d	<   |	| j                  d
<   | j                  | j                  d	      |d<   |S )Nzorganizations/r   z
-----BEGINr@   api_key	timestamp	signaturezV apiKey should contain the name(eg: organizations/3b910e93....) and not the public keywsTokenwsTokenTimestampx   jwt)number_to_stringsecondscheck_required_credentialsapiKeyfindsecret
startswithrL   hmacencodehashlibsha256r   rA   safe_stringr4   safe_integercreate_auth_token)r8   r<   rT   rB   rc   isCloudAPiKeyauthcurrentTokentokenTimestamprj   tokens              r:   rO   zcoinbase.create_ws_auth   s   	))$,,.9	'')))*:;q@kdkkF\F\]iFj4#((:"66#';;Ii %.Ik"%)YYt{{4/@$++dkkBZ\c\j\j%kIk"  {{%%l3'  3K  )K  L  L++DLL)DL!..t||=OQRSNllnG#~';g'E..w7*/Y'3:/0#//iHIer;   rQ   c                 J   K   d}| j                  |d||       d{   S 7 w)a  
        watches 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-api/docs/ws-channels#ticker-channel

        :param str [symbol]: unified symbol of the market to fetch the ticker for
        :param dict [params]: extra parameters specific to the exchange API endpoint
        :returns dict: a `ticker structure <https://docs.ccxt.com/#/?id=ticker-structure>`
        tickerFN)rB   )r8   rQ   rR   r<   s       r:   watch_tickerzcoinbase.watch_ticker   s(      ^^D%@@@@s   #!#c                    K   || j                   }d}| j                  |d||       d{   }| j                  ri }|d   }|||<   |S | j                  S 7 *w)a  
        watches 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-api/docs/ws-channels#ticker-batch-channel

        :param str[] [symbols]: unified symbol of the market to fetch the ticker for
        :param dict [params]: extra parameters specific to the exchange API endpoint
        :returns dict: a `ticker structure <https://docs.ccxt.com/#/?id=ticker-structure>`
        Nticker_batchFrQ   )rU   r`   
newUpdatestickers)r8   rU   rR   r<   r}   r   rQ   s          r:   watch_tickerszcoinbase.watch_tickers   sh      ?llG..tUGVLL??GH%F$GFON|| Ms   (AA+Ac                 >   | j                  |d      }| j                  |dg       }| j                  |d      }| j                  |      }g }t        dt	        |            D ]  }||   }	| j                  |	dg       }
t        dt	        |
            D ]  }|
|   }| j                  |d      }|| j                  |      }||d<   ||d<   |d   }|| j                  |<   |j                  |       |d	z   |z   }|j                  ||       | j                  |||         y )
NrF   eventsrc   r   r   
product_iddatetimerQ   r?   )
rt   	safe_list	parse8601rY   rZ   parse_ws_tickerr   r[   resolvetry_resolve_usdc)r8   clientmessagerF   r   r   rc   
newTickersr^   
tickersObjr   jr}   
wsMarketIdresultrQ   rS   s                    r:   handle_tickerszcoinbase.handle_tickers   s=   t ""7I626##G[9NN8,	
q#f+& 	CAJnnZB?G1c'l+ C !--flC
%--f5&/{#%-z")'-V$!!&)%nv5v{3%%fk6BC	Cr;   c           	      "   | j                  |d      }d }| j                  |d      }| j                  i d|d| j                  ||d      d|d| j	                  |      d| j                  |d	      d
| j                  |d      d| j                  |d      d| j                  |d      d| j                  |d      d| j                  |d      dd dd d|d|dd dd d| j                  |d      d | j                  |d      d d      S )Nr   priceinforQ   -rc   r   high	high_24_hlowlow_24_hr,   best_bid	bidVolumebest_bid_quantityaskbest_ask	askVolumebest_ask_quantityvwapopencloselastpreviousClosechange
percentageprice_percent_chg_24_hvolume_24_h)average
baseVolumequoteVolume)rt   safe_numbersafe_tickersafe_symboliso8601)r8   r}   rM   r_   rc   r   s         r:   r   zcoinbase.parse_ws_ticker,  s   & ##FL9	0 !
F!
d&&x=!
 !
 Y/	!

 D$$V[9!
 4##FJ7!
 4##FJ7!
 ))&2EF!
 4##FJ7!
 ))&2EF!
 D!
 D!
 T!
 D!
 T!
  d!!
" $**63KL#!
$ **6=A)!
  	r;   sincelimitc                   K   | j                          d{    | j                  |      }d}| j                  |d||       d{   }| j                  r|j	                  ||      }| j                  |||dd      S 7 f7 9w)a@  
        get the list of most recent trades for a particular symbol

        https://docs.cloud.coinbase.com/advanced-trade-api/docs/ws-channels#market-trades-channel

        :param str symbol: unified symbol of the market to fetch trades for
        :param int [since]: timestamp in ms of the earliest trade to fetch
        :param int [limit]: the maximum amount of trades to fetch
        :param dict [params]: extra parameters specific to the exchange API endpoint
        :returns dict[]: a list of `trade structures <https://docs.ccxt.com/#/?id=public-trades>`
        Nmarket_tradesFrc   T)rG   rQ   rB   r   getLimitfilter_by_since_limit)r8   rQ   r   r   rR   r<   tradess          r:   watch_tradeszcoinbase.watch_tradesY  s      !!!V$~~dE66BB??OOFE2E))&%TRR 	" Cs!   BA=.BA?8B?Bc                 ,  K   | j                          d{    d}| j                  |d||       d{   }| j                  r6| j                  |d      }| j	                  |d      }|j                  ||      }| j                  |||dd      S 7 y7 ]w)aC  
        get the list of most recent trades for a particular symbol

        https://docs.cloud.coinbase.com/advanced-trade-api/docs/ws-channels#market-trades-channel

        :param str[] symbols: unified symbol of the market to fetch trades for
        :param int [since]: timestamp in ms of the earliest trade to fetch
        :param int [limit]: the maximum amount of trades to fetch
        :param dict [params]: extra parameters specific to the exchange API endpoint
        :returns dict[]: a list of `trade structures <https://docs.ccxt.com/#/?id=public-trades>`
        Nr   Fr   rQ   rc   T)rG   r`   r   	safe_dictrt   r   r   )	r8   rU   r   r   rR   r<   r   firsttradeSymbols	            r:   watch_trades_for_symbolsz!coinbase.watch_trades_for_symbolsm  s      !!!..tUGVLL??NN61-E**5(;KOOK7E))&%TRR 	"Ls    BBBBABBc                    K   | j                          d{    d}| j                  |d||       d{   }| j                  r|j                  ||      }| j	                  |||dd      S 7 U7 9w)aI  
        watches information on multiple orders made by the user

        https://docs.cloud.coinbase.com/advanced-trade-api/docs/ws-channels#user-channel

        :param str [symbol]: unified market symbol of the market orders were made in
        :param int [since]: the earliest time in ms to fetch orders for
        :param int [limit]: the maximum number of order structures to retrieve
        :param dict [params]: extra parameters specific to the exchange API endpoint
        :returns dict[]: a list of `order structures <https://docs.ccxt.com/#/?id=order-structure>`
        NuserTrc   )rG   rB   r   r   r   )r8   rQ   r   r   rR   r<   orderss          r:   watch_orderszcoinbase.watch_orders  so      !!!~~dD&&AA??OOFE2E))&%TRR 	"As   A0A,A0A.8A0.A0c                    K   | j                          d{    d}| j                  |      }|d   }| j                  |d||       d{   }|j                         S 7 H7 w)aP  
        watches information on open orders with bid(buy) and ask(sell) prices, volumes and other data

        https://docs.cloud.coinbase.com/advanced-trade-api/docs/ws-channels#level2-channel

        :param str symbol: unified symbol of the market to fetch the order book for
        :param int [limit]: the maximum amount of order book entries to return
        :param dict [params]: extra parameters specific to the exchange API endpoint
        :returns dict: A dictionary of `order book structures <https://docs.ccxt.com/#/?id=order-book-structure>` indexed by market symbols
        Nlevel2rQ   F)rG   rM   rB   r   )r8   rQ   r   rR   r<   rM   	orderbooks          r:   watch_order_bookzcoinbase.watch_order_book  sg      !!!V$!..uffEE	   	" Fs!   A#A3A#
A!A#!A#c                    K   | j                          d{    d}| j                  |d||       d{   }|j                         S 7 27 w)a3  
        watches information on open orders with bid(buy) and ask(sell) prices, volumes and other data

        https://docs.cloud.coinbase.com/advanced-trade-api/docs/ws-channels#level2-channel

        :param str[] symbols: unified array of symbols
        :param int [limit]: the maximum amount of order book entries to return
        :param dict [params]: extra parameters specific to the exchange API endpoint
        :returns dict: A dictionary of `order book structures <https://docs.ccxt.com/#/?id=order-book-structure>` indexed by market symbols
        Nr   F)rG   r`   r   )r8   rU   r   rR   r<   r   s         r:   watch_order_book_for_symbolsz%coinbase.watch_order_book_for_symbols  sN      !!!11$wOO	   	"Os   AA	AAAAc                    | j                  |d      }| j                  |d      }| j                  |d      }| j                  |d      }| j                  |d      }| j	                  |      }d|z   }	| j                  | j
                  |      }
|
7| j                  | j                  dd      }t        |      }
|
| j
                  |<   t        dt        |            D ]X  }||   }| j                  |d      }t        dt        |            D ]'  }||   }|
j                  | j                  |             ) Z |j                  |
|	       | j                  ||	|
       y )Nr   r   r   r   zmarket_trades::r.   r)   )r   
safe_valuer   rt   r   r   ru   r4   r   rY   rZ   r[   parse_trader   r   )r8   r   r   r   eventr   trader_   rQ   rS   tradesArrayr.   r^   currentEventcurrentTradesr   items                    r:   handle_tradezcoinbase.handle_trade  sM   0 2*x0vq)##E<8!!(+'&0oodkk6:++DLL-NK0=K"-DKKq#f+& 	;A!!9L NN<BM1c-01 ;$Q'""4#3#3D#9:;	; 	{K0fk;?r;   c                    | j                  |d      }g }| j                  -| j                  | j                  dd      }t	        |      | _        t        dt        |            D ]  }||   }| j                  |d      }t        dt        |            D ]\  }	||	   }
| j                  |
      }| j                  }| j                  |
d      }||vr|j                  |       |j                  |       ^  t        dt        |            D ]V  }||   }| j                  |      }d|z   }|j                  | j                  |       | j                  ||| j                         X |j                  | j                  d       y )	Nr   r/   r)   r   r   r   zuser::r   )r   r   ru   r4   r   rY   rZ   parse_ws_orderrt   r[   r   r   r   )r8   r   r   r   rV   r   r^   r   responseOrdersr   responseOrderparsedcachedOrdersr_   rQ   rS   s                   r:   handle_orderzcoinbase.handle_order  sk   : 2	;;%%dllM4HE07DKq#f+& 
	,A1IE!^^E8<N1c.12 , .q 1,,];#{{++M<H I-$$X.##F+,
	, q#i.) 	DA |H%%h/F"V+KNN4;;4!!&+t{{C	D 	t{{F+r;   c                    | j                  |d      }| j                  |d      }| j                  |d      }| j                  |d      }| j                  ||      }| j                  i d|d| j                  |d      d|d|d	| j                  |      d
|dd d| j                  |d      dd dd d| j                  |d      dd dd dd dd dd d| j                  |d      | j                  |d      | j                  |d      | j	                  |d      | j                  |d      | j                  |d      dd d      S )Norder_idclient_order_idr   timer   rQ   rA   clientOrderIdrc   r   lastTradeTimestamprD   
order_typetimeInForcepostOnlysider   	stopPricetriggerPriceamountcostr   	avg_pricecumulative_quantityleaves_quantitystatus
total_feesquote)r   currency)filled	remainingr   feer   )rt   safe_market
safe_orderr   safe_string_lower)r8   orderrM   rA   r   r_   r   s          r:   r   zcoinbase.parse_ws_order  s     eZ0((0AB##E<8##E62!!(F3  
E 
d&&vx8 
 " 
 ]	 

 1 
  
 !$ 
 D$$UL9 
 4 
  
 D$$UF3 
 T 
  
 D 
 d 
  D! 
" t''{;# 
$ &&u.CD))%1BC,,UH=**5,? ,,VW= 3 
  	r;   c                    t        dt        |            D ]s  }||   }| j                  |d      }| j                  | j                  d   |      }| j	                  |d      }| j	                  |d      }||   }	|	j                  ||       u y )Nr   r   r1   price_levelnew_quantity)rY   rZ   rt   r4   r   store)
r8   r   updatesr^   r   sideIdr   r   r   orderbookSides
             r:   handle_order_book_helperz!coinbase.handle_order_book_helperJ  s    q#g,' 	/AAJE%%eV4F##DLL$96BD$$UM:E%%e^<F%dOMv.	/r;   c                    | j                  |d      }| j                  |d      }t        dt        |            D ]/  }||   }| j                  |dg       }| j                  |d      }| j	                  |      }	|	d   }
d|
z   }| j                  |j                  |i       }| j                  |d      }| j                  |d	      }|d
k(  r| j                  i |      | j                  |
<   |
| j                  vr| j                  |
   | j                  |
   }| j                  ||       | j                  |      |d<   ||d<   |
|d<   |j                  ||       | j                  |||       2 y )Nr   rc   r   r   r   rQ   zlevel2::r   rD   snapshotr   )r   rt   rY   rZ   r   r   subscriptionsru   
order_book
orderbooksr   r   r   r   )r8   r   r   r   r   r^   r   r   r_   rM   rQ   rS   subscriptionr   rD   r   s                   r:   handle_order_bookzcoinbase.handle_order_bookT  sr   : 2##G[9q#f+& 	BA1IEnnUIr:G''|<H%%h/FH%F$v-K??6+?+?bQL%%lG<E##E62Dz!*.//"e*D'doo-4??63J3R/I)))W=%)^^H%=Ik"$,Ij!"(IhNN9k2!!&+yA-	Br;   c                 t    |j                  d      s|j                  d      r|j                  ||dz          y y )Nz/USDz-USDC)endswithr   )r8   r   rS   r   s       r:   r   zcoinbase.try_resolve_usdc  s6    ';+?+?+GNN6;#45 ,Hr;   c                     |S N r8   r   r   s      r:   handle_subscription_statusz#coinbase.handle_subscription_status  s	     r;   c                     |S r  r  r  s      r:   handle_heartbeatszcoinbase.handle_heartbeats  s	    " r;   c                 l   | j                  |d      }| j                  | j                  | j                  | j                  | j                  | j
                  | j                  d}| j                  |d      }|dk(  r| j                  |d      }t        |      | j                  ||      }|r
 |||       y y )NrF   )r  r}   r   r   r   l2_data
heartbeatsrD   errorr   )	rt   r  r   r   r   r  r  r   r   )r8   r   r   rF   methodsrD   errorMessagemethods           r:   handle_messagezcoinbase.handle_message  s    ""7I6!<<)) //!..%%--00
 07?++GY?L--'267# r;   r  )&__name__
__module____qualname__r   r7   strboolrB   r	   r`   r   rO   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  __classcell__)r9   s   @r:   r   r      s   &# &P BFb %JC %JD %JN W[ce WS WT WG WB3 DI 0 68 A AF A 6:" 7  *oCb+Z <@d[] S SS S Sbfglbm S( OSaenp Sd3i S S[^ Suyz  vA S* 04$UYbd S SC Ss Simnsit S& @DB !S ! !S\ !$ SW_a !$s) !C !fo ! +@Z3,j/b/5Bn6&$r;   r   )ccxt.async_supportccxt ccxt.async_support.base.ws.cacher   rr   ccxt.base.typesr   r   r   r   r   r	   r
   r   r   typingr   ccxt.base.errorsr   r   async_supportr   r  r;   r:   <module>r&     s<     C  \ \ \  * .r
$t!!** r
$r;   