
    E#i<                       S SK Jr  S SKJr  S SKJrJrJrJrJ	r	J
r
JrJrJrJrJrJrJrJrJrJrJr  S SKJr  S SKJr  S SKJr  S SKJr  S SKJr  S S	KJr  S S
KJr  S SKJr  S SKJ r   S SKJ!r!  S SK"J#r#  S SK$J%r%   " S S\\5      r&g)    )Exchange)ImplicitAPI)AnyBalancesCurrencyDepositAddressIntMarketNumOrder	OrderBook	OrderSide	OrderTypeStrStringsTickerTickersTradeTransaction)List)ExchangeError)PermissionDenied)ArgumentsRequired)
BadRequest)	BadSymbol)InsufficientFunds)InvalidOrder)NotSupported)RateLimitExceeded)	TICK_SIZE)Precisec                   t  ^  \ rS rSrS\4U 4S jjr0 4S\4S jjr0 4S\\	   4S jjr
S\	4S jrSS0 4S\S	\S
\S\\   4S jjrS0 4S\S
\S\4S jjrSSS0 4S\S\S	\S
\S\\   4
S jjrSKS\	S\4S jjr0 4S\S\4S jjrS0 4S\S\4S jjrS r0 4S\S\S\4S jjr0 4S\S\4S jjr0 4S\S\4S jjrS0 4S\S\S\S\S\ 4
S jjr!S0 4S\S\"4S  jjr#S0 4S\"4S! jjr$S0 4S\S\"4S" jjr%SSS0 4S\"S	\S
\S\\&   4S# jjr'SSS0 4S\"S	\S
\S\\&   4S$ jjr(SSS0 4S\"S	\S
\S\\&   4S% jjr)SS0 4S\S\S\S\S\ S\ 4S& jjr*SKS'\+S\	S\&4S( jjr,S)\"4S* jr-S+\"4S, jr.SSS0 4S\"S	\S
\4S- jjr/SKS.\+S\	S\4S/ jjr00 4S0\S\14S1 jjr2SKS2\3S\14S3 jjr4S0 4S0\S\S4\S5\"S\54
S6 jjr6S7 r7SSS0 4S0\"S	\S
\S\\5   4S8 jjr8SSS0 4S0\"S	\S
\S\\5   4S9 jjr9SSS0 4S0\"S	\S
\S\\5   4S: jjr:SKS;\+S2\3S\54S< jjr;S)\"4S= jr<S> r=0 4S\>4S? jjr?S\>4S@ jr@SASB0 SS4SC jrAS0\BSD\SE\SF\SG\+SH\4SI jrCSJrDU =rE$ )Lalpaca   returnc                 T	  > U R                  [        [        U ]  5       0 SS_SS_SS/_SS_S	S
_SS_SSSSSSS.SSSS.SSS._S0 SS_SS_SS_SS_SS_S S_S!S_S"S_S#S_S$S_S%S_S&S_S'S_S(S_S)S_S*S_S+S_0 S,S_S-S_S.S_S/S_S0S_S1S_S2S_S3S_S4S_S5S_S6S_S7S_S8S_S9S_S:S_S;S_S<S_E0 S=S_S>S_S?S_S@S_SAS_SBS_SCS_SDS_SES_SFS_SGS_SHS_SIS_SJS_SKS_SLS_SMS_E0 SNS_SOS_SPS_SQS_SRS_SSS_STS_SUS_SVS_SWS_SXS_SYS_SZS_S[S_S\S_S]S_S^S_E0 S_S_S`S_SaS_SbS_ScS_SdS_SeS_SfS_SgS_ShS_SiS_SjS_SkS_SlS_SmS_SnS_SoS_E0 SpS_SqS_SrS_SsS_StS_SuS_SvS_SwS_SxS_SyS_SzS_S{S_S|S_S}S_S~S_SS_SS_ESSSSSSSSSS.	E_S0 S/ SQ/ SQ/ SQSS// SQS.0S/ SQ0S/ SQ0S.S._SSSSSSSSSSSSSSSSS._S[        _SSSS._SSSSU R                  S5      U R                  S5      U R                  S5      U R                  S5      /U R                  S5      U R                  S5      /U R                  S5      U R                  S5      /U R                  S5      U R                  S5      /U R                  S5      U R                  S5      /U R                  S5      U R                  S5      /U R                  S5      U R                  S5      /U R                  S5      U R                  S5      //U R                  S5      U R                  S5      /U R                  S5      U R                  S5      /U R                  S5      U R                  S5      /U R                  S5      U R                  S5      /U R                  S5      U R                  S5      /U R                  S5      U R                  S5      /U R                  S5      U R                  S5      /U R                  S5      U R                  S5      //S.S.0_SSS0_SS/ SQSSS._SSSSS SSSSSSS.SS.SSSSS.SSSSSSSS.S SSSSSS.SSSSS.SSSSSS.SSSSSSSS.SSSS SSSSS.SS0S.	S S S.S S S.S._S[        [        [        [        [        [        S.[        [        S.S._5      $ )Nidr#   nameAlpaca	countriesUS	rateLimitiM  hostnamezalpaca.marketsproTurlszOhttps://github.com/user-attachments/assets/e9476df8-a450-4c3e-ab9a-1a7794219e1bz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://alpaca.markets/docs/z,https://docs.alpaca.markets/docs/crypto-fees)logowwwapitestdocfeeshasCORSFspotmarginswapfutureoption	addMarginborrowCrossMarginborrowIsolatedMarginborrowMargincancelAllOrderscancelOrdercloseAllPositionsclosePositioncreateMarketBuyOrdercreateMarketBuyOrderWithCostcreateMarketOrderWithCostcreateOrder$createOrderWithTakeProfitAndStopLoss&createOrderWithTakeProfitAndStopLossWscreateReduceOnlyOrdercreateStopOrdercreateTriggerOrder	editOrderfetchBalancefetchBidsAsksfetchBorrowInterestfetchBorrowRatefetchBorrowRateHistoriesfetchBorrowRateHistoryfetchBorrowRatesfetchBorrowRatesPerSymbolfetchClosedOrdersfetchCrossBorrowRatefetchCrossBorrowRatesfetchCurrenciesfetchDepositAddressfetchDepositAddressesByNetworkfetchDepositsfetchDepositsWithdrawalsfetchFundingHistoryfetchFundingIntervalfetchFundingIntervalsfetchFundingRatefetchFundingRateHistoryfetchFundingRatesfetchGreeksfetchIndexOHLCVfetchIsolatedBorrowRatefetchIsolatedBorrowRatesfetchIsolatedPositionsfetchL1OrderBookfetchL2OrderBookfetchLeveragefetchLeveragesfetchLeverageTiersfetchLiquidationsfetchLongShortRatiofetchLongShortRatioHistoryfetchMarginAdjustmentHistoryfetchMarginModefetchMarginModesfetchMarketLeverageTiersfetchMarketsfetchMarkOHLCVfetchMarkPricesfetchMyLiquidationsfetchMySettlementHistoryfetchMyTrades
fetchOHLCVfetchOpenInterestfetchOpenInterestHistoryfetchOpenInterestsfetchOpenOrderfetchOpenOrdersfetchOptionfetchOptionChain
fetchOrderfetchOrderBookfetchOrdersfetchPositionfetchPositionHistoryfetchPositionModefetchPositionsfetchPositionsForSymbolfetchPositionsHistoryfetchPositionsRiskfetchPremiumIndexOHLCVfetchSettlementHistoryfetchStatusfetchTickerfetchTickers	fetchTimefetchTradesfetchTradingFeefetchTradingFeesfetchTransactionFeesfetchTransactionsfetchTransfersfetchVolatilityHistoryfetchWithdrawalsreduceMargin)	repayCrossMarginrepayIsolatedMarginsandboxsetLeverage	setMarginsetMarginModesetPositionModetransferwithdrawr5   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/announcementsz
v2/walletsv2/wallets/transfers)r   r   r   r   r   )r   r   r   r   r   )r   r   r   r   r   r   z%v2/watchlists/{watchlist_id}/{symbol})getpostputpatchdeleter   )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secretr8   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features)lastmarkindex)triggerPriceTypeprice)IOCFOKPOGTD)
marginModetriggerPricer   triggerDirectionstopLossPricetakeProfitPriceattachedStopLossTakeProfittimeInForcehedgedtrailingleveragemarketBuyRequiresPricemarketBuyByCostselfTradePreventionicebergd   i )r   limitdaysBack	untilDayssymbolRequired)r   triggerr  r  i  )r   r  r  r  r  )r   r  r  r  r  r  r  )r   r  r  daysBackCanceledr  r  r  r  r    )	r   rK   createOrdersr~   r   r   r   rZ   r   )linearinverse)r;   r=   r>   
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    S/home/james-whalen/.local/lib/python3.13/site-packages/ccxt/async_support/alpaca.pyr"  alpaca.describe   sC   fd < > RA
(RA
HRA
 $RA
 RA
 (RA
 4RA
 i/=67 F<7
 6FRA
4  ppp %p 	p
 %p %p Up $Up 'p p "4p tp $Up  p 'p  /!p" ,T#p$ t%p& 7'p( 9%)p* (+p, "4-p. %d/p0 T1p2 3p4  5p6 &u7p8 "59p: +E;p< )%=p> #E?p@ ,UApB $TCpD 'EpF (GpH "5IpJ &tKpL 1%MpN  OpP +DQpR &uSpT 'UpV (WpX #EYpZ *5[p\ $U]p^ u_p` "5apb *5cpd +Eepf )%gph #Dipj #Ekpl  mpn !%opp %eqpr $Uspt &uupv -ewpx /ypz "5{p| #E}p~ +Ep@ ApB !%CpD "5EpF &uGpH +EIpJ  KpL dMpN $UOpP +EQpR %eSpT !%UpV "4WpX uYpZ #E[p\ d]p^ !$_p` tapb  cpd 'epf $Ugph !%ipj *5kpl (mpn %eopp )%qpr )%spt uupv twpx ypz T{p| t}p~ "5p@ #EApB 'CpD $UEpF !%GpH )%IpJ #DKpL MpN %*',$"!&#(! _p5RA
V   ,!  37"#O0 2j  	     *maWRA
Z [RA
| Y}RA
~ "$RA
F !%"&!..x8!..x8 "..s3T5F5Fx5PQ!..x8$:K:KH:UV!..x8$:K:KH:UV!..y94;L;LX;VW!..z:D<M<Mh<WX!..z:D<M<Mh<WX!..z:D<M<Mh<WX!..{;T=N=Nw=WX	" "..s3T5F5Fx5PQ!..x8$:K:KH:UV!..x8$:K:KG:TU!..y94;L;LX;VW!..z:D<M<Mh<WX!..z:D<M<Mh<WX!..z:D<M<Mh<WX!..{;T=N=Nv=VW	"GRA
B	 !6C	RA
H	 #) ',!,
I	RA
^	 #&+(,,0,1).+0 )-(,)-1
 &*7 $(#'"&#(	( #($($)27+0/4#(7$: %)&+!$$*%+*/& ',#($)*/	# ',!$#($)*/( ',!$$*%+#($)*/$ ',!$$*,0%+#($)*/	*  #OJX ##
 ##aT_	RA
H "2 , * 0 1 1 5?&/IRA
 R R	    c                   #    U R                  U5      I Sh  vN nU R                  US5      nUSS n[        U5      S-
  n[        U5      S-
  nX5U nU R                  U5      U R	                  U5      S-  S-  -
  nU$  Nf7f)	z
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   r$         i  r  )traderPrivateGetV2Clocksafe_stringlen	parse8601parse_to_numeric)	r$  paramsresponser*  	localTimejetlagStrStartjetlagStrEndjetlagisos	            r&  
fetch_timealpaca.fetch_time  s      55f== $$X{;	aO	Y!+9~),7nnY'$*?*?*G$*NQU*UU
 >s   B A>A'B c                    #    SSS.nU R                  U R                  X!5      5      I Sh  vN nU R                  U5      $  N7f)z
retrieves data on all markets for alpaca

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$  r2  requestassetss       r&  fetch_marketsalpaca.fetch_markets  sK      $
 44T[[5QRR. !!&))/ Ss   )AAAc                 d   U R                  US5      nUR                  S5      nU R                  US5      nU R                  US5      nU R                  US5      nU R                  U5      nU R                  U5      nUc  US:X  a  SnUS-   U-   n	U R                  US5      n
U
S	:H  nU R                  US
5      nU R                  US5      nU R                  US5      n0 SU_SU	_SU_SU_SS _SU_SU_SS _SS_SS_SS _SS_SS_SS_S	U_SS_SS _S S S S S S UUS.S S S.US S.S S S.S S S.S .S US!.
E$ )"Nsymbol/classr      	us_equityUSDr?  r=  min_order_sizemin_trade_incrementprice_incrementr'   basequotesettlebaseIdquoteIdsettleIdtyper;   Tr<   r=   Fr>   r?   contractr  )amountr   )minmax)r  rY  r   cost)
r  contractSizeexpiryexpiryDatetimestrike
optionType	precisionlimitscreatedinfo)r.  splitsafe_currency_codesafe_number)r$  assetmarketIdparts
assetClassrT  rU  rQ  rR  rH  r?  r=  	minAmountrY  r   s                  r&  parse_marketalpaca.parse_market  s(   * ##E84s#%%eW5
!!%+""5!,&&v.''0 =Z;6Ee#!!%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	
r(  NrH  sincer  c                   #    U R                  5       I Sh  vN   U R                  U5      nUS   nU R                  USS5      nU R                  USS5      nUUS.n	U R                  USS/5      nSn
US:X  al  Ub  U R	                  U5      U	S'   Ub  X9S	'   U R                  U R                  X5      5      I Sh  vN nU R                  US
0 5      nU R                  X/ 5      n
OuUS:X  aQ  U R                  U R                  X5      5      I Sh  vN nU R                  US
0 5      nU R                  X0 5      n
U
/n
O[        U R                  S-   U-   S-   5      eU R                  XX#5      $  GNU N Nb7f)a  
get the list of most recent trades for a particular symbol

https://docs.alpaca.markets/reference/cryptotrades
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symbolsrr  startr  trades+marketPublicGetV1beta3CryptoLocLatestTradesz  fetchTrades() does not support ze, marketPublicGetV1beta3CryptoLocTrades and marketPublicGetV1beta3CryptoLocLatestTrades are supported)load_marketsr2   r.  omitiso8601ru  rA  	safe_dict	safe_listrz  r   r'   parse_trades)r$  rH  rp  r  r2  r2   rj  rr  rt  rC  symbolTradesr3  ry  s                r&  fetch_tradesalpaca.fetch_tradesC  s     !!!V$$<vud3!!&(4[\
 6E8#45<< #'<<#6  #( !GGT[HdeeH" ^^Hh;F>>&B?LDD!MMdkkZaNjkkH ^^Hh;F>>&B?L(>Ltww)KKfT  X     @  @  uDDo 	"  f( ls6   E2E+B"E29E.:AE2E0AE2.E20E2c           	        #    U R                  5       I Sh  vN   U R                  U5      nUS   nU R                  USS5      nUUS.nU R                  U R	                  Xs5      5      I Sh  vN nU R                  US0 5      n	U R                  X0 5      n
U R                  U R                  U
S5      5      nU R                  XS   US	S
SS5      $  N Ne7f)aE  
fetches information on open orders with bid(buy) and ask(sell) prices, volumes and other data

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'   rr  rs  rv  
orderbookstrH  baps)r{  r2   r.  /marketPublicGetV1beta3CryptoLocLatestOrderbooksrA  r~  r0  parse_order_book)r$  rH  r  r2  r2   r'   rr  rC  r3  r  rawOrderbookr*  s               r&  fetch_order_bookalpaca.fetch_order_book  s      !!!V$D\vud3
 MMdkkZaNjkkL ^^HlB?
