
    ":hk                         d dl Zd dlmZmZmZ d dl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  G d d	ej*                  j,                        Zy)
    N)
ArrayCacheArrayCacheBySymbolByIdArrayCacheByTimestamp)AnyIntOrder	OrderBookStrTickerTrade)Client)List)ExchangeError)AuthenticationErrorc            
           e Zd Zdef fdZi fdedefdZdefdZ	d"d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i fdededefdZdefdZd Zd Zddi fded
ededee   fdZ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efdZdefdZdefdZd"dZi fdZ defdZ!defdZ"defdZ#defdZ$defdZ%defd Z&defd!Z' xZ(S )#alpacareturnc                     | j                  t        t        |          ddddddddddd
ddddiddddid	i i dd
i iid      S )NTF)
wswatchBalancewatchMyTrades
watchOHLCVwatchOrderBookwatchOrderswatchTickerwatchTickerswatchTradeswatchPositionr   z/wss://stream.data.alpaca.markets/v1beta2/cryptozwss://api.alpaca.markets/stream)cryptotradingz%wss://paper-api.alpaca.markets/stream)apitestexact)hasurlsoptions	streaming
exceptions)deep_extendsuperr   describe)self	__class__s    I/var/www/html/turnos/venv/lib/python3.12/site-packages/ccxt/pro/alpaca.pyr+   zalpaca.describe   s    fd < > %!%""&## %#!& "S#D "S#J =$A
 $ $	    symbolc                 >  K   | j                   d   d   d   }| j                  |       d{    | j                          d{    | j                  |      }d|d   z   }d|d   gd	}| j	                  ||| j                  ||      |       d{   S 7 j7 T7 w)
a  
        watches a price ticker, a statistical calculation with the information calculated over the past 24 hours for a specific market

        https://docs.alpaca.markets/docs/real-time-crypto-pricing-data#quotes

        :param str symbol: unified symbol of the market to fetch the ticker for
        :param dict [params]: extra parameters specific to the exchange API endpoint
        :returns dict: a `ticker structure <https://docs.ccxt.com/#/?id=ticker-structure>`
        r!   r   r   Nticker:r0   	subscribeid)actionquotes)r%   authenticateload_marketsmarketwatchextend)r,   r0   paramsurlr9   messageHashrequests          r.   watch_tickerzalpaca.watch_ticker8   s      iit$X.$$$!!!V$&"22!d|n
 ZZ[$++gv2NP[\\\ 	%! ]s4   *BBBBABBBBBclientc                     | j                  |      }|d   }d|z   }|| j                  |<   |j                  | j                  |   |       y )Nr0   r2   )parse_tickertickersresolve)r,   rA   messagetickerr0   r>   s         r.   handle_tickerzalpaca.handle_tickerM   sM     ""7+!&(%Vt||F+[9r/   Nc                    | j                  |d      }| j                  |d      }| j                  i d| j                  ||      d| j                  |      d|dd dd d| j                  |d	      d
| j                  |d      d| j                  |d      d| j                  |d      dd dd dd dd dd dd dd dd d d |d|      S )NStr0   	timestampdatetimehighlowbidbp	bidVolumebsaskap	askVolumeasvwapopencloselastpreviousClosechange
percentageaverage)
baseVolumequoteVolumeinfo)safe_stringsafe_tickersafe_symbol	parse8601)r,   rG   r9   marketIdrM   s        r.   rC   zalpaca.parse_ticker_   sg    ##FC0##FC0 !
d&&x8!
1!
 !
 D	!

 4!
 4##FD1!
 ))&$7!
 4##FD1!
 ))&$7!
 D!
 D!
 T!
 D!
 T!
 d!
  $!!
" t#!
$ )!
* + 	r/   1msincelimitc                   K   | j                   d   d   d   }| j                  |       d{    | j                          d{    | j                  |      }|d   }d|d   gd}d	|z   }	| j	                  ||	| j                  ||      |	       d{   }
| j                  r|
j                  ||      }| j                  |
||d
d      S 7 7 7 ;w)a  
        watches historical candlestick data containing the open, high, low, and close price, and the volume of a market

        https://docs.alpaca.markets/docs/real-time-crypto-pricing-data#bars

        :param str symbol: unified symbol of the market to fetch OHLCV data for
        :param str timeframe: the length of time each candle represents
        :param int [since]: timestamp in ms of the earliest candle to fetch
        :param int [limit]: the maximum amount of candles to fetch
        :param dict [params]: extra parameters specific to the exchange API endpoint
        :returns int[][]: A list of candles ordered, open, high, low, close, volume
        r!   r   r   Nr0   r3   r4   )r5   barsohlcv:r   T	r%   r7   r8   r9   r:   r;   
