
    !:h                         d dl mZ d dlmZ d dl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 d dlmZ d dlmZ d dlmZ d dlmZ d d	lmZ d d
lmZ d dlmZ d dlmZ d dlm Z   G d dee      Z!y)    )Exchange)ImplicitAPIN)AnyBalancesCurrencyIntMarketNumOrder	OrderBook	OrderSide	OrderTypeStrTickerTradeTransaction)List)ExchangeError)ArgumentsRequired)
BadRequest)InsufficientFunds)InvalidOrder)OrderNotFound)	TICK_SIZE)Precisec                   x    e Zd Zdef fdZdddi fdededefdZdddi fdedededee	   fdZ
dddi fdedededee	   fd	Zdddi fdedededee	   fd
ZdefdZd ZdAdedede	fdZi fdee   fdZdedefdZi fdefdZdefdZi fdefdZdAdedefdZdddi fdedededee   fdZdi fdededefdZdAdededefdZ i fdedefdZ!i fdefdZ"dAd edede#fd!Z$ddi fdedededee#   fd"Z%di fded#e&d$e'd%e(d&e)f
d'Z*di fdefd(Z+di fd)edefd*Z,d+i fd,Z-defd-Z.dAd.edede/fd/Z0di fd)edefd0Z1dddi fdedededee/   fd1Z2dddi fdedededee/   fd2Z3dddi fdedededee/   fd3Z4dddi fdededefd4Z5di fded%e(d5ede	fd6Z6d7 Z7d8d9i ddfd:Z8de9d;ed<ed=ed>ed?efd@Z: xZ;S )B
btcmarketsreturnc                    | j                  t        t        |          dddg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
d)d
d*d
i d+d
d,dd-d
d.dd/dd0d
d1dd2dd3dd4dd5d
d6d
d7d
d8d
d9d
d:d
d;d
d
dddddd
d
d
d
dd<d=d>d>d?d@dAdBgdCdDg dEig dFg dGg dHdIgdJd?dKdLdMdNd
d
dd d
d
d
d dddd
dOd
d
d
d
dd
d
dPd d
dQdRdRddSd
d
d
d
dTd
dQd
d
d
dUd
dQdRdRd
d
d
dVd
dQdRdWdRd
d
d
dXdYdidZ	d d d[d d d[d\t        t
        t        t        t        t        t        t        t        d]i d^dd| j                  d_      | j                  d`      dadbdc| j                  dd      | j                  dd      deiidf      S )gNr   zBTC MarketsAUi  v3CORSspotTmarginFswapfutureoption	addMargincancelOrdercancelOrderscloseAllPositionsclosePositioncreateDepositAddresscreateOrdercreateReduceOnlyOrdercreateTriggerOrderfetchBalancefetchBorrowRateHistoriesfetchBorrowRateHistoryfetchClosedOrdersemulatedfetchCrossBorrowRatefetchCrossBorrowRatesfetchDepositAddressfetchDepositAddressesfetchDepositAddressesByNetworkfetchDepositsfetchDepositsWithdrawalsfetchFundingHistoryfetchFundingRatefetchFundingRateHistoryfetchFundingRatesfetchIndexOHLCVfetchIsolatedBorrowRatefetchIsolatedBorrowRatesfetchLeveragefetchMarginModefetchMarketsfetchMarkOHLCVfetchMyTrades
fetchOHLCVfetchOpenInterestHistoryfetchOpenOrders
fetchOrderfetchOrderBookfetchOrdersfetchPositionfetchPositionHistoryfetchPositionModefetchPositionsfetchPositionsForSymbolfetchPositionsHistoryfetchPositionsRisk)fetchPremiumIndexOHLCVfetchTicker	fetchTimefetchTradesfetchTransactionsfetchWithdrawalsreduceMarginsetLeveragesetMarginModesetPositionModewithdrawzOhttps://github.com/user-attachments/assets/8c8d6907-3873-4cc4-ad20-e22fba28247ezhttps://api.btcmarkets.net)publicprivatezhttps://btcmarkets.netz!https://api.btcmarkets.net/doc/v3z!https://github.com/BTCMarkets/API)logoapiwwwdocget)marketszmarkets/{marketId}/tickerzmarkets/{marketId}/tradeszmarkets/{marketId}/orderbookzmarkets/{marketId}/candleszmarkets/tickerszmarkets/orderbookstime)ordersorders/{id}batchorders/{ids}tradesztrades/{id}withdrawalszwithdrawals/{id}depositszdeposits/{id}	transfersztransfers/{id}	addresseszwithdrawal-feesassetszaccounts/me/trading-feeszaccounts/me/withdrawal-limitszaccounts/me/balanceszaccounts/me/transactionszreports/{id})rj   batchordersrn   reports)rj   rk   rl   rk   )rg   postdeleteput1m1h1d)rx   ry   rz   )IOCFOKPOGTD)
marginModetriggerPricetriggerPriceTypetriggerDirectionstopLossPricetakeProfitPriceattachedStopLossTakeProfittimeInForcehedgedleveragemarketBuyRequiresPricemarketBuyByCostselfTradePreventiontrailingicebergd   i )r   limitdaysBack	untilDayssymbolRequired)r   triggerr   r   )r   r   r   r   r   )r   r   r   r   r   r   r      )r   r   r   daysBackCanceledr   r   r   r   r   )	sandboxr.   createOrdersrH   rL   rK   rN   r4   rI   )linearinverse)r#   r%   r&   )InsufficientFundInvalidPriceInvalidAmountMissingArgumentOrderAlreadyCancelledr   OrderStatusIsFinalInvalidPaginationParameter)exactbroadz-0.0005z0.0020)
percentage	tierBasedmakertakerfeesAUDz0.0085)r   r   )idname	countries	rateLimitversionhasurlsrd   
timeframesfeaturesprecisionMode
exceptionsr   options)
deep_extendsuperr   describer   r   r   r   r   parse_number)self	__class__s    I/var/www/html/turnos/venv/lib/python3.12/site-packages/ccxt/btcmarkets.pyr   zbtcmarkets.describe   s   j$ @ B!??? %? 	?
 %? %? U? t? ? $U?  ? '? t? (? %d?  !?" +E#?$ )%%?& $Z'?( ')?* (+?, &u-?. (/?0 1%1?2  3?4 +D5?6 &u7?8 #E9?: *5;?< $U=?> "5??@ *5A?B +EC?D  E?F "5G?H I?J !%K?L  M?N dO?P +EQ?R "4S?T dU?V !$W?X tY?Z  [?\ ']?^ $U_?` !%a?b *5c?d (e?f %eg?h +0#!#%/$( %$!&#( }?B j:; 077  	* &C$2h   %&+(,,0,1).+06:#'#'"&#(	( #($)27+0/3$)#()$, %)&+!$$*%+*.& ',#($)*/	# ',!$#($)*/( ',!$$*%+#($)*/$ ',!$$*,-%+#($)*/	*  #ACJ ##
 ##SM\ ' ):$0%1'1-9%2*62<	 #!**95**84	 !%!2!28!<!%!2!28!<[uE
 u u	    Ncodesincer   c                     | j                          i }|||d<   |||d<   d }|| j                  |      } t        | |      | j                  ||            }| j	                  ||||      S )Nr   after)load_marketscurrencygetattrextendparse_transactions)	r   methodr   r   r   paramsrequestr   responses	            r   fetch_transactions_with_methodz)btcmarkets.fetch_transactions_with_method  s    $GG$GG}}T*H(74(Wf)EF&&x5%HHr   c                 ,    | j                  d||||      S )a  
        fetch history of deposits and withdrawals

        https://docs.btcmarkets.net/v3/#tag/Fund-Management-APIs/paths/~1v3~1transfers/get

        :param str [code]: unified currency code for the currency of the deposit/withdrawals, default is None
        :param int [since]: timestamp in ms of the earliest deposit/withdrawal, default is None
        :param int [limit]: max number of deposit/withdrawals to return, default is None
        :param dict [params]: extra parameters specific to the exchange API endpoint
        :returns dict: a list of `transaction structure <https://docs.ccxt.com/#/?id=transaction-structure>`
        privateGetTransfersr   r   r   r   r   r   s        r   fetch_deposits_withdrawalsz%btcmarkets.fetch_deposits_withdrawals  s!     223H$PUW\^deer   c                 ,    | j                  d||||      S )a#  
        fetch all deposits made to an account

        https://docs.btcmarkets.net/v3/#tag/Fund-Management-APIs/paths/~1v3~1deposits/get

        :param str code: unified currency code
        :param int [since]: the earliest time in ms to fetch deposits for
        :param int [limit]: the maximum number of deposits structures to retrieve
        :param dict [params]: extra parameters specific to the exchange API endpoint
        :returns dict[]: a list of `transaction structures <https://docs.ccxt.com/#/?id=transaction-structure>`
        privateGetDepositsr   r   s        r   fetch_depositszbtcmarkets.fetch_deposits*  s      223GuV[]cddr   c                 ,    | j                  d||||      S )a1  
        fetch all withdrawals made from an account

        https://docs.btcmarkets.net/v3/#tag/Fund-Management-APIs/paths/~1v3~1withdrawals/get

        :param str code: unified currency code
        :param int [since]: the earliest time in ms to fetch withdrawals for
        :param int [limit]: the maximum number of withdrawals structures to retrieve
        :param dict [params]: extra parameters specific to the exchange API endpoint
        :returns dict[]: a list of `transaction structures <https://docs.ccxt.com/#/?id=transaction-structure>`
        privateGetWithdrawalsr   r   s        r   fetch_withdrawalszbtcmarkets.fetch_withdrawals8  s!     223JDRWY^`fggr   statusc                 8    dddddd}| j                  |||      S )Npendingok	cancelledfailed)AcceptedzPending AuthorizationComplete	CancelledFailedsafe_stringr   r   statusess      r   parse_transaction_statusz#btcmarkets.parse_transaction_statusF  s/    !%.$
 &&99r   c                 2    ddd}| j                  |||      S )N
withdrawaldeposit)WithdrawDepositr   )r   typer   s      r   parse_transaction_typez!btcmarkets.parse_transaction_typeP  s&    $ 
 $55r   transactionr   c                    | j                  | j                  |d            }| j                  | j                  |d            }| j                  | j                  |d            }|dk(  rd}| j	                  |di       }| j                  |d      }| j                  |d      }d }	|+|j                  d	      }
t        |
      }|d
kD  r
|
d   }|
d
   }	|}|	}d }d }| j                  |d      }| j                  | j                  |d            }| j                  |d      }| j                  |      }| j                  |d      }|rt        j                  ||      }i d| j                  |d      d|d|d| j                  |      dd d|d|d|d|	d|d|d|d| j                  |      d|d|d|d| j                  |d      d || j                  |      d d|dS ) NcreationTime
lastUpdater   r`   r   paymentDetailtxIdaddress?dt=r   r   feer   	assetNameamountr   txid	timestampdatetimenetwork	addressToaddressFromtagtagTotagFromr   updatedcommentdescription)r   costrate)internalr   info)	parse8601r   r   safe_string_lower	safe_dictsplitlenr   safe_currency_coder   
string_subiso8601r   )r   r   r   r   r   r   cryptoPaymentDetailr   r   r   addressPartsnumPartsr   r   r   r   r   r   
currencyIdr   r   s                        r   parse_transactionzbtcmarkets.parse_transactionW  s   \ NN4#3#3K#PQ	^^D$4$4[,$OP
**4+A+A+v+VW:D"nn[/2N 3V<""#6	B"==0L<(H!|&q/"1o	{E2..t/?/?X/VW%%k;?
&&z2!!+x8''4F
$"";5
D
 
 Y/	

 t
 w
 
 ;
 3
 U
 w
 D
 d''/
 
 f
  z!
" t'']C#
$  ))#.
  1
 	
