
    ein                         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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dS )
    N)
ArrayCacheArrayCacheBySymbolByIdArrayCacheByTimestamp)AnyBool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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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                 &   |                      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ddd	ddddiddddidi i ddi iid          S )NwsT&createOrderWithTakeProfitAndStopLossWsFcreateReduceOnlyOrderWscreateStopLossOrderWscreateTakeProfitOrderWsfetchPositionForSymbolWsfetchPositionsForSymbolWsfetchPositionsWsfetchPositionWsunWatchPositionswatchBalancewatchLiquidationswatchLiquidationsForSymbolswatchMarkPricewatchMarkPriceswatchMyLiquidationswatchMyLiquidationsForSymbols)	watchMyTrades
watchOHLCVwatchOrderBookwatchOrderswatchPositionwatchPositionswatchTickerwatchTickerswatchTradesz/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    M/var/www/html/volatility/venv/lib/python3.11/site-packages/ccxt/pro/alpaca.pyr<   zalpaca.describe   s   fd 3 3 < < > >d8% *5 (	
 *5 +E ,U #E "5 #E  $U .u !% "5  &u!" 0#$ "&""&#!&"'# %#5  < "S#D  "S#J   ]4A
 4A
 4 4 4	    symbolc                 ^  K   | j         d         d         d         }|                     |           d{V  |                                  d{V  |                     |          }d|d         z   }d|d         gd	}|                     |||                     ||          |           d{V S )
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>`
        r2   r   r0   Nticker:rA   	subscribeid)actionquotes)r6   authenticateload_marketsmarketwatchextend)r=   rA   paramsurlrJ   messageHashrequests          r?   watch_tickerzalpaca.watch_tickerH   s       it$X.$$$$$$$$$!!!!!!!!!V$$&"22!d|n
 
 ZZ[$++gv2N2NP[\\\\\\\\\r@   clientc                     |                      |          }|d         }d|z   }|| j        |<   |                    | j        |         |           d S )NrA   rC   )parse_tickertickersresolve)r=   rR   messagetickerrA   rO   s         r?   handle_tickerzalpaca.handle_ticker]   sX     ""7++!&(%Vt|F+[99999r@   Nc                    |                      |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|          S )NStrA   	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=   rX   rJ   marketIdr^   s        r?   rT   zalpaca.parse_tickero   s    ##FC00##FC00 !
d&&x88!
11!
 !
 D	!

 4!
 4##FD11!
 ))&$77!
 4##FD11!
 ))&$77!
 D!
 D!
 T!
 D!
 T!
 d!
  $!!
" t#!
$ )!
 !
 !
* +  	r@   1m	timeframesincelimitc                   K   | j         d         d         d         }|                     |           d{V  |                                  d{V  |                     |          }|d         }d|d         gd}d	|z   }	|                     ||	|                     ||          |	           d{V }
| j        r|
                    ||          }|                     |
||d
d          S )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
        r2   r   r0   NrA   rD   rE   )rF   barsohlcv:r   T	r6   rH   rI   rJ   rK   rL   
newUpdatesgetLimitfilter_by_since_limit)r=   rA   rz   r{   r|   rM   rN   rJ   rP   rO   ohlcvs              r?   watch_ohlcvzalpaca.watch_ohlcv   s      it$X.$$$$$$$$$!!!!!!!!!V$$!!D\N
 
 'jjk4;;w3O3OQ\]]]]]]]]? 	2NN6511E))%q$GGGr@   c                    |                      |d          }|                     |          }|                     | j        |          }|5|                     | j        dd          }t          |          }|| j        |<   |                     |          }|                    |           d|z   }|	                    ||           d S )Nr[   
OHLCVLimit  r   )
rt   rv   
safe_valueohlcvssafe_integerr7   r   parse_ohlcvappendrV   	r=   rR   rW   rx   rA   storedr|   parsedrO   s	            r?   handle_ohlcvzalpaca.handle_ohlcv   s     ##GS11!!(++f55>%%dlL$GGE*511F"(DK!!'**f'v{+++++r@   c                   K   | j         d         d         d         }|                     |           d{V  |                                  d{V  |                     |          }|d         }d|z   }d|d         gd	}|                     |||                     ||          |           d{V }|                                S )
aF  
        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
        r2   r   r0   NrA   
orderbook:rD   rE   )rF   
orderbooks)r6   rH   rI   rJ   rK   rL   r|   )	r=   rA   r|   rM   rN   rJ   rO   rP   	orderbooks	            r?   watch_order_bookzalpaca.watch_order_book   s       it$X.$$$$$$$$$!!!!!!!!!V$$!'&0!!$<.
 
 **S+t{{7F7S7SU`aaaaaaaa	   r@   c           	         |                      |d          }|                     |          }|                      |d          }|                     |          }|                     |dd          }|| j        vr|                                 | j        |<   | j        |         }|r1|                     |||dddd          }	|                    |	           np|                     |dg           }
