
    i                         d dl mZ d dlm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 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dS )    )Exchange)ImplicitAPI)	IntMarketNumOrder	OrderBook	OrderSide	OrderTypeStrTrade)List)ExchangeError)PermissionDenied)
BadRequest)	BadSymbol)InsufficientFunds)InvalidOrder)NotSupported)RateLimitExceeded)	TICK_SIZEc                       e Zd Z fdZi fdZi fdee         fdZdefdZ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ddi fde	de
d	e
dee         fdZd$dedefdZdi fde	dedededef
dZdi fde	defdZdi fdefdZdi fde	defdZdddi fdede
d	e
dee         fdZd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edefdZd Z d Z!d$dedefdZ"d d!i ddfd"Z#d# Z$ xZ%S )%alpacac                 \   |                      t          t          |                                           i ddddddgddd	d
dddddddddddddddddi ddddddddd dd!dd"dd#dd$dd%dd&dd'dd(dd)dd*dd+dd,di d-dd.dd/dd0dd1dd2dd3dd4dd5dd6dd7dd8dd9d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@g dAg dBdCdDgdEdFgg dGdHidIg dJidIg dKidLddMdNdOdPdQdRdSdTdUdVdWdXdYdZd[d\d]d^t          d_ddd`dadbdd|                     dc          |                     dd          |                     de          |                     dd          g|                     df          |                     dg          g|                     dh          |                     di          g|                     dj          |                     dk          g|                     dl          |                     dc          g|                     dm          |                     dn          g|                     do          |                     dp          g|                     dq          |                     dr          gg|                     de          |                     dc          g|                     df          |                     dp          g|                     dh          |                     dr          g|                     dj          |                     ds          g|                     dl          |                     dt          g|                     dm          |                     du          g|                     do          |                     du          g|                     dq          |                     dv          ggdwdxidydzd{id|d}g d~ddddt          t          t          t          t          t          dt          t          dd          S )Nidr   nameAlpaca	countriesUS	rateLimitiM  hostnamezalpaca.marketsproTurlszdhttps://user-images.githubusercontent.com/1294454/187234005-b864db3d-f1e3-447a-aaf9-a9fc7b955d07.jpgzhttps://alpaca.marketszhttps://broker-api.{hostname}zhttps://api.{hostname}zhttps://data.{hostname})brokertradermarketz%https://broker-api.sandbox.{hostname}zhttps://paper-api.{hostname}zhttps://data.sandbox.{hostname}zhttps://alpaca.markets/docs/z,https://docs.alpaca.markets/docs/crypto-fees)logowwwapitestdocfeeshasCORSFspotmarginswapfutureoptioncancelAllOrderscancelOrdercloseAllPositionsclosePositioncreateOrderfetchBalancefetchBidsAsksfetchClosedOrdersfetchCurrenciesfetchDepositAddressfetchDepositAddressesByNetworkfetchDepositsfetchDepositsWithdrawalsfetchFundingHistoryfetchFundingRatefetchFundingRatesfetchL1OrderBookfetchL2OrderBookfetchMarketsfetchMyTrades
fetchOHLCVfetchOpenOrderfetchOpenOrders
fetchOrderfetchOrderBookfetchOrdersfetchPositionsfetchStatus)fetchTickerfetchTickers	fetchTimefetchTradesfetchTradingFeefetchTradingFeesfetchTransactionFeesfetchTransactionsfetchTransfersfetchWithdrawalssetLeveragesetMarginModetransferwithdrawr)   private)z
v2/account	v2/ordersv2/orders/{order_id}v2/positions!v2/positions/{symbol_or_asset_id}zv2/account/portfolio/historyv2/watchlistsv2/watchlists/{watchlist_id}v2/watchlists:by_namev2/account/configurationszv2/account/activitiesz%v2/account/activities/{activity_type}zv2/calendarzv2/clockz	v2/assetszv2/assets/{symbol_or_asset_id}z'v2/corporate_actions/announcements/{id}z"v2/corporate_actions/announcements)r_   rc   rd   re   rd   re   r`   rf   )r_   r`   ra   rb   rd   re   z%v2/watchlists/{watchlist_id}/{symbol})getpostputpatchdeleterg   )zv1beta3/crypto/{loc}/barsz v1beta3/crypto/{loc}/latest/barsz&v1beta3/crypto/{loc}/latest/orderbooksz"v1beta3/crypto/{loc}/latest/quotesz"v1beta3/crypto/{loc}/latest/tradeszv1beta3/crypto/{loc}/quoteszv1beta3/crypto/{loc}/snapshotszv1beta3/crypto/{loc}/trades)zv1beta1/corporate-actionszv1beta1/forex/latest/rateszv1beta1/forex/rateszv1beta1/logos/{symbol}zv1beta1/newsz$v1beta1/screener/stocks/most-activesz%v1beta1/screener/{market_type}/moverszv2/stocks/auctionszv2/stocks/barszv2/stocks/bars/latestz$v2/stocks/meta/conditions/{ticktype}zv2/stocks/meta/exchangeszv2/stocks/quoteszv2/stocks/quotes/latestzv2/stocks/snapshotszv2/stocks/tradeszv2/stocks/trades/latestzv2/stocks/{symbol}/auctionszv2/stocks/{symbol}/barszv2/stocks/{symbol}/bars/latestzv2/stocks/{symbol}/quotesz v2/stocks/{symbol}/quotes/latestzv2/stocks/{symbol}/snapshotzv2/stocks/{symbol}/tradesz v2/stocks/{symbol}/trades/latest)publicr^   
timeframes1min3min5min15min30min1H2H4H6H8H12H1D3D1W1M)1m3m5m15m30m1h2h4h6h8h12h1d3d1wr|   precisionModerequiredCredentials)apiKeysecretr,   tradingz0.0015z0.00250100000z0.0022500000z0.00201000000z0.00181000000025000000z0.001350000000z0.0012	100000000z0.001z0.0008z0.0005z0.0002z0.00)takermaker)	tierBased
percentager   r   tiersheaderszAPCA-PARTNER-IDccxtoptionsCBSE)r   FTXGNSSERSXgtcz	ccxt_{id})defaultExchange	exchangesdefaultTimeInForceclientOrderId
exceptions)z
forbidden.4041000040010001401100004031000042910000)zInvalid format for parameterzInvalid symbol)exactbroad)deep_extendsuperr   describer   parse_numberr   r   r   r   r   r   )self	__class__s    _/var/www/html/crypto-bot/backend/venv/lib/python3.11/site-packages/ccxt/async_support/alpaca.pyr   zalpaca.describe   s+   fd 3 3 < < > > zA
(zA
HzA
 $zA
 zA
 (zA
 4zA
 ~/=67  F<? 
 6F zA
4  111 %1 	1
 %1 %1 "41 t1 $U1  1 t1 1  1 $T1 "51  &u!1" 1%#1 1$  %1& +E'1( &u)1* #E+1, $U-1. #D/10 #E112 314  516 d718 !%91: "4;1< d=1> !$?1@ tA1B !%C1D uE1 1F  % %!##($)(-%*"'$)$!&!!a1 1 15zA
X       (! ! ! ;3 
 37"# # #G,  , .b  	  	  	         * *e] ]YzA
T  UzA
v YwzA
x "$ $yzA
@ !%"&!..x88!..x88 "..s33T5F5Fx5P5PQ!..x88$:K:KH:U:UV!..x88$:K:KH:U:UV!..y994;L;LX;V;VW!..z::D<M<Mh<W<WX!..z::D<M<Mh<W<WX!..z::D<M<Mh<W<WX!..{;;T=N=Nw=W=WX	" "..s33T5F5Fx5P5PQ!..x88$:K:KH:U:UV!..x88$:K:KG:T:TU!..y994;L;LX;V;VW!..z::D<M<Mh<W<WX!..z::D<M<Mh<W<WX!..z::D<M<Mh<W<WX!..{;;T=N=Nv=V=VW	"  AzA
| !6}zA
B #)   ',!,
 
CzA
X "2 , * 0 1 1  5?&/  YzA
 z z z	    c                 >  K   |                      |           d{V }|                     |d          }|dd         }t          |          dz
  }t          |          dz
  }|||         }|                     |          |                     |          dz  dz  z
  }|S )	a  
        fetches the current integer timestamp in milliseconds from the exchange server
        :param dict [params]: extra parameters specific to the exchange API endpoint
        :returns int: the current integer timestamp in milliseconds from the exchange server
        N	timestampr            i  i  )traderPrivateGetV2Clocksafe_stringlen	parse8601parse_to_numeric)	r   paramsresponser   	localTimejetlagStrStartjetlagStrEndjetlagisos	            r   