r   c                 F    | j                  |      }| j                  |      S )a0  
        retrieves data on all markets for btcmarkets

        https://docs.btcmarkets.net/v3/#tag/Market-Data-APIs/paths/~1v3~1markets/get

        :param dict [params]: extra parameters specific to the exchange API endpoint
        :returns dict[]: an array of objects representing market data
        )publicGetMarketsparse_marketsr   r   r   s      r   fetch_marketszbtcmarkets.fetch_markets  s'     ((0 !!(++r   marketc                 .   | j                  |d      }| j                  |d      }| j                  |d      }| j                  |      }| j                  |      }|dz   |z   }| j                  | j                  | j                  di       || j
                        }| j                  | j                  | j                  |d                  }	| j                  |d      }
| j                  |d      }| j                  |d	      }d }|d
k(  r|	}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k(  dddd d |d   |d    d d d d d | j                  | j                  | j                  |d!                  |	d"d d d#|
|d#|d d#d d d#d$d |d%S )&NbaseAssetNamequoteAssetNamemarketId/r   priceDecimalsminOrderAmountmaxOrderAmountr   r   r   symbolbasequotesettlebaseIdquoteIdsettleIdr   r#   Tr$   Fr%   r&   r'   activeOnlinecontractr   r   r   amountDecimals)r   price)minmax)r   r   r-  r  )r   r   r   contractSizeexpiryexpiryDatetimestrike
optionType	precisionlimitscreatedr  )	r   r  
safe_valuer	  r   r   r   parse_precisionsafe_number)r   r  r&  r'  r   r#  r$  r"  r   pricePrecision	minAmount	maxAmountr   minPrices                 r   parse_marketzbtcmarkets.parse_market  st   !!&/:""6+;<fj1&&v.''0e#t~~dllFBGPTPYPYZ**4+?+?@P@PQWYh@i+jk$$V-=>	$$V-=>	!!&(3E>%H2
"2
f2
 D2
 U	2

 d2
 f2
 w2
 2
 F2
 D2
 e2
 E2
 e2
 e2
 v)2
  !2
