
    i:                       d dl mZ d dlmZ d dlmZmZmZmZm	Z	m
Z
mZmZmZ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%dS )    )Exchange)ImplicitAPI)Balances
CurrenciesCurrency	IndexTypeIntMarketNumOrder	OrderBook	OrderSide	OrderTypeStrStringsTickerTickersTrade)List)ExchangeError)PermissionDenied)ArgumentsRequired)
BadRequest)	BadSymbol)InsufficientFunds)InvalidOrder)OrderNotFound)RateLimitExceeded)DECIMAL_PLACES)Precisec                       e Zd Z fdZi fdefdZi fdee         fdZ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d<d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d<dedefdZd	i fd
ededefdZd=dededefdZd	i fdedefdZd	i fdefdZd<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fd"Z#d<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,Z-d- Z.d	i fd.ed
efd/Z/d	i fd
ed(e)fd0Z0d	d	d	i fd
edededee1         fd1Z2d	d	d	i fd
edededee1         fd2Z3d	i fd.ed
efd3Z4d<dede1fd4Z5d5 Z6i fd!ed)e*fd6Z7d<d#e$fd7Z8d8d9i d	d	fd:Z9d; Z: xZ;S )>	coinmetroc                 X   |                      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dedfdgdhdidjdkdldmdndododpdqdqdpdrdsgdtdudvdwdxdydzdydzdydydzdyd{idyd|dydyd|d|dyd}dydydydydydydydydydyd~
dydydydydddpdddddddddxdd|                     d          |                     d          didt
          dd 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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/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)currenciesByIdForParseMarketcurrencyIdsListForParseMarket
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    T/var/www/html/crypto-bot/backend/venv/lib/python3.11/site-packages/ccxt/coinmetro.pyr   zcoinmetro.describe   s"   i 6 6 ? ? A A gD
+gD
KgD
 $gD
 t	gD

 gD
 gD
 5gD
  ccc $c 	c
 %c %c Uc $Tc 'c "5c tc c $Uc  c 'c  t!c" &u#c c$ (%c& ''c( ()c* "4+c, 5-c. U/c0  1c2 3c4  5c6 &u7c8 +E9c: )%;c< /=c> &u?c@ #EAcB $UCcD 'Ec c cF (GcH "4IcJ KcL &uMcN (OcP 1%QcR  ScT +EUcV *5WcX +EYcZ &u[c\ #E]c^ *5_c` $Uacb "5ccd *5ecf +Egc c ch #Eicj tkcl  mcn %eocp +Eqcr sct !%ucv  wcx dycz +E{c| !%}c~ "4c@ dAcB !$CcD "5EcF uGcH #EIc c cJ  KcL !%McN %eOcP )%QcR uScT uUcV WcX UYcZ t[c\ "5]c^ #E_c` %eacb &uccd 'ecf $Ugch !%icj "5kc cl %*,1 %$)',$"!&#(!!Ec c cgD
X     YgD
f k9: 
 ??  0M uD ggD
H %&KL+,89"##$01>?	 	 +,9=<=23;?26+,   !%&#$)*23<=)*:;;<12   !<=34;<	 - * *IgD
^ "	$ $_gD
j $!&"&!..w77!..s33 kgD
| ^}gD
@ 0415 AgD
H  MYP\.:(2/;)5*6,=P\!1'4=G7@   0@-> *1;.:/;(4)5+7*;):)3&3LX): #" "IgD
 g g g	    returnc                    |                      |          }i }t          dt          |                    D ]}||         }|                     |d          }|                     |          }|                     |d          }|                     |d          }	|                     |d          }
|
r|nd}|                     |d          }|                     |d          }|                     ||||||	|d	||d	d
d	d	d
di d          ||<   |                     | j	        d          I| 
                    |d          }|| j	        d<   t          |                                          | j	        d<   |S )a@  
        fetches all available currencies on an exchange
        :see: 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canWithdraw