~~jb9NN4#3#3L##FG	$$\(3CYPSUXZ]_bccc 	" ls#   CCAC,C-A$CCr   	timeframec                 (  #    U R                  5       I Sh  vN   U R                  U5      nUS   nU R                  USS5      nU R                  USS5      n	UUS.n
U R                  USS/5      nSnU	S:X  a  Ub  XJS'   Ub  U R	                  U5      U
S	'   U R                  U R
                  X"5      U
S
'   U R                  U R                  X5      5      I Sh  vN nU R                  US0 5      nU R                  X/ 5      nOuU	S:X  aQ  U R                  U R                  X5      5      I Sh  vN nU R                  US0 5      nU R                  X0 5      nU/nO[        U R                  S-   U	-   S-   5      eU R                  XX#U5      $  GNu N Nc7f)a  
fetches historical candlestick data containing the open, high, low, and close price, and the volume of a market

https://docs.alpaca.markets/reference/cryptobars
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'   rr  rs  rt  #marketPublicGetV1beta3CryptoLocBarsrv  r  rx  r  bars)marketPublicGetV1beta3CryptoLocLatestBarsz fetchOHLCV() does not support za, marketPublicGetV1beta3CryptoLocBars and marketPublicGetV1beta3CryptoLocLatestBars are supported)r{  r2   r.  r|  yyyymmddr   r  rA  r~  r  r  r   r'   parse_ohlcvs)r$  rH  r  rp  r  r2  r2   rj  rr  rt  rC  ohlcvsr3  r  s                 r&  fetch_ohlcvalpaca.fetch_ohlcv  s      !!!V$$<vud3!!&(4YZ
 6E8#45:: #(  #'==#7 #'#3#3DOOY#ZGK !EEdkkRYFbccH< >>(FB7D^^DB7FBB!KKDKKX_LhiiH" >>(FB7D^^DB7FXFtww)JJVS  Wz   z  {  {  5IIQ 	"" dB js6   FFCFFAF,F-AFFFr2   c           	          U R                  US5      nU R                  U5      nUU R                  US5      U R                  US5      U R                  US5      U R                  US5      U R                  US5      /$ )Nr  ohlcv)r.  r0  rh  )r$  ohlcvr2   datetimer*  s        r&  parse_ohlcvalpaca.parse_ohlcv$  s     ##E3/NN8,	UC(UC(UC(UC(UC(
 	
r(  c                    #    U R                  5       I Sh  vN   U R                  U5      nU R                  U/U5      I Sh  vN nU R                  X15      $  NA N7f)a  
fetches a price ticker, a statistical calculation with the information calculated over the past 24 hours for a specific market

https://docs.alpaca.markets/reference/cryptosnapshots-1

:param str symbol: unified symbol of the market to fetch the ticker for
:param dict [params]: extra parameters specific to the exchange API endpoint
:param str [params.loc]: crypto location, default: us
:returns dict: a `ticker structure <https://docs.ccxt.com/#/?id=ticker-structure>`
N)r{  rH  fetch_tickersr~  )r$  rH  r2  tickerss       r&  fetch_tickeralpaca.fetch_ticker<  sU      !!!V$**F8V<<~~g.. 	"<s!   AA+AAAArw  c           
        #    Uc  [        U R                  S-   5      eU R                  5       I Sh  vN   U R                  U5      nU R	                  USS5      nU R                  U5      nSR                  U5      US.nU R                  US5      nU R                  U R                  XR5      5      I Sh  vN n/ nU R                  US0 5      n[        UR                  5       5      n	[        S[        U	5      5       GH  n
X   nU R                  U5      nU R                  X5      nU R                  US	0 5      nU R                  US
0 5      nU R                  US0 5      nU R                  US0 5      nU R	                  US5      nU R!                  0 SU_SUS   _SU R#                  U5      _SU_SU R	                  US5      _SU R	                  US5      _SU R	                  US5      _SU R	                  US5      _SU R	                  US5      _SU R	                  US5      _SU R	                  US5      _S U R	                  US!5      _S"U R	                  US#5      _S$U R	                  US%5      _S&U R	                  US#5      _S'S_S(S_SU R	                  US)5      U R	                  US*5      S+.EU5      nUR%                  U5        GM     U R'                  USU5      $  GN GN)7f),a  
fetches price tickers for multiple markets, statistical information calculated over the past 24 hours for each market

https://docs.alpaca.markets/reference/cryptosnapshots-1

:param str[] symbols: unified symbols of the markets to fetch tickers for
:param dict [params]: extra parameters specific to the exchange API endpoint
:param str [params.loc]: crypto location, default: us
:returns dict: a dictionary of `ticker structures <https://docs.ccxt.com/#/?id=ticker-structure>`
Nz+ fetchTickers() requires a symbols argumentrr  rs  ,rv  	snapshotsr   dailyBarprevDailyBarlatestQuotelatestTrader  re  rH  r*  r  highr  lowr  bidbp	bidVolumebsaskap	askVolumeasvwapvwopenr  closer  r   r  previousClosechanger   r  n)average
baseVolumequoteVolume)r   r'   r{  market_symbolsr.  
market_idsjoinr|  (marketPublicGetV1beta3CryptoLocSnapshotsrA  r~  listkeysranger/  safe_marketsafe_tickerr0  appendfilter_by_array)r$  rw  r2  rr  idsrC  r3  resultsr  	marketIdsirj  r2   entryr  r  r  r  r  tickers                       r&  r  alpaca.fetch_tickersL  sC     ?#DGG.[$[\\!!!%%g.vud3oog&xx}
 65)FFt{{SZGcddj NN8["=	)*	q#i.)A |H%%h/FNN97E~~eZ<H>>%DL..rBK..rBK''S9H%% ''&*' T^^H5' H	'
 ((37' t''#6' t''T:' T--k4@' t''T:' T--k4@' ((48' ((37' ))(C8' ((c:'  !1!1,!D'  $!'" d#'$  "..x=#//#>)'* +F, NN6"? *@ ##GXw??C 	" es#   /K KBK 4K5H&K K c                     U R                  U R                  S5      nU R                  5       nUR                  S5      nSR	                  U5      nU R                  USU05      nU R                  USU5      nU$ )Nr   - r'   )r.  r   uuidrf  r  implode_params)r$  r2  clientOrderIdprefixr  rk  	random_iddefaultClientIdr   s           r&  generate_client_order_idalpaca.generate_client_order_id  sp    "..t||_Myy{

3GGEN	--.AD)CTU((/Rr(  sider\  c                    #    U R                  5       I Sh  vN   SU0nU R                  USUSSU R                  XT5      5      I Sh  vN $  N5 N7f)a  
create a market order by providing the symbol, side and cost

https://docs.alpaca.markets/reference/postorder

:param str symbol: unified symbol of the market to create an order in
:param str side: 'buy' or 'sell'
:param float cost: how much you want to trade in units of the quote currency
:param dict [params]: extra parameters specific to the exchange API endpoint
:returns dict: an `order structure <https://docs.ccxt.com/#/?id=order-structure>`
Nr\  r2   r   r{  create_orderrA  )r$  rH  r  r\  r2  reqs         r&  create_market_order_with_cost$alpaca.create_market_order_with_cost  sZ      !!!D
 &&vxq$TWH`aaa	 	" b!   AA0AAAAc                    #    U R                  5       I Sh  vN   SU0nU R                  USSSSU R                  XC5      5      I Sh  vN $  N5 N7f)a  
create a market buy order by providing the symbol and cost

https://docs.alpaca.markets/reference/postorder

:param str symbol: unified symbol of the market to create an order in
:param float cost: how much you want to trade in units of the quote currency
:param dict [params]: extra parameters specific to the exchange API endpoint
:returns dict: an `order structure <https://docs.ccxt.com/#/?id=order-structure>`
Nr\  r2   buyr   r  r$  rH  r\  r2  r  s        r&  !create_market_buy_order_with_cost(alpaca.create_market_buy_order_with_cost  sZ      !!!D
 &&vx4UXIabbb	 	" cr  c                    #    U R                  5       I Sh  vN   SU0nU R                  USSUSU R                  XC5      5      I Sh  vN $  N5 N7f)a  
create a market sell order by providing the symbol and cost

https://docs.alpaca.markets/reference/postorder

:param str symbol: unified symbol of the market to create an order in
:param float cost: how much you want to trade in units of the quote currency
:param dict [params]: extra parameters specific to the exchange API endpoint
:returns dict: an `order structure <https://docs.ccxt.com/#/?id=order-structure>`
Nr\  r2   sellr  r  s        r&  "create_market_sell_order_with_cost)alpaca.create_market_sell_order_with_cost  sZ      !!!D
 &&vxtT[[Y\Mefff	 	" gr  rW  rY  r   c                   #    U R                  5       I Sh  vN   U R                  U5      nUS   nUUUS.n	U R                  USS/5      n
U
bN  UR                  S5      S:  a  SnO[	        U R
                  S	-   U-   S
-   5      eU R                  X5      U	S'   XS'   UR                  S5      S:  a  U R                  X5      U	S'   U R                  US5      nUb'  U R                  US5      nU R                  X5      U	S'   OU R                  X5      U	S'   U R                  U R                  S5      nU R                  USU5      U	S'   U R                  USS/5      nU R                  U5      U	S'   U R                  US/5      nU R                  U R                  X5      5      I Sh  vN nU R                  X5      $  GN N7f)a  
create a trade order

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 fulfilled, 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
:param float [params.cost]: *market orders only* the cost of the order in units of the quote currency
:returns dict: an `order structure <https://docs.ccxt.com/#/?id=order-structure>`
Nr'   )rH  r  rW  r   
stop_pricer  r   
stop_limitz0 createOrder() does not support stop orders for z- orders, only stop_limit orders are supportedrW  limit_pricer\  notionalqtyr   r  time_in_forceclient_order_idr   )r{  r2   safe_string_nfindr   r'   price_to_precisionr.  r|  cost_to_precisionamount_to_precisionr   r  traderPrivatePostV2OrdersrA  parse_order)r$  rH  rW  r  rY  r   r2  r2   r'   rC  r   newTyper\  
defaultTIForders                  r&  r  alpaca.create_order  s      !!!V$D\

 ))&><2PQ#yy!Q&&"477-_#_bf#f  jY  $Y  Z  Z$($;$;F$QGL!%FO99W"%)%<%<V%KGM"/YYvv.F"&"8"8"FGJ!55fEGEN%%dll4HI
#'#3#3FM:#V 6M>#BC%)%B%B6%J!"6O#4544T[[5QRRJ ..G 	"< Ss"   G F;FG %F>&G >G r'   c                    #    SU0nU R                  U R                  XC5      5      I Sh  vN nU R                  U5      $  N7f)aQ  
cancels an open order

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)"traderPrivateDeleteV2OrdersOrderIdrA  r  )r$  r'   rH  r2  rC  r3  s         r&  cancel_orderalpaca.cancel_orderN  sJ      
 @@WA]^^ )) _s   (AA Ac                    #    U R                  5       I Sh  vN   U R                  U5      I Sh  vN n[        U[        5      (       a  U R	                  US5      $ U R                  SU05      /$  NX NA7f)ae  
cancel all open orders in a market

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>`
Nre  )r{  traderPrivateDeleteV2Orders
isinstancer  parse_orders
safe_order)r$  rH  r2  r3  s       r&  cancel_all_ordersalpaca.cancel_all_orderse  sv      !!!99&AAh%%$$Xt44 H!   	"As    A3A/A3A1A A31A3c                   #    U R                  5       I Sh  vN   SU0nU R                  U R                  XC5      5      I Sh  vN nU R                  US5      nU R	                  U5      nU R                  XW5      $  Nd N:7f)am  
fetches information on an order made by the user

https://docs.alpaca.markets/reference/getorderbyorderid

:param str id: the 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>`
Nr  rH  )r{  traderPrivateGetV2OrdersOrderIdrA  r.  r  r  )r$  r'   rH  r2  rC  r  rj  r2   s           r&  fetch_orderalpaca.fetch_orderz  s      !!!
 ::4;;w;WXX##E84!!(+.. 	" Ys!   A?A;+A?A=9A?=A?c                   #    U R                  5       I Sh  vN   SS0nSnUb  U R                  U5      nUS   US'   U R                  US5      nUb&  U R                  US5      nU R	                  U5      US'   Ub  U R	                  U5      US'   Ub  X5S	'   U R                  U R                  XT5      5      I Sh  vN nU R                  XX#5      $  N N7f)
a/  
fetches information on multiple orders made by the user

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'   rw  untilendTimeafterr  )r{  r2   safe_integerr|  r}  traderPrivateGetV2OrdersrA  r  )	r$  rH  rp  r  r2  rC  r2   r  r3  s	            r&  fetch_ordersalpaca.fetch_orders  s      !!!e
 [[(F!'GI!!&'2YYvw/F!%e!4GI#||E2GG$G66t{{77STTR   5@@s 	"  Us"   CCB"C9C:CCc           	      h   #    SS0nU R                  XX0R                  XT5      5      I Sh  vN $  N7f)a   
fetch all unfilled currently open orders

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?  r  Nr  rA  r$  rH  rp  r  r2  rC  s         r&  fetch_open_ordersalpaca.fetch_open_orders  s7      f
 &&ve[[=YZZZZ   )202c           	      h   #    SS0nU R                  XX0R                  XT5      5      I Sh  vN $  N7f)a6  
fetches information on multiple closed orders made by the user

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?  closedNr  r  s         r&  fetch_closed_ordersalpaca.fetch_closed_orders  s7      h
 &&ve[[=YZZZZr"  c                 L  #    U R                  5       I Sh  vN   SU0nSn	Ub  U R                  U5      n	Ub  U R                  X%5      US'   U R                  USS/5      n
U
b&  U R	                  X*5      US'   U R                  US5      nUb  U R	                  X&5      US'   SnU R                  USSS	5      u  pUb  XS
'   U R                  U5      US'   U R                  US/5      nU R                  U R                  X5      5      I Sh  vN nU R                  X5      $  GN	 N7f)au  
edit a trade order

https://docs.alpaca.markets/reference/patchorderbyorderid-1

:param str id: order id
: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 the currency you want to trade in units of the base currency
:param float [price]: the price for the order, in units of the quote currency, ignored in market orders
:param dict [params]: extra parameters specific to the exchange API endpoint
:param str [params.triggerPrice]: the price to trigger a stop order
:param str [params.timeInForce]: for crypto trading either 'gtc' or 'ioc' can be used
:param str [params.clientOrderId]: a unique identifier for the order, automatically generated if not sent
:returns dict: an `order structure <https://docs.ccxt.com/#/?id=order-structure>`
Nr  r  r   r  r  rQ   r  r   r  r  r   )r{  r2   r  r  r  r|  handle_option_and_params_2r  !traderPrivatePatchV2OrdersOrderIdrA  r  )r$  r'   rH  rW  r  rY  r   r2  rC  r2   r   r  r3  s                r&  
edit_orderalpaca.edit_order  sF    $ !!!
 [[(F!55fEGEN))&><2PQ#$($;$;F$QGL!YYv~6F%)%<%<V%KGM""==fkS`bvw"'2O$%)%B%B6%J!"6O#45??G@\]]11- 	"* ^s"   D$DC2D$	D"
D$"D$r  c           
      D   U R                  US5      nU R                  X25      nUS   nU R                  US5      nU R                  U5      nU R                  US5      nS nUb  USS.nU R                  US5      n	U	b  U	R                  S5      S:  a  Sn	U R                  US	5      n
U R	                  U
5      nU R                  0 S
U R                  US
5      _SU R                  US5      _SU_SU
_SS _SU_SU_SU	_SU R                  U R                  US5      5      _SS _SU R                  US5      _SU R                  US5      _SU R                  US5      _SS _SU R                  US5      _SU R                  US5      _SU R                  US5      _S S UUS .EU5      $ )!NrH  r?  
commissionrM  r\  currency
order_typer  r   submitted_atr'   r   r  r*  r  lastTradeTimeStamprW  r  r  postOnlyr  r   r  r   r  r\  r  filled_avg_pricerY  r  filled
filled_qty)	remainingry  feere  )r.  r  parse_order_statusr  r0  r  parse_time_in_forcerh  )r$  r  r2   rj  rH  alpacaStatusr?  feeValuer8  	orderTyper  r*  s               r&  r  alpaca.parse_order$  sE   N ##E84!!(3!''x8((6##E<8 !C $$UL9	 ~~g&!+#	##E>:NN8,	  
$""5$/ 
T--e5FG 
  
 	 

 !$ 
 f 
 f 
 I 
 433D4D4DUO4\] 
  
 D$$UF3 
 T%%e]; 
 D,,ULA 
 D 
 t''/AB 
  d&&ue4! 
" d&&ul;# 
$ + 
, - 	r(  r?  c                 8    SSSSSSS.nU R                  X!U5      $ )Nr  r$  )pending_newacceptednewpartially_filled	activatedr5  r.  r$  r?  statusess      r&  r9  alpaca.parse_order_statusv  s0    ! &
 &99r(  r  c                 .    SS0nU R                  X!U5      $ )NdayDayrE  )r$  r  timeInForcess      r&  r:  alpaca.parse_time_in_force  s#    5
 ;GGr(  c                   #    U R                  5       I Sh  vN   SnSS0nUb  U R                  U5      nU R                  US5      nUb&  U R                  US5      nU R	                  U5      US'   Ub  U R	                  U5      US'   Ub  X6S'   U R                  SXd5      u  pdU R                  U R                  Xd5      5      I Sh  vN nU R                  XX#5      $  N N7f)aN  
fetch all trades made by the user

https://docs.alpaca.markets/reference/getaccountactivitiesbyactivitytype-1

:param str [symbol]: unified market symbol
: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 int [params.until]: the latest time in ms to fetch trades for
:param str [params.page_token]: page_token - used for paging
:returns Trade[]: a list of `trade structures <https://docs.ccxt.com/#/?id=trade-structure>`
Nactivity_typeFILLr  r  	page_size)	r{  r2   r  r|  r}  handle_until_option/traderPrivateGetV2AccountActivitiesActivityTyperA  r  )	r$  rH  rp  r  r2  r2   rC  r  r3  s	            r&  fetch_my_tradesalpaca.fetch_my_trades  s      !!!V
 [[(F!!&'2YYvw/F#||E2GG#||E2GG#(K 227GLMMdkkZaNjkk(   5@@I 	"  ls"   C CB.C CC C tradec                    U R                  USS5      nU R                  X25      nU R                  USS5      nU R                  U5      nU R                  US5      nU R                  US5      nUS:X  a  SnOUS:X  a  S	nU R                  US
S5      n	U R                  USS5      n
U R	                  UU R                  USS5      UU R                  U5      UU R                  US5      S USU	U
S S S.U5      $ )NSrH  r  transaction_timetksr  Br  r  r  r   r  r  r  r'   r  r   )re  r'   r*  r  rH  r  rW  r  takerOrMakerr   rY  r\  r8  )safe_string_2safe_symbolr0  r.  
safe_trader}  )r$  rV  r2   rj  rH  r  r*  
alpacaSider  priceStringamountStrings              r&  parse_tradealpaca.parse_trade  s   > %%eS(;!!(3%%eS2DENN8,	%%eU3
v.D3D((W=))%e<$$UC6"Y/%%eZ8# " 
  	r(  codec                    #    U R                  5       I Sh  vN   U R                  U5      nSUS   0nU R                  U R                  XB5      5      I Sh  vN nU R	                  XS5      $  NU N7f)aR  
fetch the deposit address for a currency associated with self account

https://docs.alpaca.markets/reference/listcryptofundingwallets

:param str code: unified currency code
:param dict [params]: extra parameters specific to the exchange API endpoint
:returns dict: an `address structure <https://docs.ccxt.com/#/?id=address-structure>`
Nri  r'   )r{  r/  traderPrivateGetV2WalletsrA  parse_deposit_address)r$  re  r2  r/  rC  r3  s         r&  fetch_deposit_addressalpaca.fetch_deposit_address  ss      !!!==&Xd^
 77G8TUU ))(== 	"
 Vs!   A0A,?A0A.A0.A0r/  c                 F    S nUb  US   nUUS U R                  US5      S S.$ )Nr'   address)re  r/  networkrl  tagrE  )r$  depositAddressr/  parsedCurrencys       r&  rh  alpaca.parse_deposit_address  s>     %d^N"&''	B
 	
r(  rl  rn  c                 l  #    U R                  XE5      u  pEU R                  U5        U R                  5       I Sh  vN   U R                  U5      nU(       a  US-   U-   nUS   UU R	                  U5      S.nU R                  U R                  Xu5      5      I Sh  vN nU R                  X5      $  Nu N7f)a  
make a withdrawal

https://docs.alpaca.markets/reference/createcryptotransferforaccount

:param str code: unified currency code
:param float amount: the amount to withdraw
:param str address: the address to withdraw to
:param str tag: a memo for the transaction
:param dict [params]: extra parameters specific to the exchange API endpoint
:returns dict: a `transaction structure <https://docs.ccxt.com/#/?id=transaction-structure>`
N:r'   )ri  rl  rY  )handle_withdraw_tag_and_paramscheck_addressr{  r/  number_to_string#traderPrivatePostV2WalletsTransfersrA  parse_transaction)	r$  re  rY  rl  rn  r2  r/  rC  r3  s	            r&  r   alpaca.withdraw"  s      99#F7#!!!==&mc)Gd^++F3

 AA$++gB^__$ %%h997 	" `s"   8B4B0AB4B2B42B4c                   #    U R                  5       I S h  vN   S nUb  U R                  U5      nU R                  U5      I S h  vN n/ n[        S[	        U5      5       HJ  n	Xy   n
U R                  U
S5      nX:X  a  UR                  U
5        M1  US:X  d  M9  UR                  U
5        ML     U R                  XX4U5      $  N N~7f)Nr   	directionBOTH)r{  r/  "traderPrivateGetV2WalletsTransfersr  r/  r.  r  parse_transactions)r$  rW  re  rp  r  r2  r/  r3  r  r  r  r{  s               r&  fetch_transactions_helper alpaca.fetch_transactions_helperN  s     !!!}}T*H@@HH$ q#h-(AKE((<I u%u% ) &&w%OO= 	" Is(   CC.CCAC)CCc                 D   #    U R                  SXX45      I Sh  vN $  N7f)a/  
fetch history of deposits and withdrawals

https://docs.alpaca.markets/reference/listcryptofundingtransfers

:param str [code]: unified currency code for the currency of the deposit/withdrawals, default is None
:param int [since]: timestamp in ms of the earliest deposit/withdrawal, default is None
:param int [limit]: max number of deposit/withdrawals to return, default is None
:param dict [params]: extra parameters specific to the exchange API endpoint
:returns dict: a list of `transaction structure <https://docs.ccxt.com/#/?id=transaction-structure>`
r|  Nr  r$  re  rp  r  r2  s        r&  fetch_deposits_withdrawals!alpaca.fetch_deposits_withdrawalso  s"      33FDWWWW     c                 D   #    U R                  SXX45      I Sh  vN $  N7f)a  
fetch all deposits made to an account

https://docs.alpaca.markets/reference/listcryptofundingtransfers

:param str [code]: unified currency code
:param int [since]: the earliest time in ms to fetch deposits for
:param int [limit]: the maximum number of deposit structures to retrieve
:param dict [params]: extra parameters specific to the exchange API endpoint
:returns dict[]: a list of `transaction structures <https://docs.ccxt.com/#/?id=transaction-structure>`
INCOMINGNr  r  s        r&  fetch_depositsalpaca.fetch_deposits}  "      33JU[[[[r  c                 D   #    U R                  SXX45      I Sh  vN $  N7f)a  
fetch all withdrawals made from an account