" d#2
$ ']'] "++D,@,@AQAQRXZjAk,lm'  
 %$
 $
  $ c2
 2	
r   c                 f    | j                  |      }| j                  | j                  |d            S )a_  
        fetches the current integer timestamp in milliseconds from the exchange server

        https://docs.btcmarkets.net/v3/#tag/Misc-APIs/paths/~1v3~1time/get

        :param dict [params]: extra parameters specific to the exchange API endpoint
        :returns int: the current integer timestamp in milliseconds from the exchange server
        r   )publicGetTimer  r   r  s      r   
fetch_timezbtcmarkets.fetch_time  s2     %%f- ~~d..xEFFr   c                 .   d|i}t        dt        |            D ]i  }||   }| j                  |d      }| j                  |      }| j	                         }| j                  |d      |d<   | j                  |d      |d<   |||<   k | j                  |      S )Nr  r   r   lockedusedbalancetotal)ranger  r   r  accountsafe_balance)r   r   resultirF  r  r   rI  s           r   parse_balancezbtcmarkets.parse_balance(  s    )q#h-( 	#AqkG))';?J**:6DllnG"..wAGFO#//CGG"F4L	#   ((r   c                 f    | j                          | j                  |      }| j                  |      S )a  
        query for balance and get the amount of funds available for trading or funds locked in orders

        https://docs.btcmarkets.net/v3/#tag/Account-APIs/paths/~1v3~1accounts~1me~1balances/get

        :param dict [params]: extra parameters specific to the exchange API endpoint
        :returns dict: a `balance structure <https://docs.ccxt.com/#/?id=balance-structure>`
        )r   privateGetAccountsMeBalancesrM  r  s      r   fetch_balancezbtcmarkets.fetch_balance4  s1     	44V<!!(++r   c           	          | j                  | j                  |d            | j                  |d      | j                  |d      | j                  |d      | j                  |d      | j                  |d      gS )Nr   r               )r  r   r:  )r   ohlcvr  s      r   parse_ohlcvzbtcmarkets.parse_ohlcvA  sw     NN4++E156UA&UA&UA&UA&UA&
 	
