
    !:hI                       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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" d dl#m$Z$ d dl%m&Z&  G d dee      Z'y)    )Exchange)ImplicitAPI)AnyBalances
CurrenciesCurrency	IndexTypeIntLedgerEntryMarketNumOrder	OrderBook	OrderSide	OrderTypeStrStringsTickerTickersTrade)List)ExchangeError)PermissionDenied)ArgumentsRequired)
BadRequest)	BadSymbol)InsufficientFunds)InvalidOrder)OrderNotFound)RateLimitExceeded)	TICK_SIZE)Precisec                       e Zd Zdef fdZi fdefdZi fdee   fdZ	de
defdZd Zd Zd	d
d
i fdedededee   fdZdBdedefdZ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fdZdBde
dedefdZd
i fdededefdZdCd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dBde
dede fdZ!i fd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&dBd"e
d#e'de%fd$Z(d% Z)d& Z*d
i fded'e+d(e,d)e-d*e.f
d+Z/i fd,Z0d- Z1d
i fd.edefd/Z2d
i fded(e,fd0Z3d
d
d
i fdedededee4   fd1Z5d
d
d
i fdedededee4   fd2Z6d
i fd.edefd3Z7dBd4e
dede4fd5Z8d6 Z9i fd ed)e-fd7Z:dBd#e'fd8Z;d9d:i d
d
fd;Z<d e=d<ed=ed>ed?e
d@efdAZ> xZ?S )D	coinmetroreturnc                 v   | j                  t        t        |          i ddddddg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d$dd%dd&dd'dd(dd)dd*dd+dd,dd-dd.dd/dd0dd1di d2dd3dd4dd5dd6dd7dd8dd9dd:dd;dd<dd=dd>dd?dd@ddAddBdi dCddDddEddFddGddHddIddJddKddLddMddNddOddPddQddRddSdi dTddUddVddWddXddYddZdd[dd\dd]dd^dd_dd`ddaddbddcdddddddddddddddddddedfdgdhdidjdkdldmdndododpdqdqdpdrdsgdtdudvdwdxdydzdydzdydydzdyd{idydyd|dydyd|d|dyd}dydydydydydydydydydyd~
dydydydydddpdddddddddxdd| j	                  d      | j	                  d      didt
        dd dgddd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 dd ddddddddd dddddd dd ddddd ddid	d d dd d dddt        t        t        t        t        t        t        t        t        t        t        t        t        dt        t        t        t        t        t        t        t        t        t        t        t        t        t        t        dd      S )Nidr$   name	Coinmetro	countriesEEversionv1	rateLimit   	certifiedFprohasCORSspotTmarginswapfutureoption	addMarginborrowCrossMarginborrowIsolatedMargincancelAllOrderscancelOrdercancelOrderscloseAllPositionsclosePositioncreateDepositAddresscreateOrdercreatePostOnlyOrdercreateReduceOnlyOrdercreateStopLimitOrdercreateStopMarketOrdercreateStopOrderdeposit	editOrderfetchAccountsfetchBalancefetchBidsAsksfetchBorrowInterestfetchBorrowRateHistoriesfetchBorrowRateHistoryfetchCanceledAndClosedOrdersfetchCanceledOrdersfetchClosedOrderfetchClosedOrdersfetchCrossBorrowRatefetchCrossBorrowRatesfetchCurrenciesfetchDepositfetchDepositAddressfetchDepositAddressesfetchDepositAddressesByNetworkfetchDepositsfetchDepositsWithdrawalsfetchDepositWithdrawFeefetchDepositWithdrawFeesfetchFundingHistoryfetchFundingRatefetchFundingRateHistoryfetchFundingRatesfetchIndexOHLCVfetchIsolatedBorrowRatefetchIsolatedBorrowRatesfetchL3OrderBookfetchLedgerfetchLeveragefetchLeverageTiersfetchMarketLeverageTiersfetchMarketsfetchMarkOHLCVfetchMyTrades
