<?php

namespace ccxt;

// 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

use Exception; // a common import
use ccxt\abstract\cryptomus as Exchange;

class cryptomus extends Exchange {

    public function describe(): mixed {
        return $this->deep_extend(parent::describe(), array(
            'id' => 'cryptomus',
            'name' => 'Cryptomus',
            'countries' => array( 'CA' ),
            'rateLimit' => 100, // todo check
            'version' => 'v2',
            'certified' => false,
            'pro' => false,
            'has' => array(
                'CORS' => null,
                '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' => array(),
            'urls' => array(
                'logo' => 'https://github.com/user-attachments/assets/8e0b1c48-7c01-4177-9224-f1b01d89d7e7',
                'api' => array(
                    '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' => array(
                'public' => array(
                    'get' => array(
                        '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' => array(
                    'get' => array(
                        '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' => array(
                        'v2/user-api/exchange/orders' => 1, // done
                        'v2/user-api/exchange/orders/market' => 1, // done
                    ),
                    'delete' => array(
                        'v2/user-api/exchange/orders/{orderId}' => 1, // done
                    ),
                ),
            ),
            'fees' => array(
                'trading' => array(
                    'percentage' => true,
                    'feeSide' => 'get',
                    'maker' => $this->parse_number('0.02'),
                    'taker' => $this->parse_number('0.02'),
                ),
            ),
            'options' => array(
                'createMarketBuyOrderRequiresPrice' => true,
                'networks' => array(
                    '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' => array(
                    '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' => array(
                    'level' => 0, // 0, 1, 2, 4 or 5
                ),
            ),
            'commonCurrencies' => array(),
            'exceptions' => array(
                'exact' => array(
                    '500' => '\\ccxt\\ExchangeError',
                    '6' => '\\ccxt\\InsufficientFunds', // array("code":6,"message":"Insufficient funds.")
                    'Insufficient funds.' => '\\ccxt\\InsufficientFunds',
                    'Minimum amount 15 USDT' => '\\ccxt\\InvalidOrder',
                    // array("code":500,"message":"Server error.")
                    // array("message":"Minimum amount 15 USDT","state":1)
                    // array("message":"Insufficient funds. USDT wallet balance is 35.21617400.","state":1)
                ),
                'broad' => array(),
            ),
            'precisionMode' => TICK_SIZE,
            'requiredCredentials' => array(
                'apiKey' => false,
                'uid' => true,
            ),
            'features' => array(),
        ));
    }

    public function fetch_markets($params = array ()): array {
        /**
         * retrieves data on all markets for the exchange
         *
         * @see https://doc.cryptomus.com/personal/market-cap/tickers
         *
         * @param {array} [$params] extra parameters specific to the exchange API endpoint
         * @return {array[]} an array of objects representing market data
         */
        $response = $this->publicGetV2UserApiExchangeMarkets ($params);
        //
        //     {
        //         "result" => array(
        //             array(
        //                 "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 = $this->safe_list($response, 'result', array());
        return $this->parse_markets($result);
    }

    public function parse_market(array $market): array {
        //
        //     {
        //         "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 = $this->safe_string($market, 'symbol');
        $parts = explode('_', $marketId);
        $baseId = $parts[0];
        $quoteId = $parts[1];
        $base = $this->safe_currency_code($baseId);
        $quote = $this->safe_currency_code($quoteId);
        $fees = $this->safe_dict($this->fees, 'trading');
        return $this->safe_market_structure(array(
            'id' => $marketId,
            'symbol' => $base . '/' . $quote,
            'base' => $base,
            'quote' => $quote,
            'baseId' => $baseId,
            'quoteId' => $quoteId,
            'active' => true,
            'type' => 'spot',
            'subType' => null,
            'spot' => true,
            'margin' => false,
            'swap' => false,
            'future' => false,
            'option' => false,
            'contract' => false,
            'settle' => null,
            'settleId' => null,
            'contractSize' => null,
            'linear' => null,
            'inverse' => null,
            'taker' => $this->safe_number($fees, 'taker'),
            'maker' => $this->safe_number($fees, 'maker'),
            'percentage' => $this->safe_bool($fees, 'percentage'),
            'tierBased' => null,
            'feeSide' => $this->safe_string($fees, 'feeSide'),
            'expiry' => null,
            'expiryDatetime' => null,
            'strike' => null,
            'optionType' => null,
            'precision' => array(
                'amount' => $this->parse_number($this->parse_precision($this->safe_string($market, 'quotePrec'))),
                'price' => $this->parse_number($this->parse_precision($this->safe_string($market, 'basePrec'))),
            ),
            'limits' => array(
                'amount' => array(
                    'min' => $this->safe_number($market, 'quoteMinSize'),
                    'max' => $this->safe_number($market, 'quoteMaxSize'),
                ),
                'price' => array(
                    'min' => $this->safe_number($market, 'baseMinSize'),
                    'max' => $this->safe_number($market, 'baseMaxSize'),
                ),
                'leverage' => array(
                    'min' => null,
                    'max' => null,
                ),
                'cost' => array(
                    'min' => null,
                    'max' => null,
                ),
            ),
            'created' => null,
            'info' => $market,
        ));
    }

    public function fetch_currencies($params = array ()): ?array {
        /**
         * fetches all available currencies on an exchange
         *
         * @see https://doc.cryptomus.com/personal/market-cap/assets
         *
         * @param {array} [$params] extra parameters specific to the exchange API endpoint
         * @return {array} an associative dictionary of currencies
         */
        $response = $this->publicGetV1ExchangeMarketAssets ($params);
        //
        //     {
        //         'state' => '0',
        //         'result' => array(
        //             array(
        //                 '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 = $this->safe_list($response, 'result');
        $groupedById = $this->group_by($coins, 'currency_code');
        $keys = is_array($groupedById) ? array_keys($groupedById) : array();
        $result = array();
        for ($i = 0; $i < count($keys); $i++) {
            $id = $keys[$i];
            $code = $this->safe_currency_code($id);
            $networks = array();
            $networkEntries = $groupedById[$id];
            for ($j = 0; $j < count($networkEntries); $j++) {
                $networkEntry = $networkEntries[$j];
                $networkId = $this->safe_string($networkEntry, 'network_code');
                $networkCode = $this->network_id_to_code($networkId);
                $networks[$networkCode] = array(
                    'id' => $networkId,
                    'network' => $networkCode,
                    'limits' => array(
                        'withdraw' => array(
                            'min' => $this->safe_number($networkEntry, 'min_withdraw'),
                            'max' => $this->safe_number($networkEntry, 'max_withdraw'),
                        ),
                        'deposit' => array(
                            'min' => $this->safe_number($networkEntry, 'min_deposit'),
                            'max' => $this->safe_number($networkEntry, 'max_deposit'),
                        ),
                    ),
                    'active' => null,
                    'deposit' => $this->safe_bool($networkEntry, 'can_withdraw'),
                    'withdraw' => $this->safe_bool($networkEntry, 'can_deposit'),
                    'fee' => null,
                    'precision' => null,
                    'info' => $networkEntry,
                );
            }
            $result[$code] = $this->safe_currency_structure(array(
                'id' => $id,
                'code' => $code,
                'networks' => $networks,
                'info' => $networkEntries,
            ));
        }
        return $result;
    }

    public function fetch_tickers(?array $symbols = null, $params = array ()): array {
        /**
         * fetches price tickers for multiple markets, statistical information calculated over the past 24 hours for each market
         *
         * @see https://doc.cryptomus.com/personal/market-cap/tickers
         *
         * @param {string[]} [$symbols] unified $symbols of the markets to fetch the ticker for, all market tickers are returned if not assigned
         * @param {array} [$params] extra parameters specific to the exchange API endpoint
         * @return {array} a dictionary of ~@link https://docs.ccxt.com/#/?id=ticker-structure ticker structures~
         */
        $this->load_markets();
        $symbols = $this->market_symbols($symbols);
        $response = $this->publicGetV1ExchangeMarketTickers ($params);
        //
        //     {
        //         "data" => [
        //         array(
        //             "currency_pair" => "MATIC_USDT",
        //             "last_price" => "0.342",
        //             "base_volume" => "1676.84092771",
        //             "quote_volume" => "573.48033609043"
        //         ),
        //         ...
        //     }
        //
        $data = $this->safe_list($response, 'data');
        return $this->parse_tickers($data, $symbols);
    }

    public function parse_ticker($ticker, ?array $market = null): array {
        //
        //     {
        //         "currency_pair" => "XMR_USDT",
        //         "last_price" => "158.04829772",
        //         "base_volume" => "0.35185785",
        //         "quote_volume" => "55.523761128544"
        //     }
        //
        $marketId = $this->safe_string($ticker, 'currency_pair');
        $market = $this->safe_market($marketId, $market);
        $symbol = $market['symbol'];
        $last = $this->safe_string($ticker, 'last_price');
        return $this->safe_ticker(array(
            'symbol' => $symbol,
            'timestamp' => null,
            'datetime' => null,
            'high' => null,
            'low' => null,
            'bid' => null,
            'bidVolume' => null,
            'ask' => null,
            'askVolume' => null,
            'vwap' => null,
            'open' => null,
            'close' => $last,
            'last' => $last,
            'previousClose' => null,
            'change' => null,
            'percentage' => null,
            'average' => null,
            'baseVolume' => $this->safe_string($ticker, 'base_volume'),
            'quoteVolume' => $this->safe_string($ticker, 'quote_volume'),
            'info' => $ticker,
        ), $market);
    }

    public function fetch_order_book(string $symbol, ?int $limit = null, $params = array ()): array {
        /**
         * fetches information on open orders with bid (buy) and ask (sell) prices, volumes and other $data
         *
         * @see https://doc.cryptomus.com/personal/market-cap/orderbook
         *
         * @param {string} $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 {array} [$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
         * @return {array} A dictionary of ~@link https://docs.ccxt.com/#/?id=order-book-structure order book structures~ indexed by $market symbols
         */
        $this->load_markets();
        $market = $this->market($symbol);
        $request = array(
            'currencyPair' => $market['id'],
        );
        $level = 0;
        list($level, $params) = $this->handle_option_and_params($params, 'fetchOrderBook', 'level', $level);
        $request['level'] = $level;
        $response = $this->publicGetV1ExchangeMarketOrderBookCurrencyPair ($this->extend($request, $params));
        //
        //     {
        //         "data" => {
        //             "timestamp" => "1730138702",
        //             "bids" => array(
        //                 {
        //                     "price" => "2250.00",
        //                     "quantity" => "1.00000"
        //                 }
        //             ),
        //             "asks" => array(
        //                 {
        //                     "price" => "2428.69",
        //                     "quantity" => "0.16470"
        //                 }
        //             )
        //         }
        //     }
        //
        $data = $this->safe_dict($response, 'data', array());
        $timestamp = $this->safe_timestamp($data, 'timestamp');
        return $this->parse_order_book($data, $symbol, $timestamp, 'bids', 'asks', 'price', 'quantity');
    }

    public function fetch_trades(string $symbol, ?int $since = null, ?int $limit = null, $params = array ()): array {
        /**
         * get the list of most recent trades for a particular $symbol
         *
         * @see https://doc.cryptomus.com/personal/market-cap/trades
         *
         * @param {string} $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 {array} [$params] extra parameters specific to the exchange API endpoint
         * @return {Trade[]} a list of ~@link https://docs.ccxt.com/#/?id=public-trades trade structures~
         */
        $this->load_markets();
        $market = $this->market($symbol);
        $request = array(
            'currencyPair' => $market['id'],
        );
        $response = $this->publicGetV1ExchangeMarketTradesCurrencyPair ($this->extend($request, $params));
        //
        //     {
        //         "data" => array(
        //             {
        //                 "trade_id" => "01J829C3RAXHXHR09HABGQ1YAT",
        //                 "price" => "2315.6320500000000000",
        //                 "base_volume" => "21.9839623057260000",
        //                 "quote_volume" => "0.0094937200000000",
        //                 "timestamp" => 1726653796,
        //                 "type" => "sell"
        //             }
        //         )
        //     }
        //
        $data = $this->safe_list($response, 'data');
        return $this->parse_trades($data, $market, $since, $limit);
    }

    public function parse_trade(array $trade, ?array $market = null): array {
        //
        //     {
        //         "trade_id" => "01J017Q6B3JGHZRP9D2NZHVKFX",
        //         "price" => "59498.63487492",
        //         "base_volume" => "94.00784310",
        //         "quote_volume" => "0.00158000",
        //         "timestamp" => 1718028573,
        //         "type" => "sell"
        //     }
        //
        $timestamp = $this->safe_timestamp($trade, 'timestamp');
        return $this->safe_trade(array(
            'id' => $this->safe_string($trade, 'trade_id'),
            'timestamp' => $timestamp,
            'datetime' => $this->iso8601($timestamp),
            'symbol' => $market['symbol'],
            'side' => $this->safe_string($trade, 'type'),
            'price' => $this->safe_string($trade, 'price'),
            'amount' => $this->safe_string($trade, 'quote_volume'), // quote_volume is amount
            'cost' => $this->safe_string($trade, 'base_volume'), // base_volume is cost
            'takerOrMaker' => null,
            'type' => null,
            'order' => null,
            'fee' => array(
                'currency' => null,
                'cost' => null,
            ),
            'info' => $trade,
        ), $market);
    }

    public function fetch_balance($params = array ()): array {
        /**
         * query for balance and get the amount of funds available for trading or funds locked in orders
         *
         * @see https://doc.cryptomus.com/personal/converts/balance
         *
         * @param {array} [$params] extra parameters specific to the exchange API endpoint
         * @return {array} a ~@link https://docs.ccxt.com/#/?id=balance-structure balance structure~
         */
        $this->load_markets();
        $request = array();
        $response = $this->privateGetV2UserApiExchangeAccountBalance ($this->extend($request, $params));
        //
        //     {
        //         "result" => array(
        //             {
        //                 "ticker" => "AVAX",
        //                 "available" => "0.00000000",
        //                 "held" => "0.00000000"
        //             }
        //         )
        //     }
        //
        $result = $this->safe_list($response, 'result', array());
        return $this->parse_balance($result);
    }

    public function parse_balance($balance): array {
        //
        //     {
        //         "ticker" => "AVAX",
        //         "available" => "0.00000000",
        //         "held" => "0.00000000"
        //     }
        //
        $result = array(
            'info' => $balance,
        );
        for ($i = 0; $i < count($balance); $i++) {
            $balanceEntry = $balance[$i];
            $currencyId = $this->safe_string($balanceEntry, 'ticker');
            $code = $this->safe_currency_code($currencyId);
            $account = $this->account();
            $account['free'] = $this->safe_string($balanceEntry, 'available');
            $account['used'] = $this->safe_string($balanceEntry, 'held');
            $result[$code] = $account;
        }
        return $this->safe_balance($result);
    }

    public function create_order(string $symbol, string $type, string $side, float $amount, ?float $price = null, $params = array ()): array {
        /**
         * create a trade order
         *
         * @see https://doc.cryptomus.com/personal/exchange/market-order-creation
         * @see https://doc.cryptomus.com/personal/exchange/limit-order-creation
         *
         * @param {string} $symbol unified $symbol of the $market to create an order in
         * @param {string} $type 'market' or 'limit' or for spot
         * @param {string} $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 {array} [$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 {string} [$params->clientOrderId] a unique identifier for the order (optional)
         * @return {array} an ~@link https://docs.ccxt.com/#/?id=order-structure order structure~
         */
        $this->load_markets();
        $market = $this->market($symbol);
        $request = array(
            'market' => $market['id'],
            'direction' => $side,
            'tag' => 'ccxt',
        );
        $clientOrderId = $this->safe_string($params, 'clientOrderId');
        if ($clientOrderId !== null) {
            $params = $this->omit($params, 'clientOrderId');
            $request['client_order_id'] = $clientOrderId;
        }
        $sideBuy = $side === 'buy';
        $amountToString = $this->number_to_string($amount);
        $priceToString = $this->number_to_string($price);
        $cost = null;
        list($cost, $params) = $this->handle_param_string($params, 'cost');
        $response = null;
        if ($type === 'market') {
            if ($sideBuy) {
                $createMarketBuyOrderRequiresPrice = true;
                list($createMarketBuyOrderRequiresPrice, $params) = $this->handle_option_and_params($params, 'createOrder', 'createMarketBuyOrderRequiresPrice', true);
                if ($createMarketBuyOrderRequiresPrice) {
                    if (($price === null) && ($cost === null)) {
                        throw new InvalidOrder($this->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');
                    } elseif ($cost === null) {
                        $cost = Precise::string_mul($amountToString, $priceToString);
                    }
                } else {
                    $cost = $cost ? $cost : $amountToString;
                }
                $request['value'] = $cost;
            } else {
                $request['quantity'] = $amountToString;
            }
            $response = $this->privatePostV2UserApiExchangeOrdersMarket ($this->extend($request, $params));
        } elseif ($type === 'limit') {
            if ($price === null) {
                throw new ArgumentsRequired($this->id . ' createOrder() requires a $price parameter for a ' . $type . ' order');
            }
            $request['quantity'] = $amountToString;
            $request['price'] = $price;
            $response = $this->privatePostV2UserApiExchangeOrders ($this->extend($request, $params));
        } else {
            throw new ArgumentsRequired($this->id . ' createOrder() requires a $type parameter (limit or $market)');
        }
        //
        //     {
        //         "order_id" => "01JEXAFCCC5ZVJPZAAHHDKQBNG"
        //     }
        //
        return $this->parse_order($response, $market);
    }

    public function cancel_order(string $id, ?string $symbol = null, $params = array ()) {
        /**
         * cancels an open limit order
         *
         * @see https://doc.cryptomus.com/personal/exchange/limit-order-cancellation
         *
         * @param {string} $id order $id
         * @param {string} $symbol unified $symbol of the market the order was made in (not used in cryptomus)
         * @param {array} [$params] extra parameters specific to the exchange API endpoint
         * @return {array} An ~@link https://docs.ccxt.com/#/?$id=order-structure order structure~
         */
        $this->load_markets();
        $request = array();
        $request['orderId'] = $id;
        $response = $this->privateDeleteV2UserApiExchangeOrdersOrderId ($this->extend($request, $params));
        //
        //     {
        //         "success" => true
        //     }
        //
        return $this->safe_order(array( 'info' => $response ));
    }

    public function fetch_canceled_and_closed_orders(?string $symbol = null, ?int $since = null, ?int $limit = null, $params = array ()): array {
        /**
         * fetches information on multiple $orders made by the user
         *
         * @see https://doc.cryptomus.com/personal/exchange/history-of-completed-$orders
         *
         * @param {string} $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 {array} [$params] extra parameters specific to the exchange API endpoint
         * @param {string} [$params->direction] $order direction 'buy' or 'sell'
         * @param {string} [$params->order_id] $order id
         * @param {string} [$params->client_order_id] client $order id
         * @param {string} [$params->limit] A special parameter that sets the maximum number of records the $request will return
         * @param {string} [$params->offset] A special parameter that sets the number of records from the beginning of the list
         * @return {Order[]} a list of ~@link https://docs.ccxt.com/#/?id=$order-structure $order structures~
         */
        $this->load_markets();
        $request = array();
        $market = null;
        if ($symbol !== null) {
            $market = $this->market($symbol);
            $request['market'] = $market['id'];
        }
        if ($limit !== null) {
            $request['limit'] = $limit;
        }
        $response = $this->privateGetV2UserApiExchangeOrdersHistory ($this->extend($request, $params));
        //
        //     {
        //         "result" => array(
        //             {
        //                 "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" => array(
        //                         array(
        //                             "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 = $this->safe_list($response, 'result', array());
        $orders = array();
        for ($i = 0; $i < count($result); $i++) {
            $order = $result[$i];
            $orders[] = $this->parse_order($order, $market);
        }
        return $orders;
    }

    public function fetch_open_orders(?string $symbol = null, ?int $since = null, ?int $limit = null, $params = array ()): array {
        /**
         * fetch all unfilled currently open orders
         *
         * @see https://doc.cryptomus.com/personal/exchange/list-of-active-orders
         *
         * @param {string} $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 {array} [$params] extra parameters specific to the exchange API endpoint
         * @param {string} [$params->direction] order direction 'buy' or 'sell'
         * @param {string} [$params->order_id] order id
         * @param {string} [$params->client_order_id] client order id
         * @param {string} [$params->limit] A special parameter that sets the maximum number of records the $request will return
         * @param {string} [$params->offset] A special parameter that sets the number of records from the beginning of the list
         * @return {Order[]} a list of ~@link https://docs.ccxt.com/#/?id=order-structure order structures~
         */
        $this->load_markets();
        $market = null;
        if ($symbol !== null) {
            $market = $this->market($symbol);
        }
        $request = array(
        );
        if ($market !== null) {
            $request['market'] = $market['id'];
        }
        $response = $this->privateGetV2UserApiExchangeOrders ($this->extend($request, $params));
        //
        //     {
        //         "result" => array(
        //             array(
        //                 "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 = $this->safe_list($response, 'result', array());
        return $this->parse_orders($result, $market, null, null);
    }

    public function parse_order(array $order, ?array $market = null): array {
        //
        // 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" => array(
        //                 array(
        //                     "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 = $this->safe_string_2($order, 'order_id', 'id');
        $marketId = $this->safe_string($order, 'symbol');
        $market = $this->safe_market($marketId, $market);
        $dateTime = $this->safe_string($order, 'createdAt');
        $timestamp = $this->parse8601($dateTime);
        $deal = $this->safe_dict($order, 'deal', array());
        $averageFilledPrice = $this->safe_number($deal, 'averageFilledPrice');
        $type = $this->safe_string($order, 'type');
        $side = $this->safe_string($order, 'direction');
        $price = $this->safe_number($order, 'price');
        $transaction = $this->safe_list($deal, 'transactions', array());
        $fee = null;
        $firstTx = $this->safe_dict($transaction, 0);
        $feeCurrency = $this->safe_string($firstTx, 'feeCurrency');
        if ($feeCurrency !== null) {
            $fee = array(
                'currency' => $this->safe_currency_code($feeCurrency),
                'cost' => $this->safe_number($firstTx, 'fee'),
            );
        }
        if ($price === null) {
            $price = $this->safe_number($firstTx, 'filledPrice');
        }
        $amount = $this->safe_number($order, 'quantity');
        $cost = $this->safe_number($order, 'value');
        $status = $this->parse_order_status($this->safe_string($order, 'state'));
        $clientOrderId = $this->safe_string($order, 'clientOrderId');
        return $this->safe_order(array(
            'id' => $id,
            'clientOrderId' => $clientOrderId,
            'timestamp' => $timestamp,
            'datetime' => $this->iso8601($timestamp),
            'lastTradeTimestamp' => null,
            'symbol' => $market['symbol'],
            'type' => $type,
            'timeInForce' => null,
            'postOnly' => null,
            'side' => $side,
            'price' => $price,
            'stopPrice' => $this->safe_string($order, 'stopLossPrice'),
            'triggerPrice' => $this->safe_string($order, 'stopLossPrice'),
            'amount' => $amount,
            'cost' => $cost,
            'average' => $averageFilledPrice,
            'filled' => $this->safe_string($order, 'filledQuantity'),
            'remaining' => null,
            'status' => $status,
            'fee' => $fee,
            'trades' => null,
            'info' => $order,
        ), $market);
    }

    public function parse_order_status(?string $status = null): ?string {
        $statuses = array(
            'active' => 'open',
            'completed' => 'closed',
            'partially_completed' => 'open',
            'cancelled' => 'canceled',
            'expired' => 'expired',
            'failed' => 'failed',
        );
        return $this->safe_string($statuses, $status, $status);
    }

    public function fetch_trading_fees($params = array ()): array {
        /**
         * fetch the trading fees for multiple markets
         *
         * @see https://trade-docs.coinlist.co/?javascript--nodejs#list-fees
         *
         * @param {array} [$params] extra parameters specific to the exchange API endpoint
         * @return {array} a dictionary of ~@link https://docs.ccxt.com/#/?id=fee-structure fee structures~ indexed by market symbols
         */
        $response = $this->privateGetV2UserApiExchangeAccountTariffs ($params);
        //
        //     {
        //         $result => {
        //             equivalent_currency_code => 'USD',
        //             current_tariff_step => array(
        //                 step => '0',
        //                 from_turnover => '0.00000000',
        //                 maker_percent => '0.08',
        //                 taker_percent => '0.1'
        //             ),
        //             tariff_steps => array(
        //                 array(
        //                     step => '0',
        //                     from_turnover => '0.00000000',
        //                     maker_percent => '0.08',
        //                     taker_percent => '0.1'
        //                 ),
        //                 array(
        //                     step => '1',
        //                     from_turnover => '100001.00000000',
        //                     maker_percent => '0.06',
        //                     taker_percent => '0.095'
        //                 ),
        //                 array(
        //                     step => '2',
        //                     from_turnover => '250001.00000000',
        //                     maker_percent => '0.055',
        //                     taker_percent => '0.085'
        //                 ),
        //                 array(
        //                     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 = $this->safe_dict($response, 'result', array());
        $currentFeeTier = $this->safe_dict($data, 'current_tariff_step', array());
        $makerFee = $this->safe_string($currentFeeTier, 'maker_percent');
        $takerFee = $this->safe_string($currentFeeTier, 'taker_percent');
        $makerFee = Precise::string_div($makerFee, '100');
        $takerFee = Precise::string_div($takerFee, '100');
        $feeTiers = $this->safe_list($data, 'tariff_steps', array());
        $result = array();
        $tiers = $this->parse_fee_tiers($feeTiers);
        for ($i = 0; $i < count($this->symbols); $i++) {
            $symbol = $this->symbols[$i];
            $result[$symbol] = array(
                'info' => $response,
                'symbol' => $symbol,
                'maker' => $this->parse_number($makerFee),
                'taker' => $this->parse_number($takerFee),
                'percentage' => true,
                'tierBased' => true,
                'tiers' => $tiers,
            );
        }
        return $result;
    }

    public function parse_fee_tiers($feeTiers, ?array $market = null) {
        $takerFees = array();
        $makerFees = array();
        for ($i = 0; $i < count($feeTiers); $i++) {
            $tier = $feeTiers[$i];
            $turnover = $this->safe_number($tier, 'from_turnover');
            $taker = $this->safe_string($tier, 'taker_percent');
            $maker = $this->safe_string($tier, 'maker_percent');
            $maker = Precise::string_div($maker, '100');
            $taker = Precise::string_div($taker, '100');
            $makerFees[] = array( $turnover, $this->parse_number($maker) );
            $takerFees[] = array( $turnover, $this->parse_number($taker) );
        }
        return array(
            'maker' => $makerFees,
            'taker' => $takerFees,
        );
    }

    public function sign($path, $api = 'public', $method = 'GET', $params = array (), $headers = null, $body = null) {
        $endpoint = $this->implode_params($path, $params);
        $params = $this->omit($params, $this->extract_params($path));
        $url = $this->urls['api'][$api] . '/' . $endpoint;
        if ($api === 'private') {
            $this->check_required_credentials();
            $jsonParams = '';
            $headers = array(
                'userId' => $this->uid,
            );
            if ($method !== 'GET') {
                $body = $this->json($params);
                $jsonParams = $body;
                $headers['Content-Type'] = 'application/json';
            } else {
                $query = $this->urlencode($params);
                if (strlen($query) !== 0) {
                    $url .= '?' . $query;
                }
            }
            $jsonParamsBase64 = base64_encode($jsonParams);
            $stringToSign = $jsonParamsBase64 . $this->secret;
            $signature = $this->hash($this->encode($stringToSign), 'md5');
            $headers['sign'] = $signature;
        } else {
            $query = $this->urlencode($params);
            if (strlen($query) !== 0) {
                $url .= '?' . $query;
            }
        }
        return array( 'url' => $url, 'method' => $method, 'body' => $body, 'headers' => $headers );
    }

    public function handle_errors(int $httpCode, string $reason, string $url, string $method, array $headers, string $body, $response, $requestHeaders, $requestBody) {
        if ($response === null) {
            return null;
        }
        if (is_array($response) && array_key_exists('code', $response)) {
            $code = $this->safe_string($response, 'code');
            $feedback = $this->id . ' ' . $body;
            $this->throw_exactly_matched_exception($this->exceptions['exact'], $code, $feedback);
            throw new ExchangeError($feedback);
        } elseif (is_array($response) && array_key_exists('message', $response)) {
            //
            //      array("message":"Minimum amount 15 USDT","state":1)
            //
            $message = $this->safe_string($response, 'message');
            $feedback = $this->id . ' ' . $body;
            $this->throw_exactly_matched_exception($this->exceptions['exact'], $message, $feedback);
            $this->throw_broadly_matched_exception($this->exceptions['broad'], $message, $feedback);
            throw new ExchangeError($feedback); // unknown $message
        }
        return null;
    }
}