fetch_timezalpaca.fetch_time  s       55f======== $$X{;;	adO	Y!+9~~)>,67nnY''$*?*?*G*G$*NQU*UU
r   returnc                    K   ddd}|                      |                     ||                     d{V }|                     |          S )a  
        retrieves data on all markets for alpaca
        :see: https://docs.alpaca.markets/reference/get-v2-assets
        :param dict [params]: extra parameters specific to the exchange api endpoint
        :returns dict[]: an array of objects representing market data
        cryptoactive)asset_classstatusN)traderPrivateGetV2Assetsextendparse_markets)r   r   requestassetss       r   fetch_marketszalpaca.fetch_markets+  se       $
 
 44T[[&5Q5QRRRRRRRR. !!&)))r   c                    |                      |d          }|                    d          }|                      |d          }|                      |d          }|                      |d          }|                     |          }|                     |          }||dk    rd}|dz   |z   }	|                      |d          }
|
d	k    }|                     |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!
S )"Nsymbol/classr      	us_equityUSDr   r   min_order_sizemin_trade_incrementprice_incrementr   basequotesettlebaseIdquoteIdsettleIdtyper/   Tr0   r1   Fr2   r3   contractlinear)amountprice)minmax)leverager   r   cost)
inversecontractSizeexpiryexpiryDatetimestrike
optionType	precisionlimitscreatedinfo)r   splitsafe_currency_codesafe_number)r   assetmarketIdparts
assetClassr   r   r   r   r   r   r   	minAmountr   r   s                  r   parse_marketzalpaca.parse_marketO  st   * ##E844s##%%eW55
!!%++""5!,,&&v..''00 =Z;66Ee#!!%22H$$$U,<==	!!%)>??  (9::0
(0
f0
 D0
 U	0

 d0
 f0
 w0
 0
 F0
 D0
 d0
 E0
 e0
 e0
 f0
  !0
" d#0
$  "     
 % 
   
    $ _0
 0
 0
 0	
r   Nr   sincelimitc                 P  K   |                                   d{V  |                     |          }|d         }|                     |dd          }|                     |dd          }||d}	|                     |ddg          }d}
|dk    r||                     |          |	d<   |||	d	<   |                     |                     |	|                     d{V }|                     |d
i           }|                     ||g           }
n|dk    ra| 	                    |                     |	|                     d{V }|                     |d
i           }|                     ||i           }
|
g}
nt          | j        dz   |z   dz             |                     |
|||          S )a  
        get the list of most recent trades for a particular symbol
        :see: https://docs.alpaca.markets/reference/cryptotrades
        :see: https://docs.alpaca.markets/reference/cryptolatesttrades
        :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
        :param str [params.loc]: crypto location, default: us
        :param str [params.method]: method, default: marketPublicGetV1beta3CryptoLocTrades
        :returns Trade[]: a list of `trade structures <https://docs.ccxt.com/#/?id=public-trades>`
        Nr   locusmethod%marketPublicGetV1beta3CryptoLocTradessymbolsr  startr  trades+marketPublicGetV1beta3CryptoLocLatestTradesz  fetchTrades() does not support ze, marketPublicGetV1beta3CryptoLocTrades and marketPublicGetV1beta3CryptoLocLatestTrades are supported)load_marketsr&   r   omitiso8601r	  r   	safe_dict	safe_listr  r   r   parse_trades)r   r   r  r  r   r&   r   r  r  r   symbolTradesr   r  s                r   fetch_tradeszalpaca.fetch_trades  s      !!!!!!!!!V$$$<vud33!!&(4[\\
 
 6E8#455<<< #'<<#6#6  #( !GGT[]cHdHdeeeeeeeeH" ^^Hh;;F>>&(B??LLDDD!MMdkkZaciNjNjkkkkkkkkH ^^Hh;;F>>&(B??L(>LLtw)KKfT  X     @  @  @  vueDDDr   c           	        K   |                                   d{V  |                     |          }|d         }|                     |dd          }||d}|                     |                     ||                     d{V }|                     |di           }	|                     |	|i           }
|                     |                     |
d                    }|                     |
|d         |d	d
dd          S )a  
        fetches information on open orders with bid(buy) and ask(sell) prices, volumes and other data
        :see: https://docs.alpaca.markets/reference/cryptolatestorderbooks
        :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 str [params.loc]: crypto location, default: us
        :returns dict: A dictionary of `order book structures <https://github.com/ccxt/ccxt/wiki/Manual#order-book-structure>` indexed by market symbols
        Nr   r  r  r
  