canDepositcanTradeTdigitsminQtyNminmax)amountr   )r$   coder%   infoactiverE   r   fee	precisionlimitsnetworksr   r$   r   )publicGetAssetsrangelensafe_stringsafe_currency_code
safe_valuesafe_integersafe_numbersafe_currency_structurer   index_bylistkeys)r   paramsresponseresulticurrencyr$   r   r   rE   r   r   r   	minAmountcurrenciesByIds                  r   fetch_currencieszcoinmetro.fetch_currencies  s    ''//V q#h--(( 	 	A{H!!(H55B**2..Dx??Hooh==Gx<<H!)3XXtF))(H==I((8<<I77  "$&&/==(,T : :  9 9  F4LL  ??4<)GHHP!]]6488N;IDL78<@ATATAVAV<W<WDL89r   c                     |                      |          }|                     | j        d          |                                  |                     |          S )aC  
        retrieves data on all markets for coinmetro
        :see: 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_marketsV  sV     ((00??4<)GHHP!!###* !!(+++r   c                 <   |                      |d          }|                     |          }|                      |d          }|                      |d          }|                     |          }|                     |          }|                     |          }|                     |          }	|                     |dd          }
|                     | j        di           }|                     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 |                     |d          |                     |d          d d d d d |d         |	d         |d         |	d         dd d d|d         d dd d d|	d         d ddd |d          S )NpairbaseIdquoteIdr2   Fr   r$   r   /basequotesettlesettleIdtyper1   Tr3   r4   r5   r   contractlinearr   r   r   )r   pricer   r   r   minLimit)leverager   r  cost)inverser   r   contractSizeexpiryexpiryDatetimestrike
optionTyper   r   createdr   )	r   parse_market_idr   !parse_market_precision_and_limits	safe_boolr   r   safe_market_structurer   )r   marketr$   parsedMarketIdr   r   r   r   basePrecisionAndLimitsquotePrecisionAndLimitsr2   tradingFeess               r   parse_marketzcoinmetro.parse_marketv  s   ff----b11!!.(;;"">9==&&v..''00!%!G!G!O!O"&"H"H"Q"Q%88oodiB??)) 4+
"4+
dSj5(4+
 D4+
 U	4+

 d4+
 f4+
 w4+
 4+
 F4+
 D4+
 f4+
 E4+
 e4+
 e4+
 d4+
  !4+
" d#4+
$ %%k7;;%%k7;; "0=0=.{;0=	    
 2*= 
   
 3:>  $ g4+
 4+
 4+
 4 4 4	r   c                 P   d }d }|                      | j        dg           }t          dt          |                    D ]b}||         }|                    |          }|dk    r=|                    |d          }|                     ||          r|dk    r|}|}n|}|} nc||d}	|	S )Nr   r    )r   r   )r   r   r   r   findreplacein_array)
r   marketIdr   r   currencyIdsr   
currencyId
entryIndexrestIdr   s
             r   r  zcoinmetro.parse_market_id  s    oodl4SUWXXq#k**++ 	 	A$QJ!z22JR!))*b99==55 !Q!+"(!'",E
 
 r   c                 *   |                      | j        di           }|                      ||i           }|                     |d          }|                      |di           }|                      |di           }|                     |d          }||d}|S )Nr   r   r   r   r   )r   r  )r   r   r   r   )	r   r#  
currenciesr   r   r   amountLimitsr  r   s	            r   r  z+coinmetro.parse_market_precision_and_limits  s    __T\3QSUVV
??:z2>>%%h<<	8R88vx<<##L%88" 
 
 r   r   Nr   sincelimitc                 N   |                                   |                     |          }|d         |                     | j        ||          d}d}|9||d<   |1|                     |          dz  }	|                     ||	|z            }nd|d<   |                     |dd|          }||                     |ddg          }||d	<   nd
|d	<   |                     | 	                    ||                    }
| 
                    |