fetchOHLCVfetchOpenInterestHistoryfetchOpenOrderfetchOpenOrders
fetchOrderfetchOrderBookfetchOrderBooksfetchOrdersfetchOrderTradesfetchPositionfetchPositionsfetchPositionsRiskfetchPremiumIndexOHLCVfetchStatusfetchTickerfetchTickers	fetchTimefetchTradesfetchTradingFeefetchTradingFeesfetchTradingLimitsfetchTransactionFeefetchTransactionFeesfetchTransactionsfetchTransfersfetchWithdrawal)fetchWithdrawalsfetchWithdrawalWhitelistreduceMarginrepayCrossMarginrepayIsolatedMarginsandboxsetLeverage	setMarginsetMarginModesetPositionModesignIntransferwithdrawws
timeframes6000030000018000001440000086400000)1m5m30m4h1durlszQhttps://github.com/ccxt/ccxt/assets/43336371/e86f87ec-6ba3-4410-962b-f7988c5db539zhttps://api.coinmetro.com)publicprivatehttps://api.coinmetro.com/openzhttps://coinmetro.com/z7https://documenter.getpostman.com/view/3653795/SVfWN6KSzZhttps://help.coinmetro.com/hc/en-gb/articles/6844007317789-What-are-the-fees-on-Coinmetro-z&https://go.coinmetro.com/?ref=crypto24)logoapitestwwwdocfeesreferralr   get      )z	demo/tempz/exchange/candles/{pair}/{timeframe}/{from}/{to}zexchange/priceszexchange/ticks/{pair}/{from}assetsmarketszexchange/book/{pair}z"exchange/bookUpdates/{pair}/{from}gQ?)zusers/balanceszusers/walletszusers/wallets/history/{since}z exchange/orders/status/{orderID}zexchange/orders/activezexchange/orders/history/{since}zexchange/fills/{since}zexchange/margin)
jwt	jwtDevicedeviceszjwt-read-onlyzexchange/orders/createz exchange/orders/modify/{orderID}zexchange/swapzexchange/swap/confirm/{swapId}zexchange/orders/close/{orderID}zexchange/orders/hedge)r   z exchange/orders/cancel/{orderID}zusers/margin/collateralzusers/margin/primary/{currency})r   postputrequiredCredentials)apiKeysecretuidtokenr   tradingz0.0010)feeSide	tierBased
percentagetakermakerprecisionModeoptionsQRDO)currenciesByIdForParseMarketcurrencyIdsListForParseMarketfeatures)triggerPriceTypeprice)IOCFOKPOGTD)
marginModetriggerPricer   triggerDirectionstopLossPricetakeProfitPriceattachedStopLossTakeProfittimeInForcehedgedtrailingleveragemarketBuyByCostmarketBuyRequiresPriceselfTradePreventionicebergi )r   limitdaysBack	untilDayssymbolRequired)r   triggerr   r   )r   r   r   r   r   )r   r   r   r   r   r   r   r     )	r   rB   createOrdersrm   rr   rq   ru   rS   rn   )linearinverse)r4   r6   r7   
exceptions)z4Both buyingCurrency and sellingCurrency are requiredz8One and only one of buyingQty and sellingQty is requiredzInvalid buyingCurrencyzInvalid 'from'zInvalid sellingCurrencyzInvalid buyingQtyzInvalid sellingQtyzInsufficient balancez8Expiration date is in the past or too near in the future	ForbiddenzOrder Not Foundz%since must be a millisecond timestampzThis pair is disabled on margin)zaccessing from a new IPzavailable to allocatezAt leastzcollateral is not allowedzInsufficient liquidityzInsufficient order sizezInvalid quantityzInvalid Stop LosszInvalid stop price!zNot enough balancezNot enough marginzorderType missingzServer Timeoutz4Time in force has to be IOC or FOK for market orderszToo many attempts)exactbroad)deep_extendsuperr$   describeparse_numberr!   r   r   r   r   r   r   r   r    )self	__class__s    H/var/www/html/turnos/venv/lib/python3.12/site-packages/ccxt/coinmetro.pyr   zcoinmetro.describe   sx   i ? A qD
+qD
KqD
 $qD
 t	qD

 qD
 qD
 5qD
  ddd $d 	d
 %d %d Ud $Td 'd "5d td d $Ud  d 'd  t!d" &u#d$ (%d& ''d( ()d* "4+d, 5-d. U/d0  1d2 3d4  5d6 &u7d8 +E9d: )%;d< /=d> &u?d@ #EAdB $UCdD 'EdF (GdH "4IdJ KdL &uMdN (OdP 1%QdR  SdT +EUdV *5WdX +EYdZ &u[d\ #E]d^ *5_d` $Uadb "5cdd *5edf +Egdh #Eidj tkdl  mdn %eodp +Eqdr sdt !%udv  wdx dydz +E{d| !%}d~ "4d@ dAdB !$CdD "5EdF uGdH #EIdJ  KdL !%MdN %eOdP )%QdR uSdT uUdV WdX UYdZ t[d\ "5]d^ #E_d` %eadb &ucdd 'edf $Ugdh !%idj "5kdl %*,1 %$)',$"!&#(!!GdqD
Z    [qD
h k9:
 ?? 0M uDiqD
J %&KL+,89"##$01>?	 +,)*9=<=23;?26+,	  !%&#$)*23<=)*:;;<12  !<=34;<	/+KqD
b "	$cqD
n $!&"&!..w7!..s3oqD
@ YAqD
D 0428EqD
L #&*(,,0,1).+004%*7
 $(#'"'#'	( #($)$)+/27/4#'/$2 %)&+!%$*%)*/& ',#($)*/	# ',!%#($)*/( ',!%$*%)#($)*/$ *.#u=~ ##
 ##GGMqD
\  MYP\.:(2/;)5*6,=P\!1'4=G7@  0@-> *1;.:/;(4)5+7*;):)3&3LX):#"]qD
 q q	    c                    | j                  |      }i }t        dt        |            D ]  }||   }| j                  |d      }| j	                  |      }| j                  |d      }d}	|dk(  s
|dk(  s|dk(  rd}	n|d	k(  rd	}	| j                  |d
d      }
| j                  ||||	|| j                  |d      | j                  |d      | j                  |d      d| j                  | j                  |
            | j                  |d      ddddddi d      ||<    | j                  | j                  d      | j                  |d      }|| j                  d<   | j                  | j                  dg       }t        |j!                               }t        dt        |            D ]  }|j#                  ||           || j                  d<   |S )a<  
        fetches all available currencies on an exchange

        https://documenter.getpostman.com/view/3653795/SVfWN6KS#d5876d43-a3fe-4479-8c58-24d0f044edfb

        :param dict [params]: extra parameters specific to the exchange API endpoint
        :returns dict: an associative dictionary of currencies
        r   symboltypeNcoinr   erc20cryptofiatdigitsnotabeneDecimalscanTrade