orderbookstr   baps)r  r&   r   /marketPublicGetV1beta3CryptoLocLatestOrderbooksr   
safe_valuer   parse_order_book)r   r   r  r   r&   r   r  r   r   r  rawOrderbookr   s               r   fetch_order_bookzalpaca.fetch_order_book  s      !!!!!!!!!V$$D\vud33
 
 MMdkkZaciNjNjkkkkkkkkL __X|R@@
z2r::NN4#3#3L##F#FGG	$$\6(3CYPSUXZ]_bcccr   r}   c                   K   |                                   d{V  |                     |          }|d         }|                     |dd          }|                     |dd          }	||d}
|                     |ddg          }d}|	dk    r|||
d<   ||                     |          |
d	<   |                     | j        ||          |
d
<   |                     |                     |
|                     d{V }|                     |di           }| 	                    ||g           }n|	dk    ra| 
                    |                     |
|                     d{V }|                     |di           }|                     ||i           }|g}nt          | j        dz   |	z   dz             |                     |||||          S )ai  
        fetches historical candlestick data containing the open, high, low, and close price, and the volume of a market
        :see: https://docs.alpaca.markets/reference/cryptobars
        :see: https://docs.alpaca.markets/reference/cryptolatestbars
        :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 alpha api endpoint
        :param str [params.loc]: crypto location, default: us
        :param str [params.method]: method, default: marketPublicGetV1beta3CryptoLocBars
        :returns int[][]: A list of candles ordered, open, high, low, close, volume
        Nr   r  r  r  #marketPublicGetV1beta3CryptoLocBarsr
  r  r  	timeframebars)marketPublicGetV1beta3CryptoLocLatestBarsz fetchOHLCV() does not support za, marketPublicGetV1beta3CryptoLocBars and marketPublicGetV1beta3CryptoLocLatestBars are supported)r  r&   r   r  yyyymmddrm   r$  r   r  r  r'  r   r   parse_ohlcvs)r   r   r%  r  r  r   r&   r   r  r  r   ohlcvsr   r&  s                 r   fetch_ohlcvzalpaca.fetch_ohlcv*  s#      !!!!!!!!!V$$$<vud33!!&(4YZZ
 
 6E8#455::: #(  #'==#7#7 #'#3#3DOYPY#Z#ZGK !EEdkkRY[aFbFbccccccccH< >>(FB77D^^D(B77FFBBB!KKDKKX_agLhLhiiiiiiiiH" >>(FB77D^^D(B77FXFFtw)JJVS  Wz   z  {  {  {  E5IIIr   r&   c           	      0   |                      |d          }|                     |          }||                     |d          |                     |d          |                     |d          |                     |d          |                     |d          gS )Nr  ohlcv)r   r   r   )r   ohlcvr&   datetimer   s        r   parse_ohlcvzalpaca.parse_ohlcv  s     ##E3//NN8,,	UC((UC((UC((UC((UC((
 	