dg           }|                     |||||          S )a
  
        fetches historical candlestick data containing the open, high, low, and close price, and the volume of a market
        :see: 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fromi  z:fromtilluntiltoz:tocandleHistory)load_marketsr  r   r   parse_timeframesumsafe_integer_2omit+publicGetExchangeCandlesPairTimeframeFromToextend	safe_listparse_ohlcvs)r   r   r,  r)  r*  r   r  requestr/  durationr   r1  s               r   fetch_ohlcvzcoinmetro.fetch_ohlcv  sH    	V$$4L))$/9iPP
 
 #GFO //	::TAE(:;;%GFO##FFGUCCYYv'899F!GDMM!GDMCCDKKPWY_D`D`aa8 x"EE  	5%PPPr   r  c           	         |                      |d          |                     |d          |                     |d          |                     |d          |                     |d          |                     |d          gS )N	timestampohlcv)r   r   )r   ohlcvr  s      r   parse_ohlcvzcoinmetro.parse_ohlcv  s~    e[11UC((UC((UC((UC((UC((
 	
r   c                 2   |                                   |                     |          }d|d         i}|||d<   nd|d<   |                     |                     ||                    }|                     |dg           }|                     ||||          S )a^  
        get the list of most recent trades for a particular symbol
        :see: 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$   Nr-  r  tickHistory)r2  r  publicGetExchangeTicksPairFromr8  r9  parse_trades)	r   r   r)  r*  r   r  r;  r   rH  s	            r   fetch_tradeszcoinmetro.fetch_trades$  s     	V$$F4L
 #GFOO !GFO66t{{7F7S7STT: nnX}bAA  feUCCCr   c                     |                                   d}||                     |          }i }|||d<   nd|d<   |                     |                     ||                    }|                     ||||          S )a8  
        fetch all trades made by the user
        :see: 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>`
        Nr)  r   )r2  r  privateGetExchangeFillsSincer8  rJ  r   r   r)  r*  r   r  r;  r   s           r   fetch_my_tradeszcoinmetro.fetch_my_tradesX  s     	[[((F$GG  !GG44T[[&5Q5QRR   65%@@@r   c                    |                      |dd          }|                     ||          }|d         }|                     |g d          }|                     |d          }|                     |d          }|                     |d          }|                     |d          }	|                     |d          }
|                     ||	||                     |          |d |
d ||d d |d	|          S )
Nr   r   )_idseqNum	seqNumberr?  r  qtyorderIDside)r$   orderr?  datetimer   r  rV  takerOrMakerr  r   r	  r   r   )safe_string_2safe_marketsafe_string_nr   r   
safe_tradeiso8601)r   trader  r!  r   r$   r?  priceStringamountStringrW  rV  s              r   parse_tradezcoinmetro.parse_trade}  s   V %%eXv>>!!(F33!'E'E'EFF%%e[99	&&ug66''u55  	22v.."Y//  " 
  
   	r   c                    |                                   |                     |          }d|d         i}|                     |                     ||                    }|                     |di           }|                     |di           }|                     |di           }	||	d}
|                     |
|          }|                     |d          |d<   |S )	at  
        fetches information on open orders with bid(buy) and ask(sell) prices, volumes and other data
        :see: 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asksrS  nonce)r2  r  publicGetExchangeBookPairr8  r   parse_order_bookr   )r   r   r*  r   r  r;  r   rd  rawBidsrawAsksrawOrderbook	orderbooks               r   fetch_order_bookzcoinmetro.fetch_order_book  s     	V$$F4L
 11$++gv2N2NOO8 x44//$r22//$r22
 
 )),??	!..t[AA	'r   r   r      priceKey	amountKeycountOrIdKeyc                 >   t          |                                          }g }t          dt          |                    D ][}|                     ||          }|                     ||          }	|                     ||          }
|                    |	|
g           \|S )Nr   )r   r   r   r   r   r   append)r   bidasksrr  rs  rt  pricesr   r   r`  r  volumes              r   parse_bids_askszcoinmetro.parse_bids_asks  s    gllnn%%q#f++&& 	+ 	+A**6155K$$VQ//E%%g{;;FMM5&/****r   symbolsc                    |                                   |                     |          }|                     |dg           }|                     |dg           }i }t          dt	          |                    D ]'}||         }|                     |d          }	|	|||	<   (t          dt	          |                    D ]R}||         }
|                     |
d          }	|	0|                     ||	i           }|                     |
|          ||	<   St          |                                          }| 	                    ||          S )a9  
        fetches price tickers for multiple markets, statistical information calculated over the past 24 hours for each market
        :see: 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   )
