
    eiM                       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'dS )    )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dee         f
dZdFd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dFde
dedefdZd
i fdededefdZdGd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dFd 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&dFd&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d0Z0d1 Z1d
i fd2edefd3Z2d
i fded,e,fd4Z3d
d
d
i fdedededee4         fd5Z5d
d
d
i fdedededee4         fd6Z6d
i fd2edefd7Z7dFd8e
dede4fd9Z8d: Z9i fd$ed-e-fd;Z:dFd'e'fd<Z;d=d>i d
d
fd?Z<d$e=d@edAedBedCe
dDefdEZ> xZ?S )H	coinmetroreturnc                    |                      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|                     d          |                     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    L/var/www/html/volatility/venv/lib/python3.11/site-packages/ccxt/coinmetro.pyr   zcoinmetro.describe   sT	   i 6 6 ? ? A 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( ()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 d 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 d 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 d 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 dl %*,1 %$)',$"!&#(!!Gd d 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7!..s33 oqD
@ YAqD
D 0428 EqD
L #&*(,,0,1).+004%*7 7
 $(#'"'#'	( ( #($)$)+/27/4#'/$ $2 %)&+!%$*%)*/& & ',#($)*/	# # ',!%#($)*/( ( ',!%$*%)#($)*/$ $ *.#u= =~ ## 
 ## G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 q	    c                 T   |                      |          }i }t          dt          |                    D ]4}||         }|                     |d          }|                     |          }|                     |d          }d}	|dk    s|dk    s|dk    s|dk    rd}	n|d	k    rd	}	|                     |d
d          }
|dk    rd}
|                     ||||	||                     |d          |                     |d          |                     |d          d|                     | 	                    |
                    | 
                    |d          ddddddi d          ||<   6|                     | j        d          |                     |d          }|| j        d<   |                     | j        dg           }t          |                                          }t          dt          |                    D ]}|                    ||                    || 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RENDER4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55B**2..D&&x88GD&  Gw$6$6'W:L:LPW[cPcPcF"""008EWXXOx"%77 ..:>>>>(LAA NN8]CC!..t/C/CO/T/TUU  $//(CC# 
  $#! !	 	 +9 9  F4LL. ??4<)GHHP!]]6488N;IDL78%)^^DLBace%f%f"">#6#6#8#899O1c/2233 B B&--oa.@AAAA<RDL89r   c                    g }|                     |                     |                     |                     | j        d          '|                     |                                            |}|d         }g }t          dt          |                    D ]C}|                     ||                   }|d         |d         .|                     |           D|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   Nr   basequote)r  publicGetMarketsr  r   r%  r  r  parse_market)r   r  promises	responsesr  r  r  markets           r   fetch_marketszcoinmetro.fetch_markets  s     --f55666??4<)GHHPOOD1133444	Q<  q#h--(( 	" 	"A&&x{33Ff~%)@MM&!!!!r   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          S )NpairbaseIdquoteIdr5   Fr   r'   r   /r'  r(  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'   parsedMarketIdr1  r2  r'  r(  basePrecisionAndLimitsquotePrecisionAndLimitsr5   tradingFeess               r   r*  zcoinmetro.parse_market  s   ff----b11!!.(;;"">9==&&v..''00!%!G!G!O!O"&"H"H"Q"Q%88oodi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@e+f+fgg    
 2*= 
   
 3:>  $ c2+
 2+
 2+
 2 2 2	r   c                    d }d }|                      | j        dg           }t          |          }t          d|          D ][}t          d||z
  dz
            D ]B}||         }||dz            }	t          |          t          |	          k     r|	||<   |||dz   <   C\t          dt          |                    D ]b}||         }
|                    |
          }|dk    r=|                    |
d          }|                     ||          r|dk    r|
}|}n|}|
} nc||Z|                    d          r|                    dd          }d}|                    d          r|                    dd          }d}||d}|S )Nr   r   r    USDTUSD)r1  r2  )r  r   r  r  findreplacein_arrayendswith)r   marketIdr1  r2  currencyIdscurrencyIdsLengthr  jab
currencyId
entryIndexrestIdr  s                 r   r?  zcoinmetro.parse_market_id  s   oodl4SUWXX,,q+,, 	+ 	+A1/!3a788 + +NA&q66CFF??%&KN)*KA&+ q#k**++ 	 	A$QJ!z22JQ!))*b99==55 !Q!+"(!'",E>W_  (( !!))&"55   ''  !))%44
 
 r   c                 &   |                      | j        di           }|                      ||i           }|                      |di           }|                      |di           }|                     |d          }|                     |d          |d}|S )Nr   r	  r  r  r  )r  r7  )r  r   r  )r   rT  