r   r   sider   r   c                 `  K   |                                   d{V  |                     |          }|d         }||                     ||          ||d}	|                     |ddg          }
|
Yd}|                    d          dk    rd}nt          | j        d	z   |z   d
z             |                     ||
          |	d<   ||	d<   |                    d          dk    r|                     ||          |	d<   |                     | j	        d          }|                     |d|          |	d<   | 
                    |ddg          }|                     | j	        d          }|                                 }|                    d          }d                    |          }|                     |d|i          }|                     |d|          }||	d<   | 
                    |dg          }|                     |                     |	|                     d{V }|                     ||          S )a  
        create a trade order
        :see: https://docs.alpaca.markets/reference/postorder
        :param str symbol: unified symbol of the market to create an order in
        :param str type: 'market', 'limit' or 'stop_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 fullfilled, in units of the quote currency, ignored in market orders
        :param dict [params]: extra parameters specific to the exchange API endpoint
        :param float [params.triggerPrice]: The price at which a trigger order is triggered at
        :returns dict: an `order structure <https://docs.ccxt.com/#/?id=order-structure>`
        Nr   )r   qtyr5  r   triggerPrice
stop_pricer  r   
stop_limitz0 createOrder() does not support stop orders for z- orders, only stop_limit orders are supportedr   limit_pricer   timeInForcetime_in_forcer   - client_order_id)r  r&   amount_to_precisionsafe_string_nfindr   r   price_to_precisionr   r   r  uuidr   joinimplode_paramstraderPrivatePostV2Ordersr   parse_order)r   r   r   r5  r   r   r   r&   r   r   r8  newType
defaultTIFclientOrderIdprefixrE  r   	random_iddefaultClientIdr   orders                       r   create_orderzalpaca.create_order  sg      !!!!!!!!!V$$D\++FF;;	
 
 ))&><2PQQ#Gyy!!Q&&&"47-_#_bf#f  jY  $Y  Z  Z  Z$($;$;FL$Q$QGL!%GFO99W""%)%<%<VU%K%KGM"%%dl4HII