r2  publicGetExchangePricesr   r   r   r   r8  r   valuesparse_tickers)r   r{  r   r   r}  twentyFourHInfostickersObjectr   latestPricer!  twentyFourHInfotickerss               r   fetch_tickerszcoinmetro.fetch_tickers   sR    	//77b xDD??8YCCq#l++,, 	6 	6A&q/K''V<<H#*5h'q#.//00 	T 	TA.q1O''@@H#"oomXrJJ*.++o{*S*Sh'}++--..!!'7333r   c                     |                                   |                     |          }|                     |dg           }|                     ||          S )a  
        fetches the bid and ask price and volume for multiple markets
        :see: 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}  )r2  r  r9  r  )r   r{  r   r   r}  s        r   fetch_bids_askszcoinmetro.fetch_bids_asksL  sT     	//77~~hCC!!,888r   c                    |                      |d          }|                     ||          }|                     |d          }|                      |d          }|                      |d          }|                      |d          }|                      |d          }|                      |d          }	|                      |d          }
|                      |d	          }t          j        |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|          S )Nr   r?  re  rf  rA  rB  r  rD  delta100r   rX  openhighlowcloselast	bidVolume	askVolumevwappreviousClosechanger   average)
baseVolumequoteVolumer   )r   r[  r   r    
string_mulsafe_tickerr^  )r   tickerr  r!  r?  re  rf  r  r  r  r  r  r   s                r   parse_tickerzcoinmetro.parse_tickerY  s   & ##FF33!!(F33%%fk::	vu--vu--,,vs++00%%fc22
  11'u55
 !
fX&!
!
 Y//!
 D	!

 D!
 3!
 T!
 D!
 3!
 !
 3!
 !
 D!
 T!
 d!
  *!!
" t#!
$ %)!
 !
 !
* +  	r   c                 ~    |                                   |                     |          }|                     |          S )a  
        query for balance and get the amount of funds available for trading or funds locked in orders
        :see: https://documenter.getpostman.com/view/3653795/SVfWN6KS#698ae067-43dd-4e19-a0ac-d9ba91381816
        :param dict [params]: extra parameters specific to the exchange API endpoint
        :returns dict: a `balance structure <https://docs.ccxt.com/#/?id=balance-structure>`
        )r2  privateGetUsersBalancesparse_balancer   s      r   fetch_balancezcoinmetro.fetch_balance  s=     	//77!!(+++r   c                    d|i}|                      |ddg          }t          |                                          }t          dt	          |                    D ]h}||         }|                     |          }|                                 }|                     ||i           }	|                     |	|          |d<   |||<   i| 	                    |          S )Nr   TOTALREFr   total)
r6  r   r   r   r   r   accountr   r   safe_balance)
r   r   r   balancesr"  r   r#  r   r  r   s
             r   r  zcoinmetro.parse_balance  s    2 H
 99X'7888==??++q#k**++ 	# 	#A$QJ**:66DllnnGxR@@H#//*EEGG"F4LL  (((r   r   c                 \   |                                   i }|||d<   nd|d<   d}||                     |          }|                     |                     ||                    }|                     |dg           }g }	t          dt          |                    D ]y}