currenciesr  r	  amountLimitsr7  r  s           r   r@  z+coinmetro.parse_market_precision_and_limits?  s    __T\3QSUVV
??:z2>>8R88vx<<##L%88))(K@@ 
 
 r   r   Nr   	timeframesincer   c                 J   |                                   |                     |          }|d         |                     | j        ||          d}d}|9||d<   |1|                     |          dz  }	|                     ||	|z            }n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

        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'   )r0  rZ  Nfromr   z:fromuntiltoz:tocandleHistory)load_marketsr-  r  r   parse_timeframesumsafe_integeromit+publicGetExchangeCandlesPairTimeframeFromToextendr  parse_ohlcvs)r   r   rZ  r[  r   r  r-  requestr^  durationr  r`  s               r   fetch_ohlcvzcoinmetro.fetch_ohlcvK  sC    	V$$4L))$/9iPP
 
 #GFO //	::TAE(:;;%GFO!!&'599YYvy11F!GDMM!GDMCCDKKPWY_D`D`aa8 x"EE  	5%PPPr   c           	         |                      |d          |                     |d          |                     |d          |                     |d          |                     |d          |                     |d          gS )N	timestampohlcv)rd  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 )aX  
        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>`
        r0  r'   Nr]  rG  tickHistory)ra  r-  publicGetExchangeTicksPairFromrg  r  parse_trades)	r   r   r[  r   r  r-  ri  r  rv  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 )a2  
        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>`
        Nr[  r   )ra  r-  privateGetExchangeFillsSincerg  rx  r   r   r[  r   r  r-  ri  r  s           r   fetch_my_tradeszcoinmetro.fetch_my_trades  s     	[[((F$GG  !GG44T[[&5Q5QRR   65%@@@r   tradec                    |                      |dd          }|                     ||          }|d         }|                     |g d          }|                     |d          }|                     |d          }|                     |d          }|                     |d          }	|                     |d          }
|                     ||	||                     |          |d |
d ||d d |d	|          S )
Nr   r0  )_idseqNum	seqNumberrm  r   qtyorderIDside)r'   orderrm  datetimer   r   r  takerOrMakerr   r  r8  r  r  )r  safe_marketsafe_string_nrd  r  
safe_tradeiso8601)r   r~  r-  rN  r   r'   rm  priceStringamountStringr  r  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 )	an  
        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
        r0  r'   bookbidask)bidsasksr  nonce)ra  r-  publicGetExchangeBookPairrg  r  parse_order_bookrd  )r   r   r   r  r-  ri  r  r  rawBidsrawAsksrawOrderbook	orderbooks               r   fetch_order_bookzcoinmetro.fetch_order_book7  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  r  )r   bidasksr  r  r  pricesr  r  r  r   volumes              r   parse_bids_askszcoinmetro.parse_bids_asksn  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 )a3  
        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   r0  )
ra  publicGetExchangePricesr  r  r  r  rg  r  valuesparse_tickers)r   r  r  r  r  twentyFourHInfostickersObjectr  latestPricerN  twentyFourHInfotickerss               r   fetch_tickerszcoinmetro.fetch_tickersx  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

        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  )ra  r  r  r  )r   r  r  r  r  s        r   fetch_bids_askszcoinmetro.fetch_bids_asks  sT     	//77~~hCC!!,888r   tickerc                    |                      |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 )Nr0  rm  r  r  ro  rp  r   rr  delta100r   r  openhighlowcloselast	bidVolume	askVolumevwappreviousClosechanger   average)