r   rx   r"  c                 D   | j                          | j                  |      }|d   | j                  | j                  ||      d}|| j	                  |      |d<   |t        |d      |d<   | j                  | j                  ||            }| j                  |||||      S )a  
        fetches historical candlestick data containing the open, high, low, and close price, and the volume of a market

        https://docs.btcmarkets.net/v3/#tag/Market-Data-APIs/paths/~1v3~1markets~1{marketId}~1candles/get

        :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
        :returns int[][]: A list of candles ordered, open, high, low, close, volume
        r   )r  
timeWindowfrom   r   )	r   r  r   r   r  r.  publicGetMarketsMarketIdCandlesr   parse_ohlcvs)	r   r"  	timeframer   r   r   r  r   r   s	            r   fetch_ohlcvzbtcmarkets.fetch_ohlcvU  s     	V$t**4??IyQ
 "ll51GFO"5#GG77GV8TU   69eUKKr   c                    | j                          | j                  |      }d|d   i}| j                  | j                  ||            }| j	                  |dd      }| j                  |||      }| j                  |d      |d<   |S )aa  
        fetches information on open orders with bid(buy) and ask(sell) prices, volumes and other data

        https://docs.btcmarkets.net/v3/#tag/Market-Data-APIs/paths/~1v3~1markets~1{marketId}~1orderbook/get

        :param str symbol: unified symbol of the market to fetch the order book for
        :param int [limit]: the maximum amount of order book entries to return
        :param dict [params]: extra parameters specific to the exchange API endpoint
        :returns dict: A dictionary of `order book structures <https://docs.ccxt.com/#/?id=order-book-structure>` indexed by market symbols
        r  r   
snapshotIdgMbP?nonce)r   r  !publicGetMarketsMarketIdOrderbookr   safe_integer_productparse_order_booksafe_integer)	r   r"  r   r   r  r   r   r   	orderbooks	            r   fetch_order_bookzbtcmarkets.fetch_order_book{  s     	V$t
 99$++gv:VW" --heL	))(FIF	!..xF	'r   tickerc                    | j                  |d      }| j                  ||d      }|d   }| j                  | j                  |d            }| j                  |d      }| j                  |d      }| j                  |d      }| j                  |d      }	| j                  |d	      }