||
         }|                     |d          }|                     |dg           }t          dt          |                    D ]$}||         }||d<   |	                    |           %z| 	                    |	|||          S )	a  
        fetch the history of changes, actions done by the user or operations that altered balance of the user
        :see: 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 entrys 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-structure>`
        Nr)  r  r   r   r   balanceHistoryr#  )
r2  r   "privateGetUsersWalletsHistorySincer8  r   r   r   r   rv  parse_ledger)r   r   r)  r*  r   r;  r   r   ledgerByCurrenciesledgerr   currencyLedgerr#  r  jrawLedgerEntrys                   r   fetch_ledgerzcoinmetro.fetch_ledger  sX    	$GG  "GG}}T**H::4;;wPV;W;WXXr "__XvrBBq#01122 	. 	.A/2N)).*EEJ!__^=MrRRN1c.1122 . .!/!2/9|,n----.   5%@@@r   r   c                    |                      |d          }|                      |d          }|                     |d          }|                     ||          }|                      |dd          }|                     |          \  }}|                     |di           }|                      |d          }	|	d d}
|                      |d          }d }|Ct          j        |d	          rd
}t          j        |          }nt          j        |d	          rd}| 	                    |d | 
                    |          ||d |d |||d d d |
d|          S )Nr?  r#  descriptionr  JSONdatar   )r	  r   r   r   outin)r   r$   r?  rX  	directionr  referenceIdreferenceAccountr  r   r   beforeafterstatusr   )r   r6  safe_currencyparse_ledger_entry_descriptionr   r    	string_lt
string_abs	string_gtsafe_ledger_entry	parse8601)r   itemr   rX  r#  r  r  r  r  feeCostr   r   r  s                r   parse_ledger_entryzcoinmetro.parse_ledger_entry9  s   ##D+66%%dL99
yy|,,%%j(;;&&t]B?? ??LLk??4R88""8V44
 
 !!$11	 -- !!	 +F33"63// ! 	%%11 "& $ '
 '
  !  	r   c                     g }||                     d          }d }d }t          |          }|dk    rF|                     |d                   }|d         dk    r	|d         }n|                     |d          }||gS )N r   r   -rq  )splitr   parse_ledger_entry_typer   )r   r  descriptionArrayr  r  lengths         r   r  z(coinmetro.parse_ledger_entry_description`  s    "*0055%&&A:://0@0CDDD"c)).q1"../?CCk""r   c                 <    dddd}|                      |||          S )Ntransactionr_  )DepositWithdrawr   )r   )r   r  typess      r   r  z!coinmetro.parse_ledger_entry_typeo  s1    $%
 

 tT222r   r  rV  r   r  c                 J   |                                   |                     |          }i }||d<   d}	||                     ||          }	|                     |d          }
|                     |d          }|dk    ru||
t          | j        dz   |z   dz             |R|Pt          j        | 	                    |          | 	                    |	                    }| 
                    |          }
d}|
|                     ||
          }|dk    r&|                     |d         |d	         |	||          }n+|d