baseVolumequoteVolumer  )r  r  rd  r"   
string_mulsafe_tickerr  )r   r  r-  rN  rm  r  r  r  r  r  r  r  r   s                r   parse_tickerzcoinmetro.parse_ticker  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                     |                                   |                     |          }|                     |dg           }|                     |          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  )ra  privateGetUsersWalletsr  parse_balance)r   r  r  r  s       r   fetch_balancezcoinmetro.fetch_balance
  sR     	..v66~~h33!!$'''r   c                    d|i}t          dt          |                    D ]}|                     ||i           }|                     |d          }|                     |          }|                                 }|                     |d          |d<   |                     |d          |d<   |||<   |                     |          S )Nr  r   r  balancetotalreservedused)r  r  	safe_dictr  r  accountsafe_balance)r   balancesr  r  balanceEntryrT  r  r  s           r   r  zcoinmetro.parse_balance  s    0 H
 q#h--(( 	# 	#A>>(Ar::L)),
CCJ**:66DllnnG#//iHHGG"..|ZHHGFO"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 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-entry-structure>`
        Nr[  rG  r  r   r  balanceHistoryrT  )
ra  r  "privateGetUsersWalletsHistorySincerg  r  r  r  r  r  parse_ledger)r   r  r[  r   r  ri  r  r  ledgerByCurrenciesledgerr  currencyLedgerrT  r  rQ  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   itemr  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 )Nrm  rT  descriptionrG  JSONdatar   )r8  r  r  r   outin)r  r'   rm  r  	directionr  referenceIdreferenceAccountr   r  r  beforeafterstatusr  )r  re  safe_currencyparse_ledger_entry_descriptionr  r"   	string_lt
string_abs	string_gtsafe_ledger_entry	parse8601)r   r  r  r  rT  r  r   r  r  feeCostr  r  r  s                r   parse_ledger_entryzcoinmetro.parse_ledger_entry  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   -r  )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_type  s1    $%
 

 tT222r   r   r  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 )at  
        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>`
        	orderTypeNr8  r   z> createOrder() requires a price or params.cost argument for a z ordersellr1  r2  buyr   r   	stopPriceuserDataclientOrderIdcommentr   stopLossr   
takeProfit)ra  r-  amount_to_precisionr  re  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privatePostExchangeOrdersCreaterg  parse_order)r   r   r   r  r  r   r  r-  ri  formattedAmountr8  
costStringprecisedCostr   r   r  r	  r   r   r  s                       r   create_orderzcoinmetro.create_order  sk   . 	V$$
#"66vvFFOvv..66**7??DL'2r(ruy(y  }E  )E  F  F  F#&*<$/0E0Ee0L0LdNcNcdsNtNtuu
,,Z8811&$??L6>>33F84DfYFWYhjvx  A  AGGU]]33F94EvhGWYegvx  A  AGoofm<<"YYv}55F%)%D%D[%Q%QGM"))&.+NN#YYv'788F#'#:#:6<#P#PGK ??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  ri  s         r   r  z"coinmetro.handle_create_order_sideZ  s=    %4!"$2 !!$.GL! #,GK r   c                 >    ddddd}|                      |||          S )Nr   r  r      )GTCr   r   r   r  r   r   timeInForceTypess      r   r  z$coinmetro.encode_order_time_in_forcec  s4    	"
 "
 /kJJJr   r'   c                    |                                   d|i}d}|                     d|          \  }}|                     |dd          }|                     |d          }d}|s|*|                     |                     ||                    }n)|                     |                     ||                    }|                     |          S )aF  
        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)ra  handle_margin_mode_and_paramsr  re  %privatePostExchangeOrdersCloseOrderIDrg  %privatePutExchangeOrdersCancelOrderIDr  )r   r'   r   r  ri  r   isMarginr  s           r   cancel_orderzcoinmetro.cancel_orderl  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 )aQ  
        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>`
        orderIdNz- closePosition() requires a orderId parameterr  )ra  r  r   r'   r(  rg  r  )r   r   r  r  r-  ri  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 )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  )ra  r-  privateGetExchangeOrdersActiveparse_ordersr  r  )
r   r   r[  r   r  r-  r  ordersr  r  s
             r   fetch_open_orderszcoinmetro.fetch_open_orders  s     	[[((F66v>>""8VUEBBq#f++&& 	% 	%A1IE$E(OOr   c                     |                                   d}||                     |          }i }|||d<   |                     |                     ||                    }|                     ||||          S )af  
        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>`
        Nr[  )ra  r-  $privateGetExchangeOrdersHistorySincerg  r1  r|  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

        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  )ra  %privateGetExchangeOrdersStatusOrderIDrg  r  )r   r'   r   r  ri  r  s         r   fetch_orderzcoinmetro.fetch_order  s]     	r
 ==dkk'SY>Z>Z[[H )))r   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          }| 	                    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/|          S )0NcreationTimecanceledTcompletionTimerejectedr  r  r  r  	boughtQtysoldQtyr-  r   r  rG  r  r'   r  r'  r  r(  r   )r  r8  ratefillsr  r	  r  r
  r  r  rm  r  lastTradeTimestamplastFillTimer   r   r   r  r   r   r  r   r   r  r  r8  )filled	remainingr  r   tradesr  )rd  r  r  re  r  r   r"   
string_divr  
safe_orderr  parse_order_time_in_force)r   r  r-  rm  
isCanceledr  r   r  r  r?  r@  buyingCurrencyIdsellingCurrencyIdbyuingIdPlusSellingIdsellingIdPlusBuyingIdr  rN  
baseAmountquoteAmountrE  r8  feeInBaseOrQuotemarketsByIdr   r  r  rG  r  r  r   r   s                                  r   r  zcoinmetro.parse_order1  sr   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 
 D,,UK@@ 
  
 ] 
 t 
  j! 
" D# 
$ / 
  
  
0 1  	r   c                 8    g d}|                      |||          S )N)Nr"  r   r   r   r#  r$  s      r   rJ  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

        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  )ra  r  currency_to_precisionprivatePutUsersMarginCollateralrg  r  parse_margin_loan)
r   r  r  r  r  rT  ri  r  r  r  s
             r   borrow_cross_marginzcoinmetro.borrow_cross_marginG  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 )Nr   )r'   r  r  r   rm  r  r  )r  r  )r   r  r  rT  s       r   rX  zcoinmetro.parse_margin_loana  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 )Nr3  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)re  extract_paramsimplode_paramsr   	urlencoder   r   r   r   twofa
startswithcheck_required_credentialsr  rM  )r   pathr   re  r  rg  rf  ri  endpointrd  querys              r   signzcoinmetro.signm  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   reasonrd  re  rg  rf  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  rr  rd  re  rg  rf  r  requestHeadersrequestBodyfeedbackrv  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   r  )@__name__
__module____qualname__r   r   r   r%  r   r   r.  dictr*  r?  r@  strr
   r  rk  rt  r   ry  r   r}  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   r3  r6  r9  r  rJ  rY  rX  rq  intr|  __classcell__)r   s   @r   r$   r$      s       r# r r r r r rh	 ') b bZ b b b bH $& % %$v, % % % %N=4 =F = = = =~& & &P
 
 
 9=4^bkm ?Q ?Q# ?Q# ?QS ?QX[ ?Qrvw{r| ?Q ?Q ?Q ?QB
 
 
4 
 
 
 
 6:UW 4D 4D3 4Ds 4D# 4D\`af\g 4D 4D 4D 4Dl -1tRV_a %A %Ac %A %AC %A %A %A %ANB B Bv B B B B BH :>b 5 5s 53 5Y 5 5 5 5n  9 hq     04B L4 L4W L47 L4 L4 L4 L4\ 26b 9 9w 9 9 9 93 34 3 36 3 3 3 3j $& ( (( ( ( ( (") ") ") ") ")H (,$TZ\ zA zA zAC zAs zAaefqar zA zA zA zAx% %t %x %; % % % %N# # #3 3 3 gksu b2 b23 b2i b2y b2RW b2`c b2 b2 b2 b2H hj    K K K 37r -* -*s -*C -* -* -* -*^ =A 2* 2*S 2*	 2* 2* 2* 2*h /3TXac   3 c hlmrhs    . >BPTcgpr A As A# A]` Aw{  }B  xC A A A A, 26b 3* 3*c 3*3 3* 3* 3* 3*jJ J Jv J J J J JXK K K DF   U    4

 

 

 

 

 

 &eBSW !P !P !P !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     s3   ( ' ' ' ' ' / / / / / / x  x  x  x  x  x  x  x  x  x  x  x  x  x  x  x  x  x  x  x  x  x  x  x  x  x  x  x  x  x  x  x  x  x  x  x  x  x  x  x       * * * * * * - - - - - - . . . . . . ' ' ' ' ' ' & & & & & & . . . . . . ) ) ) ) ) ) * * * * * * . . . . . . 4 4 4 4 4 4 % % % % % %B B B B B+ B B B B Br   