newUpdatesgetLimitfilter_by_since_limit)r,   r0   	timeframeri   rj   r<   r=   r9   r?   r>   ohlcvs              r.   watch_ohlcvzalpaca.watch_ohlcv   s      iit$X.$$$!!!V$!!D\N
 'jjk4;;w3OQ\]]??NN651E))%q$GG 	%! ^4   *CCCCACC8CCCc                 f   | j                  |d      }| j                  |      }| j                  | j                  |      }|7| j	                  | j
                  dd      }t        |      }|| j                  |<   | j                  |      }|j                  |       d|z   }|j                  ||       y )NrJ   
OHLCVLimit  rm   )
rc   re   
safe_valueohlcvssafe_integerr&   r   parse_ohlcvappendrE   	r,   rA   rF   rg   r0   storedrj   parsedr>   s	            r.   handle_ohlcvzalpaca.handle_ohlcv   s     ##GS1!!(+f5>%%dllL$GE*51F"(DKK!!'*f'v{+r/   c                 b  K   | j                   d   d   d   }| j                  |       d{    | j                          d{    | j                  |      }|d   }d|z   }d|d   gd	}| j	                  ||| j                  ||      |       d{   }|j                         S 7 |7 f7 w)
aH  
        watches information on open orders with bid(buy) and ask(sell) prices, volumes and other data

        https://docs.alpaca.markets/docs/real-time-crypto-pricing-data#orderbooks

        :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
        r!   r   r   Nr0   
orderbook:r3   r4   )r5   
orderbooks)r%   r7   r8   r9   r:   r;   rj   )	r,   r0   rj   r<   r=   r9   r>   r?   	orderbooks	            r.   watch_order_bookzalpaca.watch_order_book   s      iit$X.$$$!!!V$!'&0!!$<.
 **S+t{{7F7SU`aa	   	%! bs4   *B/B)B/B+AB/B-B/+B/-B/c           	         | j                  |d      }| j                  |      }| j                  |d      }| j                  |      }| j                  |dd      }|| j                  vr| j                         | j                  |<   | j                  |   }|r)| j                  |||dddd      }	|j                  |	       nZ| j                  |dg       }
| j                  |dg       }| j                  |d	   |
       | j                  |d
   |       ||d<   ||d<   d|z   }|| j                  |<   |j                  ||       y )NrJ   rK   rFbapsasksbidsrL   rM   r   )rc   re   rf   	safe_boolr   
order_bookparse_order_bookreset	safe_listhandle_deltasrE   )r,   rA   rF   rg   r0   rM   rL   
isSnapshotr   snapshotr   r   r>   s                r.   handle_order_bookzalpaca.handle_order_book   s<   , ##GS1!!(+##GS1NN8,	^^GS%8
$//)&*oo&7DOOF#OOF+	,,WficSVX[\HOOH%>>'33D>>'33Dy0$7y0$7%.Ik"$,Ij!'&0"+y+.r/   c                 L    | j                  |dd      }|j                  |       y )Nr   r   )parse_bid_ask
storeArray)r,   booksidedeltabidAsks       r.   handle_deltazalpaca.handle_delta   s$    ##E34F#r/   c                 b    t        dt        |            D ]  }| j                  |||           y )Nr   )rangelenr   )r,   r   deltasis       r.   r   zalpaca.handle_deltas  s0    q#f+& 	3Ahq	2	3r/   c                   K   | j                   d   d   d   }| j                  |       d{    | j                          d{    | j                  |      }|d   }d|z   }d|d   gd	}| j	                  ||| j                  ||      |       d{   }	| j                  r|	j                  ||      }| j                  |	||d
d      S 7 7 7 ;w)a<  
        watches information on multiple trades made in a market

        https://docs.alpaca.markets/docs/real-time-crypto-pricing-data#trades

        :param str symbol: unified market symbol of the market trades were made in
        :param int [since]: the earliest time in ms to fetch orders for
        :param int [limit]: the maximum number of trade structures to retrieve
        :param dict [params]: extra parameters specific to the exchange API endpoint
        :returns dict[]: a list of `trade structures <https://docs.ccxt.com/#/?id=trade-structure>`
        r!   r   r   Nr0   trade:r3   r4   )r5   tradesrL   Trn   )