#'#3#3FM:#V#V 6M>#BCC"..t|_MMyy{{

3GGENN	--.AD)CTUU((/RR%2!"6O#45544T[[&5Q5QRRRRRRRRJ v...r   r   c                    K   d|i}|                      |                     ||                     d{V }|                     |di           S )a  
        cancels an open order
        :see: https://docs.alpaca.markets/reference/deleteorderbyorderid
        :param str id: order id
        :param str symbol: unified symbol of the market the order was made in
        :param dict [params]: extra parameters specific to the exchange API endpoint
        :returns dict: An `order structure <https://docs.ccxt.com/#/?id=order-structure>`
        order_idNmessage)"traderPrivateDeleteV2OrdersOrderIdr   r  )r   r   r   r   r   r   s         r   cancel_orderzalpaca.cancel_order  sb       
 @@WV\A]A]^^^^^^^^ xB777r   c                    K   |                                   d{V  |                     |           d{V }t          |t                    r|                     |d          S |S )a  
        cancel all open orders in a market
        :see: https://docs.alpaca.markets/reference/deleteallorders
        :param str symbol: alpaca cancelAllOrders cannot setting symbol, it will cancel all open orders
        :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)r  traderPrivateDeleteV2Orders
isinstancelistparse_orders)r   r   r   r   s       r   cancel_all_orderszalpaca.cancel_all_orders  s~       !!!!!!!!!99&AAAAAAAAh%% 	$$Xt444Or   c                 "  K   |                                   d{V  d|i}|                     |                     ||                     d{V }|                     |d          }|                     |          }|                     ||          S )a  
        fetches information on an order made by the user
        :see: https://docs.alpaca.markets/reference/getorderbyorderid
        :param str symbol: unified symbol of the market the order was made in
        :param dict [params]: extra parameters specific to the exchange API endpoint
        :returns dict: An `order structure <https://docs.ccxt.com/#/?id=order-structure>`
        NrR  r   )r  traderPrivateGetV2OrdersOrderIdr   r   safe_marketrI  )r   r   r   r   r   rO  r   r&   s           r   fetch_orderzalpaca.fetch_order  s       !!!!!!!!!
 ::4;;wPV;W;WXXXXXXXX##E844!!(++v...r   c                   K   |                                   d{V  ddi}d}| |                     |          }|d         |d<   |                     |d          }||                     |d          }||d<   |||d<   |||d	<   |                     |                     ||                     d{V }|                     ||||          S )