k    r%|                     |d	         |d         ||	|          }|                     |d          }|.|                     |d          }|                     |          |d<   |                     |dd          }|0|                     |dg          }|                     ||          |d<   |                     |di           }|                     |dd          }||                     |dg          }||d<   |                     |d          }|/|                     |d          }|                     ||          |d<   |                     |d          }|/|                     |d          }|                     ||          |d<   |                     |          s||d<   |                     |                     ||                    }|                     ||          S )a{  
        create a trade order
        :see: 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 fullfilled, in units of the quote currency, ignored in market orders
        :param dict [params]: extra parameters specific to the exchange API endpoint
        :param float [params.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>`
        	orderTypeNr	  r*  z> createOrder() requires a price or params.cost argument for a z ordersellr   r   buytimeInForcetriggerPrice	stopPriceuserDataclientOrderIdcommentstopLossPricestopLosstakeProfitPrice
takeProfit)r2  r  amount_to_precisionr   r6  r   r$   r    r  number_to_stringparse_to_numericcost_to_precisionhandle_create_order_sideencode_order_time_in_forcerZ  price_to_precisionr   is_emptyprivatePostExchangeOrdersCreater8  parse_order)r   r   r  rV  r   r  r   r  r;  precisedAmountr	  
costStringprecisedCostr  r  r  r  r  r  r   s                       r   create_orderzcoinmetro.create_orderw  s_   * 	V$$
#!55ffEENvv..66**7??DL'2r(ruy(y  }E  )E  F  F  F#&*<$/0E0Ee0L0LdNcNcdrNsNstt
,,Z8811&$??L6>>33F84DfYFWYgiuw~GGU]]33F94EvhGWYeguw~Goofm<<"YYv}55F%)%D%D[%Q%QGM"&&v~{KK	 YYv'788F#'#:#:69#M#MGK ??6:r::$$V_iHHYYv'899F")HY((AA$YYv77F#'#:#:6=#Q#QHZ **63DEE&YYv'899F%)%<%<V_%U%UH\"}}X&& 	+"*GJ77GV8T8TUU: &111r   c                 6    ||d<   ||d<   |||d<   |||d<   |S )NsellingCurrencybuyingCurrency
sellingQty	buyingQty )r   r  r  r  r  r;  s         r   r  z"coinmetro.handle_create_order_side  s=    %4!"$2 !!$.GL! #,GK r   c                 >    ddddd}|                      |||          S )Nr   rq  r      )GTCIOCGTDFOKr   r   r  timeInForceTypess      r   r  z$coinmetro.encode_order_time_in_force  s4    	
 
 /kJJJr   r$   c                    |                                   d|i}d}|                     d|          \  }}|                     |dd          }|                     |d          }d}|s|*|                     |                     ||                    }n)|                     |                     ||                    }|                     |          S )aR  
        cancels an open order
        :see: https://documenter.getpostman.com/view/3653795/SVfWN6KS#eaea86da-16ca-4c56-9f00-5b1cb2ad89f8
        :see: 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>`
        rU  Nr:   r2   F)r2  handle_margin_mode_and_paramsr  r6  %privatePostExchangeOrdersCloseOrderIDr8  %privatePutExchangeOrdersCancelOrderIDr  )r   r$   r   r   r;  
marginModeisMarginr   s           r   cancel_orderzcoinmetro.cancel_order  s     	r
 
;;M6RR>>&(E::68,, 	`
.AA$++gW]B^B^__HHAA$++gW]B^B^__H( )))r   c                    |                                   |                     |d          }|t          | j        dz             d|i}|                     |                     ||                    }|                     |          S )aW  
        closes an open position
        :see: 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>`
        orderIdNz- closePosition() requires a orderId parameterrU  )r2  r   r   r$   r  r8  r  )r   r   rV  r   r  r;  r   s          r   close_positionzcoinmetro.close_position  s     	""6955?#DG.]$]^^^w
 ==dkk'SY>Z>Z[[< )))r   c                    |                                   d}||                     |          }|                     |          }|                     ||||          }t	          dt          |                    D ]}||         }	d|	d<   |S )a1  
        fetch all unfilled currently open orders
        :see: 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  )r2  r  privateGetExchangeOrdersActiveparse_ordersr   r   )
r   r   r)  r*  r   r  r   ordersr   rW  s
             r   fetch_open_orderszcoinmetro.fetch_open_ordersJ  s     	[[((F66v>>""8VUEBBq#f++&& 	% 	%A1IE$E(OOr   c                     |                                   d}||                     |          }i }|||d<   |                     |                     ||                    }|                     ||||          S )al  
        fetches information on multiple canceled and closed orders made by the user
        :see: 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>`
        Nr)  )r2  r  $privateGetExchangeOrdersHistorySincer8  r  rN  s           r    fetch_canceled_and_closed_ordersz*coinmetro.fetch_canceled_and_closed_orders_  s     	[[((F$GG<<T[[RX=Y=YZZ  65%@@@r   c                     |                                   d|i}|                     |                     ||                    }|                     |          S )a  
        fetches information on an order made by the user
        :see: 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>`
        rU  )r2  %privateGetExchangeOrdersStatusOrderIDr8  r  )r   r$   r   r   r;  r   s         r   fetch_orderzcoinmetro.fetch_orders  s]     	r
 ==dkk'SY>Z>Z[[H )))r   c           
         |                      |d          }|                     |d          }d }|du r||                      |d          }d}n/d}n,|                     |d          }|                     |d          }|                     |d          }|                     |d          }|                     |d	          }|                     |d
          }	|                     |d          }