r,   r0   ri   rj   r<   r=   r9   r>   r?   r   s
             r.   watch_tradeszalpaca.watch_trades  s      iit$X.$$$!!!V$!'!d|n
 zz#{DKK4PR]^^??OOFE2E))&%TRR 	%! _ru   c                 f   | j                  |d      }| j                  |      }| j                  | j                  |      }|7| j	                  | j
                  dd      }t        |      }|| j                  |<   | j                  |      }|j                  |       d|z   }|j                  ||       y )NrJ   tradesLimitrx   r   )
rc   re   ry   r   r{   r&   r   parse_trader}   rE   r~   s	            r.   handle_tradeszalpaca.handle_trades"  s     ##GS1!!(+f5>%%dllM4HE&F"(DKK!!'*f#f,v{+r/   c                   K   | j                   d   d   d   }| j                  |       d{    d}| j                          d{    || j                  |      }|d|z   z  }ddd	gid
}| j	                  ||| j                  ||      |       d{   }| j                  r|j                  ||      }| j                  |||dd      S 7 7 7 ;w)a  
        watches information on multiple trades made by the user

        https://docs.alpaca.markets/docs/websocket-streaming#trade-updates

        :param str symbol: unified market symbol of the market trades were made in
        :param int [since]: the earliest time in ms to fetch trades for
        :param int [limit]: the maximum number of trade structures to retrieve
        :param dict [params]: extra parameters specific to the exchange API endpoint
        :param boolean [params.unifiedMargin]: use unified margin account
        :returns dict[]: a list of `trade structures <https://docs.ccxt.com/#/?id=trade-structure>`
        r!   r   r    NmyTrades:listenstreamstrade_updatesr5   datarL   T)	r%   r7   r8   r0   r:   r;   ro   rp   rq   )	r,   r0   ri   rj   r<   r=   r>   r?   r   s	            r.   watch_my_tradeszalpaca.watch_my_trades:  s      iit$Y/$$$ !!![[(F3<'KO,
 zz#{DKK4PR]^^??OOFE2E))&%TRR 	%! _s4   *CCCCACC8CCCc                   K   | j                   d   d   d   }| j                  |       d{    | j                          d{    d}|| j                  |      }|d   }d|z   }dd	d
gid}| j	                  ||| j                  ||      |       d{   }	| j                  r|	j                  ||      }| j                  |	|||d      S 7 7 7 ;w)a  
        watches information on multiple orders made by the user
        :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>`
        r!   r   r    Nordersr0   orders:r   r   r   r   T)	r%   r7   r8   r9   r:   r;   ro   rp   filter_by_symbol_since_limit)
r,   r0   ri   rj   r<   r=   r>   r9   r?   r   s
             r.   watch_orderszalpaca.watch_ordersY  s      iit$Y/$$$!!![[(FH%F#f,KO,
 zz#{DKK4PR]^^??OOFE2E00tTT! 	%! _s4   *CCCCACC8CCCc                 L    | j                  ||       | j                  ||       y N)handle_orderhandle_my_trader,   rA   rF   s      r.   handle_trade_updatezalpaca.handle_trade_updateu  s"    &'*VW-r/   c                 z   | j                  |di       }| j                  |di       }| j                  -| j                  | j                  dd      }t	        |      | _        | j                  }| j                  |      }|j                  |       d}|j                  ||       d|d   z   }|j                  ||       y )Nr   orderordersLimitrx   r   r   r0   )ry   r   r{   r&   r   parse_orderr}   rE   )	r,   rA   rF   r   rawOrderrj   r   r   r>   s	            r.   r   zalpaca.handle_ordery  s    \ w3??4"5;;%%dllM4HE07DK  *ev{+%/1v{+r/   c                    | j                  |di       }| j                  |d      }|dk7  r|dk7  ry | j                  |di       }| j                  }|(| j                  | j                  dd      }t        |      }| j                  |      }|j                  |       d|d	   z   }	|j                  ||	       d
}	|j                  ||	       y )Nr   eventfillpartial_fillr   r   rx   z	myTrades:r0   r   )	ry   rc   r   r{   r&   r   parse_my_trader}   rE   )
r,   rA   rF   r   r   r   r   rj   trader>   s
             r.   r   zalpaca.handle_my_trade  s    \ w3  w/F?u6??4"5==%%dllM4HE-e4H##H-!E(O3x- x-r/   c                    | j                  |d      }| j                  |d      }| j                  |d      }|j                  d      dk\  rd}| j                  | j                  |d      || j                  |      || j	                  |d d      | j                  |d      || j                  |d	      |d
k(  rdnd| j                  |d      | j                  |d      d d d|      S )Nr0   	filled_attyperj   r   r   /r4   sider9   takermakerfilled_avg_price
filled_qty)r4   rb   rL   rM   r0   r   r   r   takerOrMakerpriceamountcostfee)rc   find
safe_traderf   re   )r,   r   r9   rg   rM   r   s         r.   r   zalpaca.parse_my_trade  s    L ##E84##E;7v.99W"D""5#.1 &&xs;%%eT2$$UF3(,(8Gw%%e-?@&&ul; 
  	r/   c                   K   | j                          d}| j                  |      }|j                  |      }| j                  |j                  |      }|cd| j
                  | j                  d}|| j                  d   d   d   k(  rd| j
                  | j                  dd	}| j                  |||||       | d {   S 7 w)
Nauthenticatedauth)r5   keysecretr!   r   r    r7   )key_id
secret_keyr   )	check_required_credentialsrA   futurery   subscriptionsapiKeyr   r%   r:   )r,   r=   r<   r>   rA   r   r   r?   s           r.   r7   zalpaca.authenticate.  s     '')%S!{+(<(<kJ  {{++G
 dii&t,Y77 -"&++&*kk JJsK+vF||s   B;C=C>Cc                     | j                  |d      }| j                  |di       }t        | j                  dz   |z   dz   |z         )Ncodemsgz code: z
 message: )rc   ry   r   r4   )r,   rA   rF   r   r   s        r.   handle_error_messagezalpaca.handle_error_messageF  sK     0oogub1DGGi/$6EKLLr/   c                     |S r    r   s      r.   handle_connectedzalpaca.handle_connectedR  s	     r/   c                    t        dt        |            D ]  }||   }| j                  |d      }| j                  |d      }|dk(  r| j                  ||        y |dk(  r|dk(  r| j	                  ||        y |dk(  r|dk(  r| j                  ||        y | j                  | j                  | j                  | j                  | j                  d}| j                  ||      }| |||        y )	Nr   Tr   subscriptionsuccess	connectedr   )errorr   qrK   o)r   r   rc   handle_subscriptionr   handle_authenticater   r   rH   r   r   ry   )	r,   rA   rF   r   r   r   r   methodsmethods	            r.   handle_crypto_messagezalpaca.handle_crypto_message[  s    q#g,' 	%A1:D  s+A""4/CN"((6I~#"4%%fd3I~#"8((622&&''''++G __Wa0F!vt$-	%r/   c                     | j                  |d      }| j                  | j                  | j                  d}| j	                  ||      }|
 |||       y y )Nstream)authorization	listeningr   )rc   r   r   r   ry   )r,   rA   rF   r   r   r   s         r.   handle_trading_messagezalpaca.handle_trading_messaget  s]    !!'84!5511!55

 &167# r/   c                 n    t        |t              r| j                  ||       y | j                  ||       y r   )
isinstancelistr   r   r   s      r.   handle_messagezalpaca.handle_message  s/    gt$&&vw7##FG4r/   c                     | j                  |d      }| j                  |di       }| j                  |d      }|dk(  s|dk(  r!|j                  d   }|j                  |       y t	        | j
                  dz         )Nr   r   statusr   
authorizedr   z failed to authenticate.)rc   ry   futuresrE   r   r4   )r,   rA   rF   r   r   r  promises          r.   r   zalpaca.handle_authenticate  sz    4 Wc*w3!!$1	>V|3nn_5GOOG$!$'',F"FGGr/   c                     |S r   r   r   s      r.   r   zalpaca.handle_subscription  s	    ( r/   r   ))__name__
__module____qualname__r   r+   strr   r@   r   rH   rC   r   r   r  rt   r   r	   r   r   r   r   r   r   r   r
   r   r   r   r   r   r   r   r7   r   r   r   r   r  r   r   __classcell__)r-   s   @r.   r   r      s   %# %N 68 ] ]F ]*:F :$#6 #J 8<$]ajl H HC HWZ Hquvzq{ H8,6 ,6 @DB !S ! !S\ !0*/ */X$3 <@d[] S SS S Sbfglbm S6,F ,0 37TX\eg SC Ss SRU Slpqvlw S> 04$UYbd U UC Us Uimnsit U8.& .9,6 9,v<.f <.|:x .0 0
M6 
Mv %F %2	$V 	$5V 5!H& !HF& r/   r   )ccxt.async_supportccxt ccxt.async_support.base.ws.cacher   r   r   ccxt.base.typesr   r   r   r	   r
   r   r   !ccxt.async_support.base.ws.clientr   typingr   ccxt.base.errorsr   r   async_supportr   r   r/   r.   <module>r     s?     f f J J J 4  * 0m
T&& m
r/   