# -*- coding: utf-8 -*-

# PLEASE DO NOT EDIT THIS FILE, IT IS GENERATED AND WILL BE OVERWRITTEN:
# https://github.com/ccxt/ccxt/blob/master/CONTRIBUTING.md#how-to-contribute-code

from ccxt.base.exchange import Exchange
from ccxt.abstract.cryptomus import ImplicitAPI
from ccxt.base.types import Any, Balances, Currencies, Int, Market, Num, Order, OrderBook, OrderSide, OrderType, Str, Strings, Ticker, Tickers, Trade, TradingFees
from typing import List
from ccxt.base.errors import ExchangeError
from ccxt.base.errors import ArgumentsRequired
from ccxt.base.errors import InsufficientFunds
from ccxt.base.errors import InvalidOrder
from ccxt.base.decimal_to_precision import TICK_SIZE
from ccxt.base.precise import Precise


class cryptomus(Exchange, ImplicitAPI):

    def describe(self) -> Any:
        return self.deep_extend(super(cryptomus, self).describe(), {
            'id': 'cryptomus',
            'name': 'Cryptomus',
            'countries': ['CA'],
            'rateLimit': 100,  # todo check
            'version': 'v2',
            'certified': False,
            'pro': False,
            'has': {
                'CORS': None,
                'spot': True,
                'margin': False,
                'swap': False,
                'future': False,
                'option': False,
                'addMargin': False,
                'borrowCrossMargin': False,
                'borrowIsolatedMargin': False,
                'borrowMargin': False,
                'cancelAllOrders': False,
                'cancelAllOrdersAfter': False,
                'cancelOrder': True,
                'cancelOrders': False,
                'cancelWithdraw': False,
                'closeAllPositions': False,
                'closePosition': False,
                'createConvertTrade': False,
                'createDepositAddress': False,
                'createMarketBuyOrderWithCost': False,
                'createMarketOrder': False,
                'createMarketOrderWithCost': False,
                'createMarketSellOrderWithCost': False,
                'createOrder': True,
                'createOrderWithTakeProfitAndStopLoss': False,
                'createOrderWithTakeProfitAndStopLossWs': False,
                'createPostOnlyOrder': False,
                'createReduceOnlyOrder': False,
                'createStopLimitOrder': False,
                'createStopLossOrder': False,
                'createStopMarketOrder': False,
                'createStopOrder': False,
                'createTakeProfitOrder': False,
                'createTrailingAmountOrder': False,
                'createTrailingPercentOrder': False,
                'createTriggerOrder': False,
                'fetchAccounts': False,
                'fetchBalance': True,
                'fetchBorrowInterest': False,
                'fetchBorrowRate': False,
                'fetchBorrowRateHistories': False,
                'fetchBorrowRateHistory': False,
                'fetchBorrowRates': False,
                'fetchBorrowRatesPerSymbol': False,
                'fetchCanceledAndClosedOrders': True,
                'fetchCanceledOrders': False,
                'fetchClosedOrder': False,
                'fetchClosedOrders': False,
                'fetchConvertCurrencies': False,
                'fetchConvertQuote': False,
                'fetchConvertTrade': False,
                'fetchConvertTradeHistory': False,
                'fetchCrossBorrowRate': False,
                'fetchCrossBorrowRates': False,
                'fetchCurrencies': True,
                'fetchDepositAddress': False,
                'fetchDeposits': False,
                'fetchDepositsWithdrawals': False,
                'fetchFundingHistory': False,
                'fetchFundingInterval': False,
                'fetchFundingIntervals': False,
                'fetchFundingRate': False,
                'fetchFundingRateHistory': False,
                'fetchFundingRates': False,
                'fetchGreeks': False,
                'fetchIndexOHLCV': False,
                'fetchIsolatedBorrowRate': False,
                'fetchIsolatedBorrowRates': False,
                'fetchIsolatedPositions': False,
                'fetchLedger': False,
                'fetchLeverage': False,
                'fetchLeverages': False,
                'fetchLeverageTiers': False,
                'fetchLiquidations': False,
                'fetchLongShortRatio': False,
                'fetchLongShortRatioHistory': False,
                'fetchMarginAdjustmentHistory': False,
                'fetchMarginMode': False,
                'fetchMarginModes': False,
                'fetchMarketLeverageTiers': False,
                'fetchMarkets': True,
                'fetchMarkOHLCV': False,
                'fetchMarkPrices': False,
                'fetchMyLiquidations': False,
                'fetchMySettlementHistory': False,
                'fetchMyTrades': False,
                'fetchOHLCV': False,
                'fetchOpenInterest': False,
                'fetchOpenInterestHistory': False,
                'fetchOpenInterests': False,
                'fetchOpenOrder': False,
                'fetchOpenOrders': True,
                'fetchOption': False,
                'fetchOptionChain': False,
                'fetchOrder': True,
                'fetchOrderBook': True,
                'fetchOrders': False,
                'fetchOrderTrades': False,
                'fetchPosition': False,
                'fetchPositionHistory': False,
                'fetchPositionMode': False,
                'fetchPositions': False,
                'fetchPositionsForSymbol': False,
                'fetchPositionsHistory': False,
                'fetchPositionsRisk': False,
                'fetchPremiumIndexOHLCV': False,
                'fetchSettlementHistory': False,
                'fetchStatus': False,
                'fetchTicker': False,
                'fetchTickers': True,
                'fetchTime': False,
                'fetchTrades': True,
                'fetchTradingFee': False,
                'fetchTradingFees': True,
                'fetchTransactions': False,
                'fetchTransfers': False,
                'fetchVolatilityHistory': False,
                'fetchWithdrawals': False,
                'reduceMargin': False,
                'repayCrossMargin': False,
                'repayIsolatedMargin': False,
                'repayMargin': False,
                'sandbox': False,
                'setLeverage': False,
                'setMargin': False,
                'setMarginMode': False,
                'setPositionMode': False,
                'transfer': False,
                'withdraw': False,
            },
            'timeframes': {},
            'urls': {
                'logo': 'https://github.com/user-attachments/assets/8e0b1c48-7c01-4177-9224-f1b01d89d7e7',
                'api': {
                    'public': 'https://api.cryptomus.com',
                    'private': 'https://api.cryptomus.com',
                },
                'www': 'https://cryptomus.com',
                'doc': 'https://doc.cryptomus.com/personal',
                'fees': 'https://cryptomus.com/tariffs',  # todo check
                'referral': 'https://app.cryptomus.com/signup/?ref=JRP4yj',  # todo
            },
            'api': {
                'public': {
                    'get': {
                        'v2/user-api/exchange/markets': 1,  # done
                        'v2/user-api/exchange/market/price': 1,  # not used
                        'v1/exchange/market/assets': 1,  # done
                        'v1/exchange/market/order-book/{currencyPair}': 1,  # done
                        'v1/exchange/market/tickers': 1,  # done
                        'v1/exchange/market/trades/{currencyPair}': 1,  # done
                    },
                },
                'private': {
                    'get': {
                        'v2/user-api/exchange/orders': 1,  # done
                        'v2/user-api/exchange/orders/history': 1,  # done
                        'v2/user-api/exchange/account/balance': 1,  # done
                        'v2/user-api/exchange/account/tariffs': 1,  # done
                        'v2/user-api/payment/services': 1,
                        'v2/user-api/payout/services': 1,
                        'v2/user-api/transaction/list': 1,
                    },
                    'post': {
                        'v2/user-api/exchange/orders': 1,  # done
                        'v2/user-api/exchange/orders/market': 1,  # done
                    },
                    'delete': {
                        'v2/user-api/exchange/orders/{orderId}': 1,  # done
                    },
                },
            },
            'fees': {
                'trading': {
                    'percentage': True,
                    'feeSide': 'get',
                    'maker': self.parse_number('0.02'),
                    'taker': self.parse_number('0.02'),
                },
            },
            'options': {
                'createMarketBuyOrderRequiresPrice': True,
                'networks': {
                    'BEP20': 'bsc',
                    'DASH': 'dash',
                    'POLYGON': 'polygon',
                    'ARB': 'arbitrum',
                    'SOL': 'sol',
                    'TON': 'ton',
                    'ERC20': 'eth',
                    'TRC20': 'tron',
                    'LTC': 'ltc',
                    'XMR': 'xmr',
                    'BCH': 'bch',
                    'DOGE': 'doge',
                    'AVAX': 'avalanche',
                    'BTC': 'btc',
                    'RUB': 'rub',
                },
                'networksById': {
                    'bsc': 'BEP20',
                    'dash': 'DASH',
                    'polygon': 'POLYGON',
                    'arbitrum': 'ARB',
                    'sol': 'SOL',
                    'ton': 'TON',
                    'eth': 'ERC20',
                    'tron': 'TRC20',
                    'ltc': 'LTC',
                    'xmr': 'XMR',
                    'bch': 'BCH',
                    'doge': 'DOGE',
                    'avalanche': 'AVAX',
                    'btc': 'BTC',
                    'rub': 'RUB',
                },
                'fetchOrderBook': {
                    'level': 0,  # 0, 1, 2, 4 or 5
                },
            },
            'commonCurrencies': {},
            'exceptions': {
                'exact': {
                    '500': ExchangeError,
                    '6': InsufficientFunds,  # {"code":6,"message":"Insufficient funds."}
                    'Insufficient funds.': InsufficientFunds,
                    'Minimum amount 15 USDT': InvalidOrder,
                    # {"code":500,"message":"Server error."}
                    # {"message":"Minimum amount 15 USDT","state":1}
                    # {"message":"Insufficient funds. USDT wallet balance is 35.21617400.","state":1}
                },
                'broad': {},
            },
            'precisionMode': TICK_SIZE,
            'requiredCredentials': {
                'apiKey': False,
                'uid': True,
            },
            'features': {},
        })

    def fetch_markets(self, params={}) -> List[Market]:
        """
        retrieves data on all markets for the exchange

        https://doc.cryptomus.com/personal/market-cap/tickers

        :param dict [params]: extra parameters specific to the exchange API endpoint
        :returns dict[]: an array of objects representing market data
        """
        response = self.publicGetV2UserApiExchangeMarkets(params)
        #
        #     {
        #         "result": [
        #             {
        #                 "id": "01JHN5EFT64YC4HR9KCGM5M65D",
        #                 "symbol": "POL_USDT",
        #                 "baseCurrency": "POL",
        #                 "quoteCurrency": "USDT",
        #                 "baseMinSize": "1.00000000",
        #                 "quoteMinSize": "5.00000000",
        #                 "baseMaxSize": "50000.00000000",
        #                 "quoteMaxSize": "10000000000.00000000",
        #                 "basePrec": "1",
        #                 "quotePrec": "4"
        #             },
        #             ...
        #         ]
        #     }
        #
        result = self.safe_list(response, 'result', [])
        return self.parse_markets(result)

    def parse_market(self, market: dict) -> Market:
        #
        #     {
        #         "id": "01JHN5EFT64YC4HR9KCGM5M65D",
        #         "symbol": "POL_USDT",
        #         "baseCurrency": "POL",
        #         "quoteCurrency": "USDT",
        #         "baseMinSize": "1.00000000",
        #         "quoteMinSize": "5.00000000",
        #         "baseMaxSize": "50000.00000000",
        #         "quoteMaxSize": "10000000000.00000000",
        #         "basePrec": "1",
        #         "quotePrec": "4"
        #     }
        #
        marketId = self.safe_string(market, 'symbol')
        parts = marketId.split('_')
        baseId = parts[0]
        quoteId = parts[1]
        base = self.safe_currency_code(baseId)
        quote = self.safe_currency_code(quoteId)
        fees = self.safe_dict(self.fees, 'trading')
        return self.safe_market_structure({
            'id': marketId,
            'symbol': base + '/' + quote,
            'base': base,
            'quote': quote,
            'baseId': baseId,
            'quoteId': quoteId,
            'active': True,
            'type': 'spot',
            'subType': None,
            'spot': True,
            'margin': False,
            'swap': False,
            'future': False,
            'option': False,
            'contract': False,
            'settle': None,
            'settleId': None,
            'contractSize': None,
            'linear': None,
            'inverse': None,
            'taker': self.safe_number(fees, 'taker'),
            'maker': self.safe_number(fees, 'maker'),
            'percentage': self.safe_bool(fees, 'percentage'),
            'tierBased': None,
            'feeSide': self.safe_string(fees, 'feeSide'),
            'expiry': None,
            'expiryDatetime': None,
            'strike': None,
            'optionType': None,
            'precision': {
                'amount': self.parse_number(self.parse_precision(self.safe_string(market, 'quotePrec'))),
                'price': self.parse_number(self.parse_precision(self.safe_string(market, 'basePrec'))),
            },
            'limits': {
                'amount': {
                    'min': self.safe_number(market, 'quoteMinSize'),
                    'max': self.safe_number(market, 'quoteMaxSize'),
                },
                'price': {
                    'min': self.safe_number(market, 'baseMinSize'),
                    'max': self.safe_number(market, 'baseMaxSize'),
                },
                'leverage': {
                    'min': None,
                    'max': None,
                },
                'cost': {
                    'min': None,
                    'max': None,
                },
            },
            'created': None,
            'info': market,
        })

    def fetch_currencies(self, params={}) -> Currencies:
        """
        fetches all available currencies on an exchange

        https://doc.cryptomus.com/personal/market-cap/assets

        :param dict [params]: extra parameters specific to the exchange API endpoint
        :returns dict: an associative dictionary of currencies
        """
        response = self.publicGetV1ExchangeMarketAssets(params)
        #
        #     {
        #         'state': '0',
        #         'result': [
        #             {
        #                 'currency_code': 'USDC',
        #                 'network_code': 'bsc',
        #                 'can_withdraw': True,
        #                 'can_deposit': True,
        #                 'min_withdraw': '1.00000000',
        #                 'max_withdraw': '10000000.00000000',
        #                 'max_deposit': '10000000.00000000',
        #                 'min_deposit': '1.00000000'
        #             },
        #             ...
        #         ]
        #     }
        #
        coins = self.safe_list(response, 'result')
        groupedById = self.group_by(coins, 'currency_code')
        keys = list(groupedById.keys())
        result: dict = {}
        for i in range(0, len(keys)):
            id = keys[i]
            code = self.safe_currency_code(id)
            networks = {}
            networkEntries = groupedById[id]
            for j in range(0, len(networkEntries)):
                networkEntry = networkEntries[j]
                networkId = self.safe_string(networkEntry, 'network_code')
                networkCode = self.network_id_to_code(networkId)
                networks[networkCode] = {
                    'id': networkId,
                    'network': networkCode,
                    'limits': {
                        'withdraw': {
                            'min': self.safe_number(networkEntry, 'min_withdraw'),
                            'max': self.safe_number(networkEntry, 'max_withdraw'),
                        },
                        'deposit': {
                            'min': self.safe_number(networkEntry, 'min_deposit'),
                            'max': self.safe_number(networkEntry, 'max_deposit'),
                        },
                    },
                    'active': None,
                    'deposit': self.safe_bool(networkEntry, 'can_withdraw'),
                    'withdraw': self.safe_bool(networkEntry, 'can_deposit'),
                    'fee': None,
                    'precision': None,
                    'info': networkEntry,
                }
            result[code] = self.safe_currency_structure({
                'id': id,
                'code': code,
                'networks': networks,
                'info': networkEntries,
            })
        return result

    def fetch_tickers(self, symbols: Strings = None, params={}) -> Tickers:
        """
        fetches price tickers for multiple markets, statistical information calculated over the past 24 hours for each market

        https://doc.cryptomus.com/personal/market-cap/tickers

        :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>`
        """
        self.load_markets()
        symbols = self.market_symbols(symbols)
        response = self.publicGetV1ExchangeMarketTickers(params)
        #
        #     {
        #         "data": [
        #         {
        #             "currency_pair": "MATIC_USDT",
        #             "last_price": "0.342",
        #             "base_volume": "1676.84092771",
        #             "quote_volume": "573.48033609043"
        #         },
        #         ...
        #     }
        #
        data = self.safe_list(response, 'data')
        return self.parse_tickers(data, symbols)

    def parse_ticker(self, ticker, market: Market = None) -> Ticker:
        #
        #     {
        #         "currency_pair": "XMR_USDT",
        #         "last_price": "158.04829772",
        #         "base_volume": "0.35185785",
        #         "quote_volume": "55.523761128544"
        #     }
        #
        marketId = self.safe_string(ticker, 'currency_pair')
        market = self.safe_market(marketId, market)
        symbol = market['symbol']
        last = self.safe_string(ticker, 'last_price')
        return self.safe_ticker({
            'symbol': symbol,
            'timestamp': None,
            'datetime': None,
            'high': None,
            'low': None,
            'bid': None,
            'bidVolume': None,
            'ask': None,
            'askVolume': None,
            'vwap': None,
            'open': None,
            'close': last,
            'last': last,
            'previousClose': None,
            'change': None,
            'percentage': None,
            'average': None,
            'baseVolume': self.safe_string(ticker, 'base_volume'),
            'quoteVolume': self.safe_string(ticker, 'quote_volume'),
            'info': ticker,
        }, market)

    def fetch_order_book(self, symbol: str, limit: Int = None, params={}) -> OrderBook:
        """
        fetches information on open orders with bid(buy) and ask(sell) prices, volumes and other data

        https://doc.cryptomus.com/personal/market-cap/orderbook

        :param str symbol: unified symbol of the market to fetch the order book for
        :param int [limit]: the maximum amount of order book entries to return
        :param dict [params]: extra parameters specific to the exchange API endpoint
        :param int [params.level]: 0 or 1 or 2 or 3 or 4 or 5 - the level of volume
        :returns dict: A dictionary of `order book structures <https://docs.ccxt.com/#/?id=order-book-structure>` indexed by market symbols
        """
        self.load_markets()
        market = self.market(symbol)
        request: dict = {
            'currencyPair': market['id'],
        }
        level = 0
        level, params = self.handle_option_and_params(params, 'fetchOrderBook', 'level', level)
        request['level'] = level
        response = self.publicGetV1ExchangeMarketOrderBookCurrencyPair(self.extend(request, params))
        #
        #     {
        #         "data": {
        #             "timestamp": "1730138702",
        #             "bids": [
        #                 {
        #                     "price": "2250.00",
        #                     "quantity": "1.00000"
        #                 }
        #             ],
        #             "asks": [
        #                 {
        #                     "price": "2428.69",
        #                     "quantity": "0.16470"
        #                 }
        #             ]
        #         }
        #     }
        #
        data = self.safe_dict(response, 'data', {})
        timestamp = self.safe_timestamp(data, 'timestamp')
        return self.parse_order_book(data, symbol, timestamp, 'bids', 'asks', 'price', 'quantity')

    def fetch_trades(self, symbol: str, since: Int = None, limit: Int = None, params={}) -> List[Trade]:
        """
        get the list of most recent trades for a particular symbol

        https://doc.cryptomus.com/personal/market-cap/trades

        :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(maximum value is 100)
        :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>`
        """
        self.load_markets()
        market = self.market(symbol)
        request: dict = {
            'currencyPair': market['id'],
        }
        response = self.publicGetV1ExchangeMarketTradesCurrencyPair(self.extend(request, params))
        #
        #     {
        #         "data": [
        #             {
        #                 "trade_id": "01J829C3RAXHXHR09HABGQ1YAT",
        #                 "price": "2315.6320500000000000",
        #                 "base_volume": "21.9839623057260000",
        #                 "quote_volume": "0.0094937200000000",
        #                 "timestamp": 1726653796,
        #                 "type": "sell"
        #             }
        #         ]
        #     }
        #
        data = self.safe_list(response, 'data')
        return self.parse_trades(data, market, since, limit)

    def parse_trade(self, trade: dict, market: Market = None) -> Trade:
        #
        #     {
        #         "trade_id": "01J017Q6B3JGHZRP9D2NZHVKFX",
        #         "price": "59498.63487492",
        #         "base_volume": "94.00784310",
        #         "quote_volume": "0.00158000",
        #         "timestamp": 1718028573,
        #         "type": "sell"
        #     }
        #
        timestamp = self.safe_timestamp(trade, 'timestamp')
        return self.safe_trade({
            'id': self.safe_string(trade, 'trade_id'),
            'timestamp': timestamp,
            'datetime': self.iso8601(timestamp),
            'symbol': market['symbol'],
            'side': self.safe_string(trade, 'type'),
            'price': self.safe_string(trade, 'price'),
            'amount': self.safe_string(trade, 'quote_volume'),  # quote_volume is amount
            'cost': self.safe_string(trade, 'base_volume'),  # base_volume is cost
            'takerOrMaker': None,
            'type': None,
            'order': None,
            'fee': {
                'currency': None,
                'cost': None,
            },
            'info': trade,
        }, market)

    def fetch_balance(self, params={}) -> Balances:
        """
        query for balance and get the amount of funds available for trading or funds locked in orders

        https://doc.cryptomus.com/personal/converts/balance

        :param dict [params]: extra parameters specific to the exchange API endpoint
        :returns dict: a `balance structure <https://docs.ccxt.com/#/?id=balance-structure>`
        """
        self.load_markets()
        request: dict = {}
        response = self.privateGetV2UserApiExchangeAccountBalance(self.extend(request, params))
        #
        #     {
        #         "result": [
        #             {
        #                 "ticker": "AVAX",
        #                 "available": "0.00000000",
        #                 "held": "0.00000000"
        #             }
        #         ]
        #     }
        #
        result = self.safe_list(response, 'result', [])
        return self.parse_balance(result)

    def parse_balance(self, balance) -> Balances:
        #
        #     {
        #         "ticker": "AVAX",
        #         "available": "0.00000000",
        #         "held": "0.00000000"
        #     }
        #
        result: dict = {
            'info': balance,
        }
        for i in range(0, len(balance)):
            balanceEntry = balance[i]
            currencyId = self.safe_string(balanceEntry, 'ticker')
            code = self.safe_currency_code(currencyId)
            account = self.account()
            account['free'] = self.safe_string(balanceEntry, 'available')
            account['used'] = self.safe_string(balanceEntry, 'held')
            result[code] = account
        return self.safe_balance(result)

    def create_order(self, symbol: str, type: OrderType, side: OrderSide, amount: float, price: Num = None, params={}) -> Order:
        """
        create a trade order

        https://doc.cryptomus.com/personal/exchange/market-order-creation
        https://doc.cryptomus.com/personal/exchange/limit-order-creation

        :param str symbol: unified symbol of the market to create an order in
        :param str type: 'market' or 'limit' or for spot
        :param str side: 'buy' or 'sell'
        :param float amount: how much of you want to trade in units of the base currency
        :param float [price]: the price that the order is to be fulfilled, in units of the quote currency, ignored in market orders(only for limit orders)
        :param dict [params]: extra parameters specific to the exchange API endpoint
        :param float [params.cost]: *market buy only* the quote quantity that can be used alternative for the amount
        :param str [params.clientOrderId]: a unique identifier for the order(optional)
        :returns dict: an `order structure <https://docs.ccxt.com/#/?id=order-structure>`
        """
        self.load_markets()
        market = self.market(symbol)
        request: dict = {
            'market': market['id'],
            'direction': side,
            'tag': 'ccxt',
        }
        clientOrderId = self.safe_string(params, 'clientOrderId')
        if clientOrderId is not None:
            params = self.omit(params, 'clientOrderId')
            request['client_order_id'] = clientOrderId
        sideBuy = side == 'buy'
        amountToString = self.number_to_string(amount)
        priceToString = self.number_to_string(price)
        cost = None
        cost, params = self.handle_param_string(params, 'cost')
        response = None
        if type == 'market':
            if sideBuy:
                createMarketBuyOrderRequiresPrice = True
                createMarketBuyOrderRequiresPrice, params = self.handle_option_and_params(params, 'createOrder', 'createMarketBuyOrderRequiresPrice', True)
                if createMarketBuyOrderRequiresPrice:
                    if (price is None) and (cost is None):
                        raise InvalidOrder(self.id + ' createOrder() requires the price argument for market buy orders to calculate the total cost to spend(amount * price), alternatively set the createMarketBuyOrderRequiresPrice option of param to False and pass the cost to spend in the amount argument')
                    elif cost is None:
                        cost = Precise.string_mul(amountToString, priceToString)
                else:
                    cost = cost if cost else amountToString
                request['value'] = cost
            else:
                request['quantity'] = amountToString
            response = self.privatePostV2UserApiExchangeOrdersMarket(self.extend(request, params))
        elif type == 'limit':
            if price is None:
                raise ArgumentsRequired(self.id + ' createOrder() requires a price parameter for a ' + type + ' order')
            request['quantity'] = amountToString
            request['price'] = price
            response = self.privatePostV2UserApiExchangeOrders(self.extend(request, params))
        else:
            raise ArgumentsRequired(self.id + ' createOrder() requires a type parameter(limit or market)')
        #
        #     {
        #         "order_id": "01JEXAFCCC5ZVJPZAAHHDKQBNG"
        #     }
        #
        return self.parse_order(response, market)

    def cancel_order(self, id: str, symbol: Str = None, params={}):
        """
        cancels an open limit order

        https://doc.cryptomus.com/personal/exchange/limit-order-cancellation

        :param str id: order id
        :param str symbol: unified symbol of the market the order was made in(not used in cryptomus)
        :param dict [params]: extra parameters specific to the exchange API endpoint
        :returns dict: An `order structure <https://docs.ccxt.com/#/?id=order-structure>`
        """
        self.load_markets()
        request: dict = {}
        request['orderId'] = id
        response = self.privateDeleteV2UserApiExchangeOrdersOrderId(self.extend(request, params))
        #
        #     {
        #         "success": True
        #     }
        #
        return self.safe_order({'info': response})

    def fetch_canceled_and_closed_orders(self, symbol: Str = None, since: Int = None, limit: Int = None, params={}) -> List[Order]:
        """
        fetches information on multiple orders made by the user

        https://doc.cryptomus.com/personal/exchange/history-of-completed-orders

        :param str symbol: unified market symbol of the market orders were made in(not used in cryptomus)
        :param int [since]: the earliest time in ms to fetch orders for(not used in cryptomus)
        :param int [limit]: the maximum number of order structures to retrieve(not used in cryptomus)
        :param dict [params]: extra parameters specific to the exchange API endpoint
        :param str [params.direction]: order direction 'buy' or 'sell'
        :param str [params.order_id]: order id
        :param str [params.client_order_id]: client order id
        :param str [params.limit]: A special parameter that sets the maximum number of records the request will return
        :param str [params.offset]: A special parameter that sets the number of records from the beginning of the list
        :returns Order[]: a list of `order structures <https://docs.ccxt.com/#/?id=order-structure>`
        """
        self.load_markets()
        request: dict = {}
        market = None
        if symbol is not None:
            market = self.market(symbol)
            request['market'] = market['id']
        if limit is not None:
            request['limit'] = limit
        response = self.privateGetV2UserApiExchangeOrdersHistory(self.extend(request, params))
        #
        #     {
        #         "result": [
        #             {
        #                 "id": "01JEXAPY04JDFBVFC2D23BCKMK",
        #                 "type": "market",
        #                 "direction": "sell",
        #                 "symbol": "TRX_USDT",
        #                 "quantity": "67.5400000000000000",
        #                 "filledQuantity": "67.5400000000000000",
        #                 "filledValue": "20.0053480000000000",
        #                 "state": "completed",
        #                 "internalState": "filled",
        #                 "createdAt": "2024-12-12 11:40:19",
        #                 "finishedAt": "2024-12-12 11:40:21",
        #                 "deal": {
        #                     "id": "01JEXAPZ9C9TWENPFZJASZ1YD2",
        #                     "state": "completed",
        #                     "createdAt": "2024-12-12 11:40:21",
        #                     "completedAt": "2024-12-12 11:40:21",
        #                     "averageFilledPrice": "0.2962000000000000",
        #                     "transactions": [
        #                         {
        #                             "id": "01JEXAPZ9C9TWENPFZJASZ1YD3",
        #                             "tradeRole": "taker",
        #                             "filledPrice": "0.2962000000000000",
        #                             "filledQuantity": "67.5400000000000000",
        #                             "filledValue": "20.0053480000000000",
        #                             "fee": "0.0000000000000000",
        #                             "feeCurrency": "USDT",
        #                             "committedAt": "2024-12-12 11:40:21"
        #                         }
        #                     ]
        #                 }
        #             },
        #             ...
        #         ]
        #     }
        #
        result = self.safe_list(response, 'result', [])
        orders = []
        for i in range(0, len(result)):
            order = result[i]
            orders.append(self.parse_order(order, market))
        return orders

    def fetch_open_orders(self, symbol: Str = None, since: Int = None, limit: Int = None, params={}) -> List[Order]:
        """
        fetch all unfilled currently open orders

        https://doc.cryptomus.com/personal/exchange/list-of-active-orders

        :param str symbol: unified market symbol
        :param int [since]: the earliest time in ms to fetch open orders for(not used in cryptomus)
        :param int [limit]: the maximum number of  open orders structures to retrieve(not used in cryptomus)
        :param dict [params]: extra parameters specific to the exchange API endpoint
        :param str [params.direction]: order direction 'buy' or 'sell'
        :param str [params.order_id]: order id
        :param str [params.client_order_id]: client order id
        :param str [params.limit]: A special parameter that sets the maximum number of records the request will return
        :param str [params.offset]: A special parameter that sets the number of records from the beginning of the list
        :returns Order[]: a list of `order structures <https://docs.ccxt.com/#/?id=order-structure>`
        """
        self.load_markets()
        market = None
        if symbol is not None:
            market = self.market(symbol)
        request: dict = {
        }
        if market is not None:
            request['market'] = market['id']
        response = self.privateGetV2UserApiExchangeOrders(self.extend(request, params))
        #
        #     {
        #         "result": [
        #             {
        #                 "id": "01JFFG72CBRDP68K179KC9DSTG",
        #                 "direction": "sell",
        #                 "symbol": "BTC_USDT",
        #                 "price": "102.0130000000000000",
        #                 "quantity": "0.0005000000000000",
        #                 "value": "0.0510065000000000",
        #                 "filledQuantity": "0.0000000000000000",
        #                 "filledValue": "0.0000000000000000",
        #                 "createdAt": "2024-12-19 09:02:51",
        #                 "clientOrderId": "987654321",
        #                 "stopLossPrice": "101.12"
        #             },
        #             ...
        #         ]
        #     }
        result = self.safe_list(response, 'result', [])
        return self.parse_orders(result, market, None, None)

    def parse_order(self, order: dict, market: Market = None) -> Order:
        #
        # createOrder
        #     {
        #         "order_id": "01JEXAFCCC5ZVJPZAAHHDKQBNG"
        #     }
        #
        # fetchOrders
        #     {
        #         "id": "01JEXAPY04JDFBVFC2D23BCKMK",
        #         "type": "market",
        #         "direction": "sell",
        #         "symbol": "TRX_USDT",
        #         "quantity": "67.5400000000000000",
        #         "filledQuantity": "67.5400000000000000",
        #         "filledValue": "20.0053480000000000",
        #         "state": "completed",
        #         "internalState": "filled",
        #         "createdAt": "2024-12-12 11:40:19",
        #         "finishedAt": "2024-12-12 11:40:21",
        #         "deal": {
        #             "id": "01JEXAPZ9C9TWENPFZJASZ1YD2",
        #             "state": "completed",
        #             "createdAt": "2024-12-12 11:40:21",
        #             "completedAt": "2024-12-12 11:40:21",
        #             "averageFilledPrice": "0.2962000000000000",
        #             "transactions": [
        #                 {
        #                     "id": "01JEXAPZ9C9TWENPFZJASZ1YD3",
        #                     "tradeRole": "taker",
        #                     "filledPrice": "0.2962000000000000",
        #                     "filledQuantity": "67.5400000000000000",
        #                     "filledValue": "20.0053480000000000",
        #                     "fee": "0.0000000000000000",
        #                     "feeCurrency": "USDT",
        #                     "committedAt": "2024-12-12 11:40:21"
        #                 }
        #             ]
        #         }
        #     },
        #     ...
        #
        # fetchOpenOrders
        #     {
        #         "id": "01JFFG72CBRDP68K179KC9DSTG",
        #         "direction": "sell",
        #         "symbol": "BTC_USDT",
        #         "price": "102.0130000000000000",
        #         "quantity": "0.0005000000000000",
        #         "value": "0.0510065000000000",
        #         "filledQuantity": "0.0000000000000000",
        #         "filledValue": "0.0000000000000000",
        #         "createdAt": "2024-12-19 09:02:51",
        #         "clientOrderId": "987654321",
        #         "stopLossPrice": "101.12"
        #     }
        #
        id = self.safe_string_2(order, 'order_id', 'id')
        marketId = self.safe_string(order, 'symbol')
        market = self.safe_market(marketId, market)
        dateTime = self.safe_string(order, 'createdAt')
        timestamp = self.parse8601(dateTime)
        deal = self.safe_dict(order, 'deal', {})
        averageFilledPrice = self.safe_number(deal, 'averageFilledPrice')
        type = self.safe_string(order, 'type')
        side = self.safe_string(order, 'direction')
        price = self.safe_number(order, 'price')
        transaction = self.safe_list(deal, 'transactions', [])
        fee = None
        firstTx = self.safe_dict(transaction, 0)
        feeCurrency = self.safe_string(firstTx, 'feeCurrency')
        if feeCurrency is not None:
            fee = {
                'currency': self.safe_currency_code(feeCurrency),
                'cost': self.safe_number(firstTx, 'fee'),
            }
        if price is None:
            price = self.safe_number(firstTx, 'filledPrice')
        amount = self.safe_number(order, 'quantity')
        cost = self.safe_number(order, 'value')
        status = self.parse_order_status(self.safe_string(order, 'state'))
        clientOrderId = self.safe_string(order, 'clientOrderId')
        return self.safe_order({
            'id': id,
            'clientOrderId': clientOrderId,
            'timestamp': timestamp,
            'datetime': self.iso8601(timestamp),
            'lastTradeTimestamp': None,
            'symbol': market['symbol'],
            'type': type,
            'timeInForce': None,
            'postOnly': None,
            'side': side,
            'price': price,
            'stopPrice': self.safe_string(order, 'stopLossPrice'),
            'triggerPrice': self.safe_string(order, 'stopLossPrice'),
            'amount': amount,
            'cost': cost,
            'average': averageFilledPrice,
            'filled': self.safe_string(order, 'filledQuantity'),
            'remaining': None,
            'status': status,
            'fee': fee,
            'trades': None,
            'info': order,
        }, market)

    def parse_order_status(self, status: Str = None) -> Str:
        statuses = {
            'active': 'open',
            'completed': 'closed',
            'partially_completed': 'open',
            'cancelled': 'canceled',
            'expired': 'expired',
            'failed': 'failed',
        }
        return self.safe_string(statuses, status, status)

    def fetch_trading_fees(self, params={}) -> TradingFees:
        """
        fetch the trading fees for multiple markets

        https://trade-docs.coinlist.co/?javascript--nodejs#list-fees

        :param dict [params]: extra parameters specific to the exchange API endpoint
        :returns dict: a dictionary of `fee structures <https://docs.ccxt.com/#/?id=fee-structure>` indexed by market symbols
        """
        response = self.privateGetV2UserApiExchangeAccountTariffs(params)
        #
        #     {
        #         result: {
        #             equivalent_currency_code: 'USD',
        #             current_tariff_step: {
        #                 step: '0',
        #                 from_turnover: '0.00000000',
        #                 maker_percent: '0.08',
        #                 taker_percent: '0.1'
        #             },
        #             tariff_steps: [
        #                 {
        #                     step: '0',
        #                     from_turnover: '0.00000000',
        #                     maker_percent: '0.08',
        #                     taker_percent: '0.1'
        #                 },
        #                 {
        #                     step: '1',
        #                     from_turnover: '100001.00000000',
        #                     maker_percent: '0.06',
        #                     taker_percent: '0.095'
        #                 },
        #                 {
        #                     step: '2',
        #                     from_turnover: '250001.00000000',
        #                     maker_percent: '0.055',
        #                     taker_percent: '0.085'
        #                 },
        #                 {
        #                     step: '3',
        #                     from_turnover: '500001.00000000',
        #                     maker_percent: '0.05',
        #                     taker_percent: '0.075'
        #                 },
        #                 {
        #                     step: '4',
        #                     from_turnover: '2500001.00000000',
        #                     maker_percent: '0.04',
        #                     taker_percent: '0.07'
        #                 }
        #             ],
        #             daily_turnover: '0.00000000',
        #             monthly_turnover: '77.52062617',
        #             circulation_funds: '25.48900443'
        #         }
        #     }
        #
        data = self.safe_dict(response, 'result', {})
        currentFeeTier = self.safe_dict(data, 'current_tariff_step', {})
        makerFee = self.safe_string(currentFeeTier, 'maker_percent')
        takerFee = self.safe_string(currentFeeTier, 'taker_percent')
        makerFee = Precise.string_div(makerFee, '100')
        takerFee = Precise.string_div(takerFee, '100')
        feeTiers = self.safe_list(data, 'tariff_steps', [])
        result: dict = {}
        tiers = self.parse_fee_tiers(feeTiers)
        for i in range(0, len(self.symbols)):
            symbol = self.symbols[i]
            result[symbol] = {
                'info': response,
                'symbol': symbol,
                'maker': self.parse_number(makerFee),
                'taker': self.parse_number(takerFee),
                'percentage': True,
                'tierBased': True,
                'tiers': tiers,
            }
        return result

    def parse_fee_tiers(self, feeTiers, market: Market = None):
        takerFees = []
        makerFees = []
        for i in range(0, len(feeTiers)):
            tier = feeTiers[i]
            turnover = self.safe_number(tier, 'from_turnover')
            taker = self.safe_string(tier, 'taker_percent')
            maker = self.safe_string(tier, 'maker_percent')
            maker = Precise.string_div(maker, '100')
            taker = Precise.string_div(taker, '100')
            makerFees.append([turnover, self.parse_number(maker)])
            takerFees.append([turnover, self.parse_number(taker)])
        return {
            'maker': makerFees,
            'taker': takerFees,
        }

    def sign(self, path, api='public', method='GET', params={}, headers=None, body=None):
        endpoint = self.implode_params(path, params)
        params = self.omit(params, self.extract_params(path))
        url = self.urls['api'][api] + '/' + endpoint
        if api == 'private':
            self.check_required_credentials()
            jsonParams = ''
            headers = {
                'userId': self.uid,
            }
            if method != 'GET':
                body = self.json(params)
                jsonParams = body
                headers['Content-Type'] = 'application/json'
            else:
                query = self.urlencode(params)
                if len(query) != 0:
                    url += '?' + query
            jsonParamsBase64 = self.string_to_base64(jsonParams)
            stringToSign = jsonParamsBase64 + self.secret
            signature = self.hash(self.encode(stringToSign), 'md5')
            headers['sign'] = signature
        else:
            query = self.urlencode(params)
            if len(query) != 0:
                url += '?' + query
        return {'url': url, 'method': method, 'body': body, 'headers': headers}

    def handle_errors(self, httpCode: int, reason: str, url: str, method: str, headers: dict, body: str, response, requestHeaders, requestBody):
        if response is None:
            return None
        if 'code' in response:
            code = self.safe_string(response, 'code')
            feedback = self.id + ' ' + body
            self.throw_exactly_matched_exception(self.exceptions['exact'], code, feedback)
            raise ExchangeError(feedback)
        elif 'message' in response:
            #
            #      {"message":"Minimum amount 15 USDT","state":1}
            #
            message = self.safe_string(response, 'message')
            feedback = self.id + ' ' + body
            self.throw_exactly_matched_exception(self.exceptions['exact'], message, feedback)
            self.throw_broadly_matched_exception(self.exceptions['broad'], message, feedback)
            raise ExchangeError(feedback)  # unknown message
        return None