| j                  i d|d|d
| j	                  |      d| j                  |d      d| j                  |d      d| j                  |d      dd d| j                  |d      dd dd dd d|d|dd d|	d|
dd |||d|      S )Nr  -r"  r   	lastPrice	volume24hvolumeQte24hprice24hpricePct24hr   highhigh24hlowbidbestBid	bidVolumeaskbestAsk	askVolumevwapopencloselastpreviousClosechanger   average)
baseVolumequoteVolumer  )r   safe_marketr  safe_tickerr  )r   ri  r  r  r"  r   r}  r  r  r  r   s              r   parse_tickerzbtcmarkets.parse_ticker  s   $ ##FJ7!!(FC8!NN4#3#3FK#HI	4%%fk:
&&v~>!!&*5%%fm<
 !
f!
!
 Y/!
 D$$VY7	!

 4##FE2!
 4##FI6!
 !
 4##FI6!
 !
 D!
 D!
 T!
 D!
 T!
 f!
  *!!
" t#!
$ %&)!
* + 	r   c                     | j                          | j                  |      }d|d   i}| j                  | j                  ||            }| j	                  ||      S )a  
        fetches a price ticker, a statistical calculation with the information calculated over the past 24 hours for a specific market

        https://docs.btcmarkets.net/v3/#tag/Market-Data-APIs/paths/~1v3~1markets~1{marketId}~1ticker/get

        :param str symbol: unified symbol of the market to fetch the ticker for
        :param dict [params]: extra parameters specific to the exchange API endpoint
        :returns dict: a `ticker structure <https://docs.ccxt.com/#/?id=ticker-structure>`
        r  r   r   r  publicGetMarketsMarketIdTickerr   r  r   r"  r   r  r   r   s         r   fetch_tickerzbtcmarkets.fetch_ticker  s`     	V$t
 66t{{7F7ST    622r   c                     | j                          | j                  |      }d|d   i}| j                  | j                  ||            }| j	                  ||      S )Nr   r  r  s         r   fetch_ticker_2zbtcmarkets.fetch_ticker_2  s\    V$&,
 66t{{7F7ST  622r   tradec                 B   | j                  | j                  |d            }| j                  |d      }| j                  ||d      }|d   dk(  r|d   n|d   }| j                  |d      }|dk(  rd	}n|d
k(  rd}| j                  |d      }| j                  |d      }| j                  |d      }	| j                  |d      }
d }| j                  |d      }|||d}| j                  |d      }| j	                  |||| j                  |      |
|d   d |||	d ||d|      S )Nr   r  rk  r$  r   r#  sideBidbuyAsksellr   r-  r   orderIdr   )r  r   liquidityTyper"  )r  r   r   r   orderr"  r   r  r-  r   r  takerOrMakerr   )r  r   r  r  
safe_trader  )r   r  r  r   r  feeCurrencyCoder  r   priceStringamountStringr  r   feeCostStringr  s                 r   parse_tradezbtcmarkets.parse_trade  s`   6 NN4#3#3E;#GH	##E:6!!(FC8.4Wo.F&/VTZ^v.5=DU]DeT*&&ug6''x8""5)4((6$%+C --e_E"Y/X& "( 
  	r   c                     | j                          | j                  |      }d|d   i}| j                  | j                  ||            }| j	                  ||||      S )aH  
        get the list of most recent trades for a particular symbol

        https://docs.btcmarkets.net/v3/#tag/Market-Data-APIs/paths/~1v3~1markets~1{marketId}~1trades/get

        :param str symbol: unified symbol of the market to fetch trades for
        :param int [since]: timestamp in ms of the earliest trade to fetch
        :param int [limit]: the maximum amount of trades to fetch
        :param dict [params]: extra parameters specific to the exchange API endpoint
        :returns Trade[]: a list of `trade structures <https://docs.ccxt.com/#/?id=public-trades>`
        r  r   )r   r  publicGetMarketsMarketIdTradesr   parse_trades)r   r"  r   r   r   r  r   r   s           r   fetch_tradeszbtcmarkets.fetch_trades=  sf     	V$ t
 66t{{7F7ST   65%@@r   r   r  r   r-  c           
      @   | j                          | j                  |      }|d   | j                  ||      |dk(  rdndd}|j                         }	| j	                  | j
                  dddd	d