canDepositcanWithdrawminQtyminmax)amountr   )r'   coder(   r   infoactiverH   r   fee	precisionlimitsnetworksr   r'   r   )publicGetAssetsrangelensafe_stringsafe_currency_codesafe_string_2safe_currency_structure	safe_boolr   parse_precisionsafe_number
safe_valuer   index_by	safe_listlistkeysappend)r   paramsresponseresulticurrencyr'   r  typeRawr   precisionDigitscurrenciesByIdcurrentCurrencyIdsListcurrencyIdsLists                 r   fetch_currencieszcoinmetro.fetch_currenciesM  s    ''/V q#h-( !	A{H!!(H5B**2.D&&x8GD& Gw$6'W:LF""008EWXO77 ..:>>>(LA NN8]C!..t/C/CO/TU  $//(C#
  $#!	 +9 F4L!	D ??4<<)GHP!]]648N;IDLL78%)^^DLLBace%f"">#6#6#89O1c/23 B&--oa.@AB<RDLL89r   c                     | j                  |      }| j                  | j                  d      | j                          | j	                  |      S )a?  
        retrieves data on all markets for coinmetro

        https://documenter.getpostman.com/view/3653795/SVfWN6KS#9fd18008-338e-4863-b07d-722878a46832

        :param dict [params]: extra parameters specific to the exchange API endpoint
        :returns dict[]: an array of objects representing market data
        r   )publicGetMarketsr  r   r#  parse_markets)r   r  r  s      r   fetch_marketszcoinmetro.fetch_markets  sI     ((0??4<<)GHP!!#  !!(++r   marketc                     | j                  |d      }| j                  |      }| j                  |d      }| j                  |d      }| j                  |      }| j                  |      }| j                  |      }| j                  |      }	| j	                  |dd      }
| j                  | j                  di       }| j                  i d|d|d	z   |z   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 | j                  |d      | j                  |d      d d d d d |d   | j                  | j                  | j                  |d                  dd d d|d   d dd d d|	d   d ddd |d      S )NpairbaseIdquoteIdr5   Fr   r'   r   /basequotesettlesettleIdr   r4   Tr6   r7   r8   r  contractr   r   r   r  )r  r   r   minLimit)r   r  r   cost)r   r   r   contractSizeexpiryexpiryDatetimestrike
optionTyper  r  createdr  )r  parse_market_idr  !parse_market_precision_and_limitsr  r  r   safe_market_structurer  r   r  )r   r(  r'   parsedMarketIdr+  r,  r.  r/  basePrecisionAndLimitsquotePrecisionAndLimitsr5   tradingFeess               r   parse_marketzcoinmetro.parse_market  sU   ff---b1!!.(;"">9=&&v.''0!%!G!G!O"&"H"H"Q%8oodiiB?)) 2+
"2+
dSj5(2+
 D2+
 U	2+

 d2+
 f2+
 w2+
 2+
 F2+
 D2+
 f2+
 E2+
 e2+
 e2+
 d2+
  !2+
" d#2+
$ %%k7;%%k7; "0=**4+?+?@P@PQWYd@e+fg  
 2*=
  
 3:>$ c2+
 2 2	r   c                    d }d }| j                  | j                  dg       }t        |      }t        d|      D ]K  }t        d||z
  dz
        D ]4  }||   }||dz      }	t        |      t        |	      k  s(|	||<   |||dz   <   6 M t        dt        |            D ]R  }||   }
|j	                  |
      }|dk(  s|j                  |
d      }| j                  ||      sD|dk(  r|
}|}n|}|
} n ||d}|S )Nr   r   r    )r+  r,  )r  r   r  r
  findreplacein_array)r   marketIdr+  r,  currencyIdscurrencyIdsLengthr  jab
currencyId
entryIndexrestIdr  s                 r   r;  zcoinmetro.parse_market_id
  s3   oodll4SUWX,q+, 	+A1/!3a78 +NA&q6CF?%&KN)*KA&+	+ q#k*+ 	A$QJ!z2JQ!))*b9==5!Q!+"(!'",	 
 r   c                     | j                  | j                  di       }| j                  ||i       }| j                  |di       }| j                  |di       }| j                  |d      }| j                  |d      |d}|S )Nr   r  r  r   r  )r  r3  )r  r   r  )r   rN  
currenciesr  r  amountLimitsr3  r  s           r   r<  z+coinmetro.parse_market_precision_and_limits*  s    __T\\3QSUV
??:z2>8R8vx<##L%8))(K@ 
 r   r   Nr   sincer   c                    | j                          | j                  |      }|d   | j                  | j                  ||      d}d}|1||d<   |/| j	                  |      dz  }	| j                  ||	|z        }nd|d<   | j                  |d|      }|| j                  |dg      }||d<   nd	|d<   | j                  | j                  ||            }
| j                  |
d
g       }| j                  |||||      S )a  
        fetches historical candlestick data containing the open, high, low, and close price, and the volume of a market

        https://documenter.getpostman.com/view/3653795/SVfWN6KS#13cfb5bc-7bfb-4847-85e1-e0f35dfb3573

        :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
        :param int [params.until]: the latest time in ms to fetch entries for
        :returns int[][]: A list of candles ordered, open, high, low, close, volume
        r'   )r*  	timeframeNfromr   z:fromuntiltoz:tocandleHistory)load_marketsr(  r  r   parse_timeframesumsafe_integeromit+publicGetExchangeCandlesPairTimeframeFromToextendr  parse_ohlcvs)r   r   rV  rT  r   r  r(  requestrX  durationr  rZ  s               r   fetch_ohlcvzcoinmetro.fetch_ohlcv6  s    	V$4L))$//9iP
 #GFO //	:TAE(:;%GFO!!&'59YYvy1F!GDM!GDMCCDKKPWY_D`a8 x"E  	5%PPr   c           	          | j                  |d      | j                  |d      | j                  |d      | j                  |d      | j                  |d      | j                  |d      gS )N	timestampohlcv)r^  r  )r   ohlcvr(  s      r   parse_ohlcvzcoinmetro.parse_ohlcvw  sl    e[1UC(UC(UC(UC(UC(
 	