|dk    r|
|	|	dk    r|	}|
|
|
dk    r|
}|                     |dd          }|                     |dd          }||z   }||z   }d }d }|}|}d }d }d }|                     | j        d          }|                     ||          d}|}|}|	}|
}d}n"|                     ||          d}|}|}|
}|	}d}d }||t          j        ||          }|                     ||          }d }|                     |d          }||||         |d d}|                     |dg           }|                     |di           }|                     |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/|          S )0NcreationTimecanceledTcompletionTimerejectedr  r  r  r  	boughtQtysoldQtyr  r   r  r  r  r$   r  r   r  r   r   )r   r	  ratefillsr  r  r  r  r  rU  r  r?  rX  lastTradeTimestamplastFillTimer   r  r  rV  r  r  r  r  r  r   r	  )filled	remainingr   r   tradesr   )r   r   r   r6  r   r   r    
string_divr[  
safe_orderr^  parse_order_time_in_force) r   rW  r  r?  
isCanceledr  r  r  r  r  r  buyingCurrencyIdsellingCurrencyIdbyuingIdPlusSellingIdsellingIdPlusBuyingIdrV  r!  
baseAmountquoteAmountr  r	  feeInBaseOrQuotemarketsByIdr  r   r  r!  r  r  r  r  r  s                                    r   r  zcoinmetro.parse_order  sw   b %%e^<<	__UJ77
  --e5EFF	##%%eX66FIIeX..E{33$$UK88	%%e\::