https://docs.alpaca.markets/reference/listcryptofundingtransfers

:param str [code]: unified currency code
:param int [since]: the earliest time in ms to fetch withdrawals for
:param int [limit]: the maximum number of withdrawal structures to retrieve
:param dict [params]: extra parameters specific to the exchange API endpoint
:returns dict[]: a list of `transaction structures <https://docs.ccxt.com/#/?id=transaction-structure>`
OUTGOINGNr  r  s        r&  fetch_withdrawalsalpaca.fetch_withdrawals  r  r  transactionc                    U R                  US5      nU R                  US5      nU R                  XB5      nU R                  US5      nU R                  US5      n[        R                  " Xg5      nU R	                  U5      US.n	0 SU_SU R                  US5      _SU R                  US	5      _S
U R                  U5      _SU_SU R                  US5      _SU R                  US5      _SU R                  US5      _SU R                  US5      _SS _SS _SS _SU R                  U R                  US5      5      _SU R                  US5      _SU_SU R                  U R                  US5      5      _SS _U	S S S.E$ )N
created_atri  r8   network_feer.  re  r'   txidtx_hashr*  r  rm  chainrl  
to_address	addressToaddressFromfrom_addressrn  tagTotagFromrW  r{  rY  r/  r?  updated)r8  commentinternal)	r.  rg  r!   
string_addr#  r0  parse_transaction_typerh  parse_transaction_status)
r$  r  r/  r  
currencyIdre  r8   
networkFeetotalFeer8  s
             r&  rx  alpaca.parse_transaction  s   $ ##K>%%k7;