r   c                     | j                          | j                  |      }d|d   i}|||d<   nd|d<   | j                  | j                  ||            }| j	                  |dg       }| j                  ||||      S )aZ  
        get the list of most recent trades for a particular symbol

        https://documenter.getpostman.com/view/3653795/SVfWN6KS#6ee5d698-06da-4570-8c84-914185e05065

        :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(default 200, max 500)
        :param dict [params]: extra parameters specific to the exchange API endpoint
        :returns Trade[]: a list of `trade structures <https://docs.ccxt.com/#/?id=public-trades>`
        r*  r'   rW  rD  tickHistory)r[  r(  publicGetExchangeTicksPairFromra  r  parse_trades)	r   r   rT  r   r  r(  rc  r  rp  s	            r   fetch_tradeszcoinmetro.fetch_trades  s     	V$F4L
 #GFO !GFO66t{{7F7ST: nnX}bA  feUCCr   c                     | j                          d}|| j                  |      }i }|||d<   nd|d<   | j                  | j                  ||            }| j	                  ||||      S )a4  
        fetch all trades made by the user

        https://documenter.getpostman.com/view/3653795/SVfWN6KS#4d48ae69-8ee2-44d1-a268-71f84e557b7b

        :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 trades structures to retrieve(default 500, max 1000)
        :param dict [params]: extra parameters specific to the exchange API endpoint
        :returns Trade[]: a list of `trade structures <https://docs.ccxt.com/#/?id=trade-structure>`
        NrT  r   )r[  r(  privateGetExchangeFillsSincera  rr  r   r   rT  r   r  r(  rc  r  s           r   fetch_my_tradeszcoinmetro.fetch_my_trades  s~     	[[(F$GG  !GG44T[[&5QR   65%@@r   tradec                    | j                  |dd      }| j                  ||      }|d   }| j                  |g d      }| j                  |d      }| j	                  |d      }| j	                  |d      }| j	                  |d      }	| j	                  |d      }
| j                  ||	|| j                  |      |d |
d ||d d |d	|      S )
Nr   r*  )_idseqNum	seqNumberrg  r   qtyorderIDside)r'   orderrg  datetimer   r   r  takerOrMakerr   r  r4  r  r  )r  safe_marketsafe_string_nr^  r  
safe_tradeiso8601)r   rx  r(  rH  r   r'   rg  priceStringamountStringr  r  s              r   parse_tradezcoinmetro.parse_trade  s    V %%eXv>!!(F3!'EF%%e[9	&&ug6''u5  	2v."Y/  " 
  	r   c                 b   | j                          | j                  |      }d|d   i}| j                  | j                  ||            }| j	                  |di       }| j	                  |di       }| j	                  |di       }	||	d}
| j                  |
|      }| j                  |d      |d<   |S )	ap  
        fetches information on open orders with bid(buy) and ask(sell) prices, volumes and other data

        https://documenter.getpostman.com/view/3653795/SVfWN6KS#26ad80d7-8c46-41b5-9208-386f439a8b87

        :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(default 100, max 200)
        :param dict [params]: extra parameters specific to the exchange API endpoint
        :returns dict: A dictionary of `order book structures <https://docs.ccxt.com/#/?id=order-book-structure>` indexed by market symbols
        r*  r'   bookbidask)bidsasksr|  nonce)r[  r(  publicGetExchangeBookPairra  r  parse_order_bookr^  )r   r   r   r  r(  rc  r  r  rawBidsrawAsksrawOrderbook	orderbooks               r   fetch_order_bookzcoinmetro.fetch_order_book"  s     	V$F4L
 11$++gv2NO8 x4//$r2//$r2
 )),?	!..t[A	'r   priceKey	amountKeycountOrIdKeyc                    t        |j                               }g }t        dt        |            D ]K  }| j	                  ||      }| j                  ||      }	| j                  ||      }
|j                  |	|
g       M |S )Nr   )r  r  r
  r  r  r  r  )r   bidasksr  r  r  pricesr  r  r  r   volumes              r   parse_bids_askszcoinmetro.parse_bids_asksY  s~    glln%q#f+& 	+A**615K$$VQ/E%%g{;FMM5&/*		+
 r   symbolsc                    | j                          | j                  |      }| j                  |dg       }| j                  |dg       }i }t        dt	        |            D ]!  }||   }| j                  |d      }	|	|||	<   # t        dt	        |            D ]D  }||   }
| j                  |
d      }	|	| j                  ||	i       }| j                  |
|      ||	<   F t        |j                               }| j                  ||      S )a5  
        fetches price tickers for multiple markets, statistical information calculated over the past 24 hours for each market

        https://documenter.getpostman.com/view/3653795/SVfWN6KS#6ecd1cd1-f162-45a3-8b3b-de690332a485

        :param str[] [symbols]: unified symbols of the markets to fetch the ticker for, all market tickers are returned if not assigned
        :param dict [params]: extra parameters specific to the exchange API endpoint
        :returns dict: a dictionary of `ticker structures <https://docs.ccxt.com/#/?id=ticker-structure>`
        latestPrices24hInfor   r*  )