$$UK88	""5)448!	(=IQTDTDT%	")<7c>>$
++E3CRHH ,,U4ErJJ 03D D 14D D
mmDL$77??;(=>>JD,H$KFD%__[*?@@LD,H#JFD&")@&{J??E!!(F33""5&11&6&B"#34 C
 44??5*b99''{;;((9==**8\BB((:>>  
$""5)44 
] 
  
 Y//	 

 !$"3"3E>"J"J 
 f 
 fX& 
 D 
 499$:K:KES`:a:abb 
 D 
 U 
 L 
  
 ] 
 t 
  j! 
" D# 
$ / 
  
  
0 1  	r   c                 8    g d}|                      |||          S )N)Nr  r  r  r  r  r  s      r   r$  z#coinmetro.parse_order_time_in_force  s-    
 
 
 /kJJJr   c                 v   |                                   |                     |          }|d         }i }|                     ||          ||<   |                     |                     ||                    }|                     |di           }|                     ||          }	|                     |	d|i          S )a  
        create a loan to borrow margin
        :see: 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   )r2  r   currency_to_precisionprivatePutUsersMarginCollateralr8  r   parse_margin_loan)
r   r   r   r   r   r#  r;  r   r   r  s
             r   borrow_cross_marginzcoinmetro.borrow_cross_margin  s     	==&&d^
"88vFF
77GV8T8TUU 8R88,,VX>>{{;f)
   	r   c                 j    |                      |d          }d |                     ||          d d d d |dS )Ncoin)r$   r   r   r   r?  rX  r   )r   r   )r   r   r   r#  s       r   r2  zcoinmetro.parse_margin_loan  sK    %%dF33
//
HEE
 
 	
r   r   GETc                 z   |                      ||                     |                    }d|                     ||          z   }| j        d         |         |z   }	|                     |          }
|i }d|d<   |dk    r| j        | j        | j        | _        | j        | j        | j        | _        |	dk    rd|d<   | j	        
| j	        |d	<   nb|	d
k    r| j        |d<   | j	        
| j	        |d	<   n@d| j        z   |d<   |	
                    d          s|                                  | j        |d<   |dk    s|dk    rd|d<   |                     |          }nt          |
          dk    r|	d|
z   z  }	|	                    d          r/|	dt          |	          dz
           }	|	                    d          /|	|||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)r6  extract_paramsimplode_paramsr   	urlencoder   r   r   r   twofa
startswithcheck_required_credentialsr   endswith)r   pathr   r@  r   rB  rA  r;  endpointr?  querys              r   signzcoinmetro.sign  s   ))FD$7$7$=$=>>,,T6:::is#h.w''?G ) t{'>;
")@![
555)1&:)'+zGG$===)-&:)'+zGG$+4tz+A(~~&FGG 633555-1XGM*&  foo*M'~~g..ZZ1__3;Cll3 	&aC1n%C ll3 	&fdwOOOr   c
                    |d S |dk    r|dk    r||dk    rv| j         dz   |z   }
|                     |d          }|                     | j        d         ||
           |                     | j        d         ||
           t          |
          d S )Nr,         r  messager   r   )r$   r   throw_broadly_matched_exceptionr   throw_exactly_matched_exceptionr   )r   r   reasonr?  r@  rB  rA  r   requestHeadersrequestBodyfeedbackrQ  s               r   handle_errorszcoinmetro.handle_errors  s    4CKKdckkw}t+H&&x;;G001I7T\]]]001I7T\]]])))tr   )N)r   r   rq  )<__name__
__module____qualname__r   r   r   r   r
   r   r  r  r  strr	   r   r=  rF  r   rK  r   rO  rb  r   rp  r   rz  r   r   r  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$  r3  r2  rM  rX  __classcell__)r   s   @r   r"   r"      s:       h h h h hT ') Q QZ Q Q Q Qf $& , ,$v, , , , ,@?f ? ? ? ?B  .   26DW[df =Q =Q# =Qc =QQT =Qkoptku =Q =Q =Q =Q~
 
 
4 
 
 
 
 6:UW 2D 2D3 2Ds 2D# 2D\`af\g 2D 2D 2D 2Dh -1tRV_a #A #Ac #A #AC #A #A #A #AJB B B5 B B B BH :>b 3 3s 33 3Y 3 3 3 3j  9 hq     04B J4 J4W J47 J4 J4 J4 J4X 26b 9 9w 9 9 9 93 36 3V 3 3 3 3j $& 	, 	,( 	, 	, 	, 	,$) $) $) $) $)L (,$TZ\ xA xA xAC xAs xA xA xA xAt% % % % % %N# # #3 3 3 gksu `2 `23 `2i `2y `2RW `2`c `2 `2 `2 `2D hj    K K K 37r +* +*s +*C +* +* +* +*Z =A 0* 0*S 0*	 0* 0* 0* 0*d /3TXac   3 c hlmrhs    * >BPTcgpr A As A# A]` Aw{  }B  xC A A A A( 26b 1* 1*c 1*3 1* 1* 1* 1*fK K K5 K K K KZK K K DF   U    0

 

 

 

 

 

 &eBSW !P !P !P !PF	 	 	 	 	 	 	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   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>rf     s   ( ' ' ' ' ' / / / / / / f  f  f  f  f  f  f  f  f  f  f  f  f  f  f  f  f  f  f  f  f  f  f  f  f  f  f  f  f  f  f  f  f  f  f  f       * * * * * * - - - - - - . . . . . . ' ' ' ' ' ' & & & & & & . . . . . . ) ) ) ) ) ) * * * * * * . . . . . . 9 9 9 9 9 9 % % % % % %v v v v v+ v v v v vr   