dd      }
| j                  |
|	|      |d<   d}d}|	dk(  rd}n|	dk(  rd}d}n|	dk(  rd}n|	dk(  rd}|r5|t        | j                  dz   |z   dz         | j                  ||      |d<   |rY| j                  |d      }| j                  |d      }|t        | j                  dz   |z   dz         | j                  ||      |d<   | j                  |d      }|||d<   | j                  |d      }| j                  | j                  ||            }| j                  ||      S )a  
        create a trade order

        https://docs.btcmarkets.net/v3/#tag/Order-Placement-APIs/paths/~1v3~1orders/post

        :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.triggerPrice]: the price at which a trigger order is triggered at
        :returns dict: an `order structure <https://docs.ccxt.com/#/?id=order-structure>`
        r   r  r  r  )r  r   r  
orderTypesLimitr	   Stopz
Stop LimitzTake Profit)r   r  stop
stop limittake profitr   Fr   Tr  r  r  z/ createOrder() requires a price argument for a r  r-  r   z7 createOrder() requires a triggerPrice parameter for a clientOrderId)r   r  amount_to_precisionlowerr8  r   r   r   r   price_to_precisionr:  omitprivatePostOrdersr   parse_order)r   r"  r   r  r   r-  r   r  r   lowercaseTyper  priceIsRequiredtriggerPriceIsRequiredr   r  r   s                   r   create_orderzbtcmarkets.create_orderY  s    	V$t..vv>"emE%
 

__T\\<&(B
 
 **:}dK!&G#"O l*%)""Om+%)"f$%)"}'2c(cfj(jmt(tuu#'#:#:65#I !++FNCLYYv~6F#'2k(knr(ru|(|}}*.*A*A&,*W'((A$'4GO$6?3))$++gv*FG( &11r   c                 T   | j                          t        dt        |            D ]  }t        ||         ||<    d|i}| j	                  | j                  ||            }| j                  |dg       }| j                  |dg       }| j                  ||      }	| j                  |	      S )a  
        cancel multiple orders

        https://docs.btcmarkets.net/v3/#tag/Batch-Order-APIs/paths/~1v3~1batchorders~1{ids}/delete

        :param str[] ids: order ids
        :param str symbol: not used by btcmarkets cancelOrders()
        :param dict [params]: extra parameters specific to the exchange API endpoint
        :returns dict: an list of `order structures <https://docs.ccxt.com/#/?id=order-structure>`
        r   idsr*   unprocessedRequests)	r   rH  r  intprivateDeleteBatchordersIdsr   	safe_listarray_concatparse_orders)
r   r  r"  r   rL  r   r   r*   r  rj   s
             r   cancel_orderszbtcmarkets.cancel_orders  s     	q#c(# 	!AQ[CF	! 3
 33DKK4PQ& ~~hC"nnX7LbQ""<1DE  ((r   r   c                     | j                          d|i}| j                  | j                  ||            }| j                  |      S )au  
        cancels an open order

        https://docs.btcmarkets.net/v3/#operation/cancelOrder

        :param str id: order id
        :param str symbol: not used by btcmarket cancelOrder()
        :param dict [params]: extra parameters specific to the exchange API endpoint
        :returns dict: An `order structure <https://docs.ccxt.com/#/?id=order-structure>`
        r   )r   privateDeleteOrdersIdr   r  r   r   r"  r   r   r   s         r   cancel_orderzbtcmarkets.cancel_order  sL     	"
 --dkk'6.JK ))r   r   c           	         | j                   |   }d}	d}
|d   dk(  rP|d   }	| j                  |      }| j                  |      }t        j                  ||      }| j	                  ||      }
n|d   }	| j                  ||      }
||   }t        j                  | j                  |      |
      }||	|t        | j                  ||            dS )a  
        calculates the presumptive fee that would be charged for an order
        :param str symbol: unified market symbol
        :param str type: not used by btcmarkets.calculateFee
        :param str side: not used by btcmarkets.calculateFee
        :param float amount: how much you want to trade, in units of the base currency on most exchanges, or number of contracts
        :param float price: the price for the order to be filled at, in units of the quote currency
        :param str takerOrMaker: 'taker' or 'maker'
        :param dict params:
        :returns dict: contains the rate, the percentage multiplied to the order amount to obtain the fee amount, and cost, the total value of the fee in units of the quote currency, for the order
        Nr$  r   r#  )r   r   r  r  )rh   number_to_stringr   
string_mulcost_to_precisionr  floatfee_to_precision)r   r"  r   r  r   r-  r  r   r  r   r  r  r  otherUnitsAmountr  rateCosts                   r   calculate_feezbtcmarkets.calculate_fee  s     f%'?e#gH008L//6K&11,L))&2BCDf~H++FF;Dl#%%d&;&;D&A4H  $//AB	
 	