r[  publicGetExchangePricesr  r
  r  r  ra  r  valuesparse_tickers)r   r  r  r  r  twentyFourHInfostickersObjectr  latestPricerH  twentyFourHInfotickerss               r   fetch_tickerszcoinmetro.fetch_tickersc  s$    	//7b xD??8YC q#l+, 	6A&q/K''V<H#*5h'		6
 q#./0 	TA.q1O''@H#"oomXrJ*.++o{*Sh'	T }++-.!!'733r   c                     | j                          | j                  |      }| j                  |dg       }| j                  ||      S )a  
        fetches the bid and ask price and volume for multiple markets

        https://documenter.getpostman.com/view/3653795/SVfWN6KS#6ecd1cd1-f162-45a3-8b3b-de690332a485

        :param str[] [symbols]: unified symbols of the markets to fetch the bids and asks for, all markets are returned if not assigned
        :param dict [params]: extra parameters specific to the exchange API endpoint
        :returns dict: a dictionary of `ticker structures <https://docs.ccxt.com/#/?id=ticker-structure>`
        r  )r[  r  r  r  )r   r  r  r  r  s        r   fetch_bids_askszcoinmetro.fetch_bids_asks  sE     	//7~~hC!!,88r   tickerc                 P   | j                  |d      }| j                  ||      }| j                  |d      }| j                  |d      }| j                  |d      }| j                  |d      }| j                  |d      }| j                  |d      }	| j                  |d      }
| j                  |d	      }t        j                  |d
      }| j                  i d|d   d|d| j                  |      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*  rg  r  r  ri  rj  r   rl  delta100r   r  openhighlowcloselast	bidVolume	askVolumevwappreviousClosechanger   average)
baseVolumequoteVolumer  )r  r  r^  r"   
string_mulsafe_tickerr  )r   r  r(  rH  rg  r  r  r  r  r  r  r  r   s                r   parse_tickerzcoinmetro.parse_ticker  s   & ##FF3!!(F3%%fk:	vu-vu-,vs+0%%fc2
  1''u5
 !
fX&!
!
 Y/!
 D	!

 D!
 3!
 T!
 D!
 3!
 !
 3!
 !
 D!
 T!
 d!
  *!!
" t#!
$ %)!
* + 	r   c                     | j                          | j                  |      }| j                  |dg       }| j                  |      S )a  
        query for balance and get the amount of funds available for trading or funds locked in orders

        https://documenter.getpostman.com/view/3653795/SVfWN6KS#741a1dcc-7307-40d0-acca-28d003d1506a

        :param dict [params]: extra parameters specific to the exchange API endpoint
        :returns dict: a `balance structure <https://docs.ccxt.com/#/?id=balance-structure>`
        r  )r[  privateGetUsersWalletsr  parse_balance)r   r  r  r  s       r   fetch_balancezcoinmetro.fetch_balance  sC     	..v6~~h3!!$''r   c                 J   d|i}t        dt        |            D ]w  }| j                  ||i       }| j                  |d      }| j	                  |      }| j                         }| j                  |d      |d<   | j                  |d      |d<   |||<   y | j                  |      S )Nr  r   r  balancetotalreservedused)r
  r  	safe_dictr  r  accountsafe_balance)r   balancesr  r  balanceEntryrN  r  r  s           r   r  zcoinmetro.parse_balance  s    0 H
 q#h-( 	#A>>(Ar:L)),
CJ**:6DllnG#//iHGG"..|ZHGFO"F4L	#   ((r   r  c                    | j                          i }|||d<   nd|d<   d}|| j                  |      }| j                  | j                  ||            }| j	                  |dg       }g }	t        dt        |            D ]a  }
||
   }| j                  |d      }| j	                  |dg       }t        dt        |            D ]  }||   }||d<   |	j                  |        c | j                  |	|||      S )	a  
        fetch the history of changes, actions done by the user or operations that altered the balance of the user

        https://documenter.getpostman.com/view/3653795/SVfWN6KS#4e7831f7-a0e7-4c3e-9336-1d0e5dcb15cf

        :param str [code]: unified currency code, default is None
        :param int [since]: timestamp in ms of the earliest ledger entry, default is None
        :param int [limit]: max number of ledger entries to return(default 200, max 500)
        :param dict [params]: extra parameters specific to the exchange API endpoint
        :param int [params.until]: the latest time in ms to fetch entries for
        :returns dict: a `ledger structure <https://docs.ccxt.com/#/?id=ledger>`
        NrT  rD  r  r   r  balanceHistoryrN  )
r[  r  "privateGetUsersWalletsHistorySincera  r  r
  r  r  r  parse_ledger)r   r  rT  r   r  rc  r  r  ledgerByCurrenciesledgerr  currencyLedgerrN  r  rK  rawLedgerEntrys                   r   fetch_ledgerzcoinmetro.fetch_ledger'  s     	$GG  "GG}}T*H::4;;wPV;WXr "__XvrBq#012 	.A/2N)).*EJ!__^=MrRN1c.12 .!/!2/9|,n-.		.   5%@@r   itemr  c                 N   | j                  |d      }| j                  |d      }| j                  |d      }| j                  ||      }| j                  |dd      }| j                  |      \  }}| j	                  |di       }| j                  |d      }	|	d d}
| j                  |d      }d }|Ft        j                  |d	      rd
}t        j                  |      }nt        j                  |d	      rd}| j                  |d | j                  |      ||d |d |||d d d |
d|      S )Nrg  rN  descriptionrD  JSONdatar   )r4  r  r  r   outin)r  r'   rg  r  	directionr  referenceIdreferenceAccountr   r  r  beforeafterstatusr  )r  r_  safe_currencyparse_ledger_entry_descriptionr  r"   	string_lt
string_abs	string_gtsafe_ledger_entry	parse8601)r   r  r  r  rN  r  r   r  r  feeCostr  r  r  s                r   parse_ledger_entryzcoinmetro.parse_ledger_entry  sN   ##D+6%%dL9
yy|,%%j(;&&t]B? ??Lk??4R8""8V4
 !!$1	  -!	 ++F3""63/ 	%%1 "& $ '
  ! 	r   c                     g }||j                  d      }d }d }t        |      }|dkD  r7| j                  |d         }|d   dk7  r	|d   }||gS | j                  |d      }||gS )N r   r   -   )splitr  parse_ledger_entry_typer  )r   r  descriptionArrayr   r  lengths         r   r  z(coinmetro.parse_ledger_entry_description  s    "*005%&A://0@0CDD"c).q1 k"" #../?Ck""r   c                 4    dddd}| j                  |||      S )Ntransactionrx  )DepositWithdrawr   )r  )r   r   typess      r   r  z!coinmetro.parse_ledger_entry_type  s)    $%

 tT22r   r   r  r  r   c                 @   | j                          | j                  |      }i }||d<   d}	|| j                  ||      }	| j                  |d      }