&&z<V4%%k=A
%%d7%%h/

K
$"";5
 D$$[)<
 1	

 
 t''W=
 t''\B
 ))+|D
 4++KH
 4
 T
 t
 D//0@0@k0Z[
 d&&{H=
 
  d33D4D4D[RZ4[\!
" t#
$ )
 	
r(  c                 2    SSSS.nU R                  X!U5      $ )Npendingfailedok)
PROCESSINGFAILEDCOMPLETErE  rF  s      r&  r  alpaca.parse_transaction_status  s'    #

 &99r(  c                 0    SSS.nU R                  X!U5      $ )Ndeposit
withdrawal)r  r  rE  )r$  rW  typess      r&  r  alpaca.parse_transaction_type  s$    !$
 T22r(  c                    #    U R                  5       I Sh  vN   U R                  U5      I Sh  vN nU R                  U5      $  N. N7f)a6  
query for balance and get the amount of funds available for trading or funds locked in orders

https://docs.alpaca.markets/reference/getaccount-1

:param dict [params]: extra parameters specific to the exchange API endpoint
:returns dict: a `balance structure <https://docs.ccxt.com/#/?id=balance-structure>`
N)r{  traderPrivateGetV2Accountparse_balance)r$  r2  r3  s      r&  fetch_balancealpaca.fetch_balance  sI      !!!77??b !!(++e 	"?s   A	AA	AA	A	c                     SU0nU R                  5       nU R                  US5      nU R                  U5      nU R                  US5      US'   U R                  US5      US'   X2U'   U R                  U5      $ )Nre  r/  cashfreeequitytotal)accountr.  rg  safe_balance)r$  r3  resultr  r  re  s         r&  r  alpaca.parse_balance  s~    ),,.%%h
;
&&z2**8V<++Hh?t  ((r(  r   GETc                    SU R                  X5      -   nU R                  U R                  S   US      5      nUb  UO0 nUS   S:X  a.  U R                  5         U R                  US'   U R
                  US'   U R                  X@R                  U5      5      n	U	(       a:  US:X  d  US	:X  a  US
U R                  U	5      -   -  nOU R                  U	5      nSUS'   X-   nXXeS.$ )NrI  r5   r   rK  r   zAPCA-API-KEY-IDzAPCA-API-SECRET-KEYr  DELETE?zapplication/jsonzContent-Type)urlrt  bodyr   )
r  implode_hostnamer/   check_required_credentialsr   r   r|  extract_params	urlencodejson)
r$  pathr5   rt  r2  r   r  endpointr  querys
             r&  signalpaca.sign"  s    ,,T::##DIIe$4SV$<=%1'q6Y++-)-G%&-1[[G)*		&"5"5d";<%Vx%7C$.."777yy'*<'ndOOr(  reasonr  rt  r   r  c
                 V   Uc  g U R                   S-   U-   n
U R                  US5      nUb  U R                  U R                  S   X5        U R	                  USS 5      nUbI  U R                  U R                  S   X5        U R                  U R                  S   X5        [        U
5      eg )N re  r  messager  )r'   r.  throw_exactly_matched_exceptionr  
safe_valuethrow_broadly_matched_exceptionr   )r$  re  r  r  rt  r   r  r3  requestHeadersrequestBodyfeedback	errorCoder  s                r&  handle_errorsalpaca.handle_errors4  s    
 77S=4'$$Xv6	001I9_//(It<001I7]001I7]))r(   )N)F__name__
__module____qualname____firstlineno__r   r"  r	   r9  r   r
   rE  rn  strr   r  r   r  r  r  r  r   r  r   r   r  r  r   floatr  r  r  r   r   r  r   r  r  r  r   r  r   r%  r*  dictr  r9  r:  rT  rc  r   ri  r   rh  r   r   r  r  r  r  rx  r  r  r   r  r  r  intr  __static_attributes____classcell__)r%  s   @r&  r#   r#      se   S# Sj ') S . *, $*V $*LV