r   c                 <    dddddddd}| j                  |||      S )Nr{  closedcanceledrejected)r   PlacedzPartially MatchedzFully Matchedr   zPartially Cancelledr   r   r   s      r   parse_order_statuszbtcmarkets.parse_order_status  s5    !'%##- 
 &&99r   r  c                    | j                  | j                  |d            }| j                  |d      }| j                  ||d      }| j                  |d      }|dk(  rd}n|dk(  rd}| j                  |d	      }| j                  |d
      }| j                  |d      }| j                  |d      }	| j	                  | j                  |d            }
| j                  |d      }| j                  |d      }| j                  |d      }| j                  |d      }| j                  i d|d|d|d|d| j                  |      dd d|d   d	|d|d|d|d
|d| j                  |d      dd d|dd d|	d |
d d d|      S )Nr   r  rk  r  r  r  r  r  r   r-  r   
openAmountr   r  r  r   postOnlyr  r   r   r   lastTradeTimestampr"  r   r  filled	remaining)r  r   rm   r   )	r  r   r  r  r  	safe_bool
safe_orderr  r:  )r   r  r  r   r  r  r   r-  r   r  r   r   r  r   r  s                  r   r  zbtcmarkets.parse_order"  s+   , NN4#3#3E>#JK	##E:6!!(FC8v.5=DU]D%%eV4  0!!%2$$UL9	(()9)9%)JKeY/((@&&um<>>%4  
E 
" 
 ] 
 	 

 Y/ 
 !$ 
 fX& 
 D 
 ; 
  
 D 
 U 
 D,,UNC 
 D 
 f 
  d! 