| j	                  |d      }|dk(  rk| |
t        | j                  dz   |z   dz         |G|Et        j                  | j                  |      | j                  |	            }| j                  |      }
d}|
| j                  ||
      }|dk(  r| j                  |d   |d	   |	||      }n |d
k(  r| j                  |d	   |d   ||	|      }| j                  |d      }|&| j	                  |d      }| j                  |      |d<   | j                  |dd      }|(| j	                  |dg      }| j                  ||      |d<   | j                  |di       }| j                  |dd      }|| j	                  |dg      }||d<   | j!                  |d      }|'| j	                  |d      }| j                  ||      |d<   | j!                  |d      }|'| j	                  |d      }| j                  ||      |d<   | j#                  |      s||d<   | j%                  | j'                  ||            }| j)                  ||      S )av  
        create a trade order

        https://documenter.getpostman.com/view/3653795/SVfWN6KS#a4895a1d-3f50-40ae-8231-6962ef06c771

        :param str symbol: unified symbol of the market to create an order in
        :param str type: 'market' or '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.cost]: the quote quantity that can be used alternative for the amount in market orders
        :param str [params.timeInForce]: "GTC", "IOC", "FOK", "GTD"
        :param number [params.expirationTime]: timestamp in millisecond, for GTD orders only
        :param float [params.triggerPrice]: the price at which a trigger order is triggered at
        :param float [params.stopLossPrice]: *margin only* The price at which a stop loss order is triggered at
        :param float [params.takeProfitPrice]: *margin only* The price at which a take profit order is triggered at
        :param bool [params.margin]: True for creating a margin order
        :param str [params.fillStyle]: fill style of the limit order: "sell" fulfills selling quantity "buy" fulfills buying quantity "base" fulfills base currency quantity "quote" fulfills quote currency quantity
        :param str [params.clientOrderId]: client's comment
        :returns dict: an `order structure <https://docs.ccxt.com/#/?id=order-structure>`
        	orderTypeNr4  r   z> createOrder() requires a price or params.cost argument for a z ordersellr+  r,  buyr   r   	stopPriceuserDataclientOrderIdcommentr   stopLossr   
takeProfit)r[  r(  amount_to_precisionr  r_  r   r'   r"   r  number_to_stringparse_to_numericcost_to_precisionhandle_create_order_sideencode_order_time_in_forcer  price_to_precisionr  is_emptyprivatePostExchangeOrdersCreatera  parse_order)r   r   r   r  r  r   r  r(  rc  formattedAmountr4  
costStringprecisedCostr   r   r  r  r   r   r  s                       r   create_orderzcoinmetro.create_order  s   . 	V$
#"66vvFOvv.66*7?DL'2r(ruy(y  }E  )E  F  F#&*<$//0E0Ee0LdNcNcdsNtu
,,Z811&$?L6>33F84DfYFWYhjvx  AGU]33F94EvhGWYegvx  AGoofm<"YYv}5F%)%D%D[%QGM"))&.+N#YYv'78F#'#:#:6<#PGK ??6:r:$$V_iHYYv'89F")HY((A$YYv7F#'#:#:6=#QHZ **63DE&YYv'89F%)%<%<V_%UH\"}}X&"*GJ77GV8TU: &11r   c                 6    ||d<   ||d<   |||d<   |||d<   |S )NsellingCurrencybuyingCurrency
sellingQty	buyingQty )r   r  r  r  r  rc  s         r   r
  z"coinmetro.handle_create_order_sideE  s=    %4!"$2 !!$.GL! #,GK r   c                 6    ddddd}| j                  |||      S )Nr   r  r      )GTCr   r   r   r  r   r   timeInForceTypess      r   r  z$coinmetro.encode_order_time_in_forceN  s,    	"
 /kJJr   r'   c                 V   | j                          d|i}d}| j                  d|      \  }}| j                  |dd      }| j                  |d      }d}|s|"| j	                  | j                  ||            }n!| j                  | j                  ||            }| j                  |      S )aH  
        cancels an open order

        https://documenter.getpostman.com/view/3653795/SVfWN6KS#eaea86da-16ca-4c56-9f00-5b1cb2ad89f8
        https://documenter.getpostman.com/view/3653795/SVfWN6KS#47f913fb-8cab-49f4-bc78-d980e6ced316

        :param str id: order id
        :param str symbol: not used by coinmetro cancelOrder()
        :param dict [params]: extra parameters specific to the exchange API endpoint
        :param str [params.margin]: True for cancelling a margin order
        :returns dict: An `order structure <https://docs.ccxt.com/#/?id=order-structure>`
        r~  Nr=   r5   F)r[  handle_margin_mode_and_paramsr  r_  %privatePostExchangeOrdersCloseOrderIDra  %privatePutExchangeOrdersCancelOrderIDr  )r   r'   r   r  rc  r   isMarginr  s           r   cancel_orderzcoinmetro.cancel_orderW  s     	r
 