a{  
        fetches information on multiple orders made by the user
        :see: https://docs.alpaca.markets/reference/getallorders
        :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
        :param int [params.until]: the latest time in ms to fetch orders for
        :returns Order[]: a list of `order structures <https://docs.ccxt.com/#/?id=order-structure>`
        Nr   allr   r  untilendTimeafterr  )r  r&   safe_integerr  traderPrivateGetV2Ordersr   rZ  )	r   r   r  r  r   r   r&   rb  r   s	            r   fetch_orderszalpaca.fetch_orders"  s      !!!!!!!!!e
 [[((F!'GI!!&'22YYvw//F!&GI$GG$GG66t{{7F7S7STTTTTTTTR   65%@@@r   c           	      r   K   ddi}|                      ||||                     ||                     d{V S )al  
        fetch all unfilled currently open orders
        :see: https://docs.alpaca.markets/reference/getallorders
        :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
        :param int [params.until]: the latest time in ms to fetch orders for
        :returns Order[]: a list of `order structures <https://docs.ccxt.com/#/?id=order-structure>`
        r   openNrg  r   r   r   r  r  r   r   s         r   fetch_open_orderszalpaca.fetch_open_ordersh  sQ       f
 &&vueT[[RX=Y=YZZZZZZZZZr   c           	      r   K   ddi}|                      ||||                     ||                     d{V S )a  
        fetches information on multiple closed orders made by the user
        :see: https://docs.alpaca.markets/reference/getallorders
        :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
        :param int [params.until]: the latest time in ms to fetch orders for
        :returns Order[]: a list of `order structures <https://docs.ccxt.com/#/?id=order-structure>`
        r   closedNrj  rk  s         r   fetch_closed_orderszalpaca.fetch_closed_ordersx  sQ       h
 &&vueT[[RX=Y=YZZZZZZZZZr   c           
         |                      |d          }|                     ||          }|d         }|                      |d          }|                     |          }|                      |d          }d }||dd}|                      |d          }	|	|	                    d          dk    r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 |          S )!Nr   r   
commissionr   )r   currency
order_typer  r   submitted_atr   r   r@  r   r3  lastTradeTimeStampr   r<  r=  postOnlyr5  r   r;  	stopPricer9  r8  r   averagefilled_avg_pricer   r7  
filled_qty)filled	remainingr  feer   )r   r^  parse_order_statusrC  r   
safe_orderparse_time_in_forcer   )r   rO  r&   r   r   alpacaStatusr   feeValuer}  	orderTyper3  r   s               r   rI  zalpaca.parse_order  s   N ##E844!!(F33!''x88((66##E<88 ! C $$UL99	 ~~g&&!++#	##E>::NN8,,	  
$""5$// 
T--e5FGG 
  
 	 

 !$ 
 f 
 f 
 I 
 433D4D4DUO4\4\]] 
  
 D$$UF33 
 T%%e];; 
 ))%>> 
 D,,ULAA 
 D 
  t''/ABB! 
" d&&ue44# 
$ &&ul;;- 
  
  
. /  	r   c                 B    ddddddd}|                      |||          S )Nri  rn  )pending_newacceptednewpartially_filled	activatedr{  r   )r   r   statusess      r   r~  zalpaca.parse_order_status  s:    ! &
 
 &&999r   c                 8    ddi}|                      |||          S )NdayDayr  )r   r<  timeInForcess      r   r  zalpaca.parse_time_in_force  s(    5
 k;GGGr   c                    |                      |d          }|                     ||          }|                      |d          }|                     |          }|                      |d          }|dk    rd}n|dk    rd}|                      |d          }	|                      |d          }