" # 
$ + 
, - 	r   c                     | j                          d|i}| j                  | j                  ||            }| j                  |      S )a  
        fetches information on an order made by the user

        https://docs.btcmarkets.net/v3/#operation/getOrderById

        :param str id: the order id
        :param str symbol: not used by btcmarkets fetchOrder
        :param dict [params]: extra parameters specific to the exchange API endpoint
        :returns dict: An `order structure <https://docs.ccxt.com/#/?id=order-structure>`
        r   )r   privateGetOrdersIdr   r  r  s         r   fetch_orderzbtcmarkets.fetch_ordera  sJ     	"
 **4;;w+GH))r   c                     | j                          ddi}d}|| j                  |      }|d   |d<   |||d<   |||d<   | j                  | j                  ||            }| j	                  ||||      S )a,  
        fetches information on multiple orders made by the user

        https://docs.btcmarkets.net/v3/#operation/listOrders

        :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>`
        r   allNr   r  r   r   )r   r  privateGetOrdersr   r  r   r"  r   r   r   r   r  r   s           r   fetch_orderszbtcmarkets.fetch_orderss  s     	e
 [[(F"(,GJ$GG$GG((Wf)EF  65%@@r   c           	      R    ddi}| j                  |||| j                  ||            S )a  
        fetch all unfilled currently open orders

        https://docs.btcmarkets.net/v3/#operation/listOrders

        :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 orders 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>`
        r   r{  )r  r   )r   r"  r   r   r   r   s         r   fetch_open_orderszbtcmarkets.fetch_open_orders  s0     "6*  t{{7F7STTr   c                 P    | j                  ||||      }| j                  |dd      S )a3  
        fetches information on multiple closed orders made by the user

        https://docs.btcmarkets.net/v3/#operation/listOrders

        :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>`
        r   r  )r  	filter_by)r   r"  r   r   r   rj   s         r   fetch_closed_orderszbtcmarkets.fetch_closed_orders  s-     ""65%@~~fh99r   c                     | j                          i }d}|| j                  |      }|d   |d<   |||d<   |||d<   | j                  | j                  ||            }| j	                  ||||      S )a  
        fetch all trades made by the user

        https://docs.btcmarkets.net/v3/#operation/getTrades

        :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
        :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  r   r   )r   r  privateGetTradesr   r  r  s           r   fetch_my_tradeszbtcmarkets.fetch_my_trades  s     	[[(F"(,GJ$GG$GG((Wf)EF8   65%@@r   r   c                 T   | j                  ||      \  }}| j                          | j                  |      }|d   | j                  ||      d}|dk7  r| j	                  |       ||d<   ||dz   |z   |d<   | j                  | j                  ||            }| j                  ||      S )a  
        make a withdrawal

        https://docs.btcmarkets.net/v3/#tag/Fund-Management-APIs/paths/~1v3~1withdrawals/post

        :param str code: unified currency code
        :param float amount: the amount to withdraw
        :param str address: the address to withdraw to
        :param str tag:
        :param dict [params]: extra parameters specific to the exchange API endpoint
        :returns dict: a `transaction structure <https://docs.ccxt.com/#/?id=transaction-structure>`
        r   )currency_idr   r   	toAddressr   )handle_withdraw_tag_and_paramsr   r   currency_to_precisioncheck_addressprivatePostWithdrawalsr   r  )	r   r   r   r   r   r   r   r   r   s	            r   r`   zbtcmarkets.withdraw  s     99#vFV==&#D>00v>
 5=w'#*GK ?#*V#3c#9GK ..t{{7F/KL" %%h99r   c                 "    | j                         S N)milliseconds)r   s    r   rb  zbtcmarkets.nonce  s      ""r   ra   GETc                    d| j                   z   dz   | j                  ||      z   }| j                  | j                  || j	                  |                  }|dk(  r| j                          t        | j                               }	| j                  | j                        }
||z   |	z   }|dk(  s|dk(  r|r.|d| j                  |      z   z  }n| j                  |      }||z  }| j                  | j                  |      |
t        j                  d      }ddd| j                   |	|d	}n|d
k(  r|r|d| j                  |      z   z  }| j"                  d   |   |z   }||||dS )Nr  rb   r  DELETE?base64zapplication/jsonzUTF-8)AcceptzAccept-CharsetzContent-TypezBM-AUTH-APIKEYzBM-AUTH-TIMESTAMPzBM-AUTH-SIGNATUREra   rd   )urlr   bodyheaders)r   implode_paramskeysortr  extract_paramscheck_required_credentialsstrrb  base64_to_binarysecret	urlencodejsonhmacencodehashlibsha512apiKeyr   )r   pathrd   r   r   r  r  r   queryrb  r  auth	signaturer  s                 r   signzbtcmarkets.sign  s[   $s*T-@-@v-NNTYYvt/B/B4/HIJ)++-

%E**4;;7FG#e+D%Vx%7sT^^E%:::Gyy'		$++d"3VW^^XVI,") 2"&++%*%.G H_3!666iis#g-fdwOOr   reasonr  r   r  r  c
                 P   |y | j                  |d      }
| j                  |d      }|
}| j                  dz   |z   }| j                  | j                  d   ||       | j                  | j                  d   |
|       | j	                  | j                  d   ||       t        |      y )Nr   message r   r   )r   r   throw_exactly_matched_exceptionr   throw_broadly_matched_exceptionr   )r   r   r  r  r   r  r  r   requestHeadersrequestBody	errorCoder  feedbacks                r   handle_errorszbtcmarkets.handle_errors,  s    
 $$Xv6	""8Y7 ww}t+H001I7T\]001I9V^_001I7T\]))r   r  )<__name__
__module____qualname__r   r   r   r   r   r   r   r   r   r   r   r   dictr   r  r	   r  r?  rB  r   rM  rP  listrW  r  r_  r   rh  r   r  r  r  r   r  r  r   r   r  r
   r  r  r  r  r  r   r  r  r  r  r  r  r`   rb  r  r  r  __classcell__)r   s   @r   r   r      s   v# vp BFTXgktv I3 Ic Iad I 6:[_hj fs f# fUX fost  pA f *.Dt\^ e3 ec e ecghsct e -1tRV_a hc h hC hfjkvfw h:s :6a
T a
X a
Q\ a
F $& ,$v, ,4A
4 A
F A
F !# Gs G"
) 
) $& ,( ,
 
4 
( 26DW[df $L# $Lc $LQT $Lkoptku $LL :>b $s $3 $Y $L04 0 06 0d 02 33 3f 3B 24 3S 3> >v > >@ 6:UW A3 As A# A\`af\g A8 gksu Y23 Y2i Y2y Y2RW Y2`c Y2v 04B ') ')R 37r *s *C *0 MT\^ 
B
: 
:= =v = =~ 26b *c *3 *$ *.Dt\^ A3 Ac A Acghmcn A6 /3TXac U U3 Uc Uhlmrhs U 154VZce :# :S :PS :jnotju : -1tRV_a 2Ac 2A 2AC 2Ah DHPR *:S *:% *:# *:Wb *:X# &eBSW P:# s  c TX `c r   r   )"ccxt.base.exchanger   ccxt.abstract.btcmarketsr   r  ccxt.base.typesr   r   r   r   r	   r
   r   r   r   r   r   r   r   r   typingr   ccxt.base.errorsr   r   r   r   r   r   ccxt.base.decimal_to_precisionr   ccxt.base.preciser   r    r   r   <module>r'     sS    ( 0  O  O  O  O  * . ' . ) * 4 %f; fr   