|                     |dg           }| 	                    |d	         |
           | 	                    |d
         |           ||d<   ||d<   d|z   }|| j        |<   |
                    ||           d S )Nr[   r\   rFbapsasksbidsr]   r^   r   )rt   rv   rw   	safe_boolr   
order_bookparse_order_bookreset	safe_listhandle_deltasrV   )r=   rR   rW   rx   rA   r^   r]   
isSnapshotr   snapshotr   r   rO   s                r?   handle_order_bookzalpaca.handle_order_book   sx   , ##GS11!!(++##GS11NN8,,	^^GS%88
$/))&*oo&7&7DOF#OF+	 		-,,WficSVX[\\HOOH%%%%>>'333D>>'333Dy0$777y0$777%.Ik"$,Ij!'&0"+y+.....r@   c                 ^    |                      |dd          }|                    |           d S )Nr   r   )parse_bid_ask
storeArray)r=   booksidedeltabidAsks       r?   handle_deltazalpaca.handle_delta  s3    ##E344F#####r@   c                 ~    t          dt          |                    D ]}|                     |||                    d S )Nr   )rangelenr   )r=   r   deltasis       r?   r   zalpaca.handle_deltas  sH    q#f++&& 	3 	3Ahq	2222	3 	3r@   c                   K   | j         d         d         d         }|                     |           d{V  |                                  d{V  |                     |          }|d         }d|z   }d|d         gd	}|                     |||                     ||          |           d{V }	| j        r|	                    ||          }|                     |	||d
d          S )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>`
        r2   r   r0   NrA   trade:rD   rE   )rF   tradesr]   Tr   )
r=   rA   r{   r|   rM   rN   rJ   rO   rP   r   s
             r?   watch_tradeszalpaca.watch_trades  s      it$X.$$$$$$$$$!!!!!!!!!V$$!'!d|n
 
 zz#{DKK4P4PR]^^^^^^^^? 	3OOFE22E))&%TRRRr@   c                    |                      |d          }|                     |          }|                     | j        |          }|5|                     | j        dd          }t          |          }|| j        |<   |                     |          }|                    |           d|z   }|	                    ||           d S )Nr[   tradesLimitr   r   )
rt   rv   r   r   r   r7   r   parse_trader   rV   r   s	            r?   handle_tradeszalpaca.handle_trades2  s     ##GS11!!(++f55>%%dlM4HHE&&F"(DK!!'**f#f,v{+++++r@   c                   K   | j         d         d         d         }|                     |           d{V  d}|                                  d{V  ||                     |          }|d|z   z  }ddd	gid
}|                     |||                     ||          |           d{V }| j        r|                    ||          }|                     |||dd          S )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>`
        r2   r   r1   NmyTrades:listenstreamstrade_updatesrF   datar]   T)	r6   rH   rI   rA   rK   rL   r   r   r   )	r=   rA   r{   r|   rM   rN   rO   rP   r   s	            r?   watch_my_tradeszalpaca.watch_my_tradesJ  s!      it$Y/$$$$$$$$$ !!!!!!!!![[((F3<'KO,
 
 zz#{DKK4P4PR]^^^^^^^^? 	3OOFE22E))&%TRRRr@   c                   K   | j         d         d         d         }|                     |           d{V  |                                  d{V  d}|"|                     |          }|d         }d|z   }dd	d
gid}|                     |||                     ||          |           d{V }	| j        r|	                    ||          }|                     |	|||d          S )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>`
        r2   r   r1   NordersrA   orders:r   r   r   r   T)	r6   rH   rI   rJ   rK   rL   r   r   filter_by_symbol_since_limit)
r=   rA   r{   r|   rM   rN   rO   rJ   rP   r   s
             r?   watch_orderszalpaca.watch_ordersi  s'      it$Y/$$$$$$$$$!!!!!!!!![[((FH%F#f,KO,
 
 zz#{DKK4P4PR]^^^^^^^^? 	3OOFE22E00tTTTr@   c                 ^    |                      ||           |                     ||           d S N)handle_orderhandle_my_trader=   rR   rW   s      r?   handle_trade_updatezalpaca.handle_trade_update  s4    &'***VW-----r@   c                    |                      |di           }|                      |di           }| j        0|                     | j        dd          }t	          |          | _        | j        }|                     |          }|                    |           d}|                    ||           d|d         z   }|                    ||           d S )Nr   orderordersLimitr   r   r   rA   )r   r   r   r7   r   parse_orderr   rV   )	r=   rR   rW   r   rawOrderr|   r   r   rO   s	            r?   r   zalpaca.handle_order  s    \ w33??4"55;%%dlM4HHE077DK  **ev{+++%/1v{+++++r@   c                    |                      |di           }|                     |d          }|dk    r|dk    rd S |                      |di           }| j        }|+|                     | j        dd          }t          |          }|                     |          }|                    |           d|d	         z   }	|                    ||	           d
}	|                    ||	           d S )Nr   eventfillpartial_fillr   r   r   z	myTrades:rA   r   )	r   rt   r   r   r7   r   parse_my_trader   rV   )
r=   rR   rW   r   r   r   r   r|   traderO   s
             r?   r   zalpaca.handle_my_trade  s    \ w33  w//F??u66F??4"55=%%dlM4HHE-e44H##H--!E(O3x--- x-----r@   c                 ,   |                      |d          }|                      |d          }|                      |d          }|                    d          dk    rd}|                     |                      |d          ||                     |          ||                     |d d          |                      |d          ||                      |d	          |d
k    rdnd|                      |d          |                      |d          d d d|          S )NrA   	filled_attyper|   r   r   /rE   siderJ   takermakerfilled_avg_price
filled_qty)rE   rs   r]   r^   rA   r   r   r   takerOrMakerpriceamountcostfee)rt   find
safe_traderw   rv   )r=   r   rJ   rx   r^   r   s         r?   r   zalpaca.parse_my_trade  s)   L ##E844##E;77v..99W""D""5#..11 &&xs;;%%eT22$$UF33(,(8(8GGw%%e-?@@&&ul;; 
  
   	r@   c                   K   |                                   d}|                     |          }|                    |          }|                     |j        |          }|Xd| j        | j        d}|| j        d         d         d         k    rd| j        | j        dd	}|                     |||||           | d {V S )
Nauthenticatedauth)rF   keysecretr2   r   r1   rH   )key_id
secret_keyr   )	check_required_credentialsrR   reusableFuturer   subscriptionsapiKeyr   r6   rK   )r=   rN   rM   rO   rR   futurer   rP   s           r?   rH   zalpaca.authenticate>  s      '')))%S!!&&{33(<kJJ  {+ G
 di&t,Y777 -"&+&*k   JJsK+vFFF||||||r@   c                     |                      |d          }|                     |di           }t          | j        dz   |z   dz   |z             )Ncodemsgz code: z
 message: )rt   r   r   rE   )r=   rR   rW   r   r   s        r?   handle_error_messagezalpaca.handle_error_messageV  sR     00oogub11DGi/$6EKLLLr@   c                     |S r    r   s      r?   handle_connectedzalpaca.handle_connectedb  s	     r@   c                 
   t          dt          |                    D ]}||         }|                     |d          }|                     |d          }|dk    r|                     ||            d S |dk    r|dk    r|                     ||            d S |dk    r|dk    r|                     ||            d S | j        | j        | j        | j	        | j
        d}|                     ||          }| |||           d S )	Nr   Tr   subscriptionsuccess	connectedr   )errorr   qr\   o)r   r   rt   handle_subscriptionr   handle_authenticater   r   rY   r   r   r   )	r=   rR   rW   r   r   r   r   methodsmethods	            r?   handle_crypto_messagezalpaca.handle_crypto_messagek  s>   q#g,,'' 	% 	%A1:D  s++A""4//CN""((666I~~#"4"4%%fd333I~~#"8"8((6662&''+ G __Wa00F!vt$$$-	% 	%r@   c                     |                      |d          }| j        | j        | j        d}|                     ||          }| |||           d S d S )Nstream)authorization	listeningr   )rt   r  r  r   r   )r=   rR   rW   r  r  r	  s         r?   handle_trading_messagezalpaca.handle_trading_message  sp    !!'844!51!5
 

 &11F67##### r@   c                     t          |t                    r|                     ||           d S |                     ||           d S r   )
isinstancelistr
  r  r   s      r?   handle_messagezalpaca.handle_message  sK    gt$$ 	&&vw777F##FG44444r@   c                    |                      |d          }|                     |di           }|                      |d          }|dk    s|dk    r$|j        d         }|                    |           d S t	          | j        dz             )Nr   r   statusr  
authorizedr   z failed to authenticate.)rt   r   futuresrV   r   rE   )r=   rR   rW   r   r   r  promises          r?   r  zalpaca.handle_authenticate  s    4 Wc**w33!!$11	>>V|33n_5GOOG$$$F!$',F"FGGGr@   c                     |S r   r   r   s      r?   r  zalpaca.handle_subscription  s	    ( r@   r   )*__name__
__module____qualname__r   r<   strr   rQ   r   rY   rT   r   r   r  r   r   r
   r   r   r   r   r   r   r   r   r   r	   r   r   r   r   r   rH   r   r   r   r
  r  r  r  r  __classcell__)r>   s   @r?   r   r      s       5# 5 5 5 5 5 5n 68 ] ] ]F ] ] ] ]*:F : : : :$# #6 # # # #J ?CQUdhqs H H H H3 H^a Hx|  ~B  yC H H H H8,6 , , , ,6 @DB ! !S ! !S\ ! ! ! !0*/ */ */ */ */X$ $ $3 3 3 <@d[] S S SS S Sbfglbm S S S S6,F , , , ,0 37TX\eg S SC Ss SRU Slpqvlw S S S S> 04$UYbd U U UC Us Uimnsit U U U U8.& . . . .9,6 9, 9, 9, 9,v<.f <. <. <. <.|: : : :x .0    0
M6 
Mt 
M 
M 
M 
Mv    %F % % % %2	$V 	$ 	$ 	$ 	$5V 5 5 5 5!H& !H !H !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   r   !ccxt.async_support.base.ws.clientr   typingr   ccxt.base.errorsr   r   async_supportr   r   r@   r?   <module>r'     s        f f f f f f f f f f P P P P P P P P P P P P P P P P P P P P 4 4 4 4 4 4       * * * * * * 0 0 0 0 0 0}
 }
 }
 }
 }
T& }
 }
 }
 }
 }
r@   