|                     ||                      |d	          ||                     |          |d d |d
|	|
d d d|          S )NSr  tksBbuysellr  r  ir   )r   r   r   r3  r   rO  r   r5  takerOrMakerr   r   r   r}  )r   safe_symbolr   
safe_trader  )r   trader&   r   r   r3  r   
alpacaSider5  priceStringamountStrings              r   parse_tradezalpaca.parse_trade  s    ##E3//!!(F33##E3//NN8,,	%%eU33
DD3D&&uc22''s33""5#.."Y//# " 
  
   	r   rl   GETc                    d|                      ||          z   }|                     | j        d         |d                            }||ni }|d         dk    r| j        |d<   | j        |d<   |                     ||                     |                    }	|	rB|dk    s|d	k    r|d
|                     |	          z   z  }n|                     |	          }d|d<   ||z   }||||dS )Nr   r)   r   r   r^   zAPCA-API-KEY-IDzAPCA-API-SECRET-KEYr  DELETE?zapplication/jsonzContent-Type)urlr  bodyr   )	rG  implode_hostnamer#   r   r   r  extract_params	urlencodejson)
r   pathr)   r  r   r   r  endpointr  querys
             r   signzalpaca.sign  s   ,,T6:::##DIe$4SV$<==%1''q6Y)-G%&-1[G)*		&$"5"5d";";<< 	=%Vx%7%7C$.."7"777yy''*<'HnfdwOOOr   c
                 t   |d S | j         dz   |z   }
|                     |d          }|"|                     | j        d         ||
           |                     |dd           }|S|                     | j        d         ||
           |                     | j        d         ||
           t          |
          d S )N coder   rS  r   )r   r   throw_exactly_matched_exceptionr   r  throw_broadly_matched_exceptionr   )r   r  reasonr  r  r   r  r   requestHeadersrequestBodyfeedback	errorCoderS  s                r   handle_errorszalpaca.handle_errors$  s    4
 7S=4'$$Xv66	001I9V^___//(It<<001I7T\]]]001I7T\]]])))tr   )N)&__name__
__module____qualname__r   r   r   r   r   r  strr   r   r  r	   r"  rY  r+  r4  r   r
   floatr   rP  r   rU  r[  r_  r   rg  rl  ro  rI  r~  r  r  r  r  __classcell__)r   s   @r   r   r      sF       { { { { {z ')    . *, "* "*V "* "* "* "*HV
V V
 V
 V
 V
p <@d[] DE DE DES DE DEbfglbm DE DE DE DEL @DB ;d ;dS ;d ;dS\ ;d ;d ;d ;dz 8<$]ajl VJ VJ VJC VJWZ VJquvzq{ VJ VJ VJ VJp
 
 
4 
 
 
 
0 mqy{ Q/ Q/ Q/I Q/Y Q/X] Q/fi Q/ Q/ Q/ Q/f 9=R 8 8S 8# 8 8 8 8* 59  c     8<B / /C / / / / /" 04$UYbd DA DA DAC DAs DAimnsit DA DA DA DAL 59tZ^gi [ [c [ [TW [nrsxny [ [ [ [  7;\`ik [ [ [3 [VY [ptuzp{ [ [ [ [ Q Q Q5 Q Q Q Qf	: 	: 	:H H H% % %5 % % % %N &eBSW P P P P"      r   r   N) ccxt.async_support.base.exchanger   ccxt.abstract.alpacar   ccxt.base.typesr   r   r   r   r	   r
   r   r   r   typingr   ccxt.base.errorsr   r   r   r   r   r   r   r   ccxt.base.decimal_to_precisionr   r    r   r   <module>r     sa   6 5 5 5 5 5 , , , , , , ` ` ` ` ` ` ` ` ` ` ` ` ` ` ` ` ` ` ` ` ` `       * * * * * * - - - - - - ' ' ' ' ' ' & & & & & & . . . . . . ) ) ) ) ) ) ) ) ) ) ) ) . . . . . . 4 4 4 4 4 4_ _ _ _ _X{ _ _ _ _ _r   