;;M6R>>&(E:68,
.AA$++gW]B^_HAA$++gW]B^_H( ))r   c                     | j                          | j                  |d      }|t        | j                  dz         d|i}| j	                  | j                  ||            }| j                  |      S )aS  
        closes an open position

        https://documenter.getpostman.com/view/3653795/SVfWN6KS#47f913fb-8cab-49f4-bc78-d980e6ced316

        :param str symbol: not used by coinmetro closePosition()
        :param str [side]: not used by coinmetro closePosition()
        :param dict [params]: extra parameters specific to the exchange API endpoint
        :param str [params.orderID]: order id
        :param number [params.fraction]: fraction of order to close, between 0 and 1(defaults to 1)
        :returns dict: An `order structure <https://docs.ccxt.com/#/?id=order-structure>`
        orderIdz- closePosition() requires a orderId parameterr~  )r[  r  r   r'   r"  ra  r  )r   r   r  r  r'  rc  r  s          r   close_positionzcoinmetro.close_position  sy     	""695?#DGG.]$]^^w
 ==dkk'SY>Z[< ))r   c                     | j                          d}|| j                  |      }| j                  |      }| j                  ||||      }t	        dt        |            D ]  }||   }	d|	d<    |S )a-  
        fetch all unfilled currently open orders

        https://documenter.getpostman.com/view/3653795/SVfWN6KS#518afd7a-4338-439c-a651-d4fdaa964138

        :param str symbol: unified market symbol
        :param int [since]: the earliest time in ms to fetch open orders for
        :param int [limit]: the maximum number of open order structures to retrieve
        :param dict [params]: extra parameters specific to the exchange API endpoint
        :returns Order[]: a list of `order structures <https://docs.ccxt.com/#/?id=order-structure>`
        Nr   r  r  )r[  r(  privateGetExchangeOrdersActiveparse_ordersr
  r  )
r   r   rT  r   r  r(  r  ordersr  r  s
             r   fetch_open_orderszcoinmetro.fetch_open_orders  s     	[[(F66v>""8VUEBq#f+& 	%A1IE$E(O	% r   c                     | j                          d}|| j                  |      }i }|||d<   | j                  | j                  ||            }| j	                  ||||      S )ah  
        fetches information on multiple canceled and closed orders made by the user

        https://documenter.getpostman.com/view/3653795/SVfWN6KS#4d48ae69-8ee2-44d1-a268-71f84e557b7b

        :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 Order[]: a list of `order structures <https://docs.ccxt.com/#/?id=order-structure>`
        NrT  )r[  r(  $privateGetExchangeOrdersHistorySincera  r+  rv  s           r    fetch_canceled_and_closed_ordersz*coinmetro.fetch_canceled_and_closed_orders  sq     	[[(F$GG<<T[[RX=YZ  65%@@r   c                     | j                          d|i}| j                  | j                  ||            }| j                  |      S )a  
        fetches information on an order made by the user

        https://documenter.getpostman.com/view/3653795/SVfWN6KS#95bbed87-db1c-47a7-a03e-aa247e91d5a6

        :param int|str id: order id
        :param str symbol: not used by coinmetro fetchOrder()
        :param dict [params]: extra parameters specific to the exchange API endpoint
        :returns dict: An `order structure <https://docs.ccxt.com/#/?id=order-structure>`
        r~  )r[  %privateGetExchangeOrdersStatusOrderIDra  r  )r   r'   r   r  rc  r  s         r   fetch_orderzcoinmetro.fetch_order  sN     	r
 ==dkk'SY>Z[H ))r   r  c           
         | j                  |d      }| j                  |d      }d }|du r|| j                  |d      }d}n'd}n$| j                  |d      }| j                  |d      }| j                  |d      }| j                  |d      }| j                  |d	      }| j                  |d
      }	| j                  |d      }