V V
p <@d[] FE FES FE FEbfglbm FEP @DB =dS =d =dS\ =d~ ?CQUdhqs XJ XJ XJ3 XJ^a XJx|  ~B  yC XJt
 
4 
0 68 / /F /  6:" n@7 n@ n@` eg b# bY bV[ b$ XZ cc c c" Y[ gs g% g" mqy{ S/ S/I S/Y S/X] S/fi S/j 9=R *S *# *. 59 c * 8<B /C / /( 04$UYbd FA FAC FAs FAimnsit FAP 59tZ^gi [c [ [TW [nrsxny [$ 7;\`ik [ [3 [VY [ptuzp{ [$ fjx|  FH (23 (2 (29 (2I (2_b (2ru (2TP Pv P Pd	: 	:Hs H 37TX\eg 2AC 2As 2ARU 2Ah9 9v 9 9v =? > >> >2
h 
R` 
& QU]_ *:3 *: *: *:# *:do *:XPB <@daenp XS X X[^ Xuy  {F  vG X 04$UYbd \ \C \s \imnyiz \ 37TX\eg \C \s \RU \lpq|l} \1
T 1
X 1
Q\ 1
f:s :3 *, ;, ;,z) ) &eBSW P$# s  c TX `c  r(  r#   N)' ccxt.async_support.base.exchanger   ccxt.abstract.alpacar   ccxt.base.typesr   r   r   r   r	   r
   r   r   r   r   r   r   r   r   r   r   r   typingr   ccxt.base.errorsr   r   r   r   r   r   r   r   r   ccxt.base.decimal_to_precisionr    ccxt.base.preciser!   r#   r  r(  r&  <module>r     s_    6 , q  q  q  q  q  * - . ' & . ) ) . 4 %mX{ mr(  