|dk(  r|	|	|	dk7  r|	}|	|
|
dk7  r|
}| j                  |dd      }| j                  |dd      }||z   }||z   }d }d }|}|}d }d }d }| j	                  | j
                  d      }| j                  ||      d}|}|}|	}|
}d}n| j                  ||      d}|}|}|
}|	}d}d }||t        j                  ||      }| j                  ||      }d }| j                  |d      }||	||   |d d}| j                  |dg       }| j                  |di       }| j                  |d      }| j                  |d      }| j                  |d      }| j                  i d| j                  |d      d|d|d | j                  |      d!| j                  |d"      d|d#|d#   d$|d%| j                  | j                  |d%            d&|d'|d(| j                  |d)      d*|d+|d,d d-|d.||d |d ||d/|      S )0NcreationTimecanceledTcompletionTimerejectedr  r  r  r  	boughtQtysoldQtyr(  r   r  rD  r  r'   r  r.  r  r/  r   )r  r4  ratefillsr  r  r  r  r~  r  rg  r  lastTradeTimestamplastFillTimer   r   r   r  r   r   r   r   r   r  r  r4  )filled	remainingr  r   tradesr  )r^  r  r  r_  r  r   r"   
string_divr  
safe_orderr  parse_order_time_in_force)r   r  r(  rg  
isCanceledr  r   r  r  r9  r:  buyingCurrencyIdsellingCurrencyIdbyuingIdPlusSellingIdsellingIdPlusBuyingIdr  rH  
baseAmountquoteAmountr?  r4  feeInBaseOrQuotemarketsByIdr   r  r  rA  r  r  r   r   s                                  r   r  zcoinmetro.parse_order  s   b %%e^<	__UJ7
  --e5EF	##%%eX6FIIeX.E{3$$UK8	%%e\:
$$UK8	""5)48!	(=IQTDT%	")<7c>$
++E3CRH ,,U4ErJ 03D D 14D D
mmDLL$7??;(=>JD,H$KFD%__[*?@LD,H#JFD&")@&&{J?E!!(F3""5&1&6&B"#34C
 4??5*b9((9=**8\B((:>  
$""5)4 
] 
  
 Y/	 

 !$"3"3E>"J 
 f 
 fX& 
 D 
 499$:K:KES`:ab 
 D 
 U 
 D,,UK@ 
  
 ] 
 t 
  j! 
" D# 
$ / 
0 1 	r   c                 0    g d}| j                  |||      S )N)Nr  r   r   r   r  r  s      r   rD  z#coinmetro.parse_order_time_in_force(  s     
 /kJJr   c                 0   | j                          | j                  |      }|d   }i }| j                  ||      ||<   | j                  | j	                  ||            }| j                  |di       }| j                  ||      }	| j	                  |	d|i      S )a  
        create a loan to borrow margin

        https://documenter.getpostman.com/view/3653795/SVfWN6KS#5b90b3b9-e5db-4d07-ac9d-d680a06fd110

        :param str code: unified currency code of the currency to borrow
        :param float amount: the amount to borrow
        :param dict [params]: extra parameters specific to the exchange API endpoint
        :returns dict: a `margin loan structure <https://docs.ccxt.com/#/?id=margin-loan-structure>`
        r'   r  r  )r[  r  currency_to_precisionprivatePutUsersMarginCollateralra  r  parse_margin_loan)
r   r  r  r  r  rN  rc  r  r  r  s
             r   borrow_cross_marginzcoinmetro.borrow_cross_margin2  s     	==&d^
"88vF
77GV8TU 8R8,,VX>{{;f)
  	r   c                 Z    | j                  |d      }d | j                  ||      d d d d |dS )Nr   )r'   r  r  r   rg  r  r  )r  r  )r   r  r  rN  s       r   rR  zcoinmetro.parse_margin_loanL  s@    %%dF3
//
HE
 	
r   r   GETc                    | j                  || j                  |            }d| j                  ||      z   }| j                  d   |   |z   }	| j	                  |      }
|i }d|d<   |dk(  r| j
                  | j                  | j                  | _        | j                  | j                  | j                  | _        |	dk(  r!d|d<   | j                  | j                  |d	<   nr|	d
k(  r+| j
                  |d<   | j                  R| j                  |d	<   nBd| j                  z   |d<   |	j                  d      s| j                          | j
                  |d<   |dk(  s|dk(  r-d|d<   | j	                  |      }nt        |
      dk7  r|	d|
z   z  }	|	j                  d      r#|	dt        |	      dz
   }	|	j                  d      r#|	|||dS )Nr-  r   trueCCXTr   zhttps://api.coinmetro.com/jwtbypasszX-Device-IdzX-OTPz#https://api.coinmetro.com/jwtDevicezBearer Authorizationr   POSTPUTz!application/x-www-form-urlencodedzContent-Typer   ?r   )urlmethodbodyheaders)r_  extract_paramsimplode_paramsr   	urlencoder   r   r   r   twofa
startswithcheck_required_credentialsr  endswith)r   pathr   r_  r  ra  r`  rc  endpointr^  querys              r   signzcoinmetro.signX  s   ))FD$7$7$=>,,T6::iis#h.w'?G ) t{{'>;;

")@![[
55)1&::)'+zzGG$==)-&::)'+zzGG$+4tzz+A(~~&FG335-1XXGM*& fo*M'~~g.Z1_3;Cll3aC1%C ll3fdwOOr   reasonr^  r_  ra  r`  c
                    |y |dk7  ry|dk7  rt|dk7  ro| j                   dz   |z   }
| j                  |d      }| j                  | j                  d   ||
       | j	                  | j                  d   ||
       t        |
      y )Nr/         r  messager   r   )r'   r  throw_broadly_matched_exceptionr   throw_exactly_matched_exceptionr   )r   r  rm  r^  r_  ra  r`  r  requestHeadersrequestBodyfeedbackrq  s               r   handle_errorszcoinmetro.handle_errors{  s    CKdckww}t+H&&x;G001I7T\]001I7T\]))r   )N)r   r   r  )@__name__
__module____qualname__r   r   r   r#  r   r   r'  dictrB  r;  r<  strr
   r  re  rn  r   rs  r   rw  r  r   r  r	   r  r   r   r  r  r   r  r   r  r  r   r  r   r  r  r  r   r   floatr   r  r
  r  r%  r(  r   r-  r0  r3  r  rD  rS  rR  rl  intrw  __classcell__)r   s   @r   r$   r$      s   r# rh	 ') _Z _B $& ,$v, ,:=4 =F =~@
 26DW[df ?Q# ?Qc ?QQT ?Qkoptku ?QB
 
4 
 6:UW 4D3 4Ds 4D# 4D\`af\g 4Dl -1tRV_a %Ac %A %AC %ANB Bv B BH :>b 5s 53 5Y 5n 9 hq  04B L4W L47 L4\ 26b 9w 934 3 36 3j $& (( (") ")H (,$TZ\ zA zAC zAs zAaefqar zAx%t %x %; %N#3 gksu b23 b2i b2y b2RW b2`c b2H hj K 37r -*s -*C -*^ =A 2*S 2*	 2*h /3TXac  3 c hlmrhs . >BPTcgpr As A# A]` Aw{  }B  xC A, 26b 3*c 3*3 3*jJ Jv J JXK DF  U 4

 

 &eBSW !PF	# 	s 	 	c 	TX 	`c 	r   r$   N)(ccxt.base.exchanger   ccxt.abstract.coinmetror   ccxt.base.typesr   r   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_    ( / x  x  x  x  x  * - . ' & . ) * . 4 %m+ mr   