# -*- 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.async_support.base.exchange import Exchange
from ccxt.abstract.hitobit import ImplicitAPI
from ccxt.base.types import Int, Market, OrderBook, Strings, Ticker, Tickers
from typing import List


class hitobit(Exchange, ImplicitAPI):

    def describe(self):
        return self.deep_extend(super(hitobit, self).describe(), {
            'id': 'hitobit',
            'name': 'Hitobit',
            'country': ['IR'],
            'rateLimit': 1000,
            'version': '1',
            'certified': False,
            'pro': False,
            'has': {
                'CORS': None,
                'spot': True,
                'margin': False,
                'swap': False,
                'future': False,
                'option': False,
                'addMargin': False,
                'cancelAllOrders': False,
                'cancelOrder': False,
                'cancelOrders': False,
                'createDepositAddress': False,
                'createOrder': False,
                'createStopLimitOrder': False,
                'createStopMarketOrder': False,
                'createStopOrder': False,
                'editOrder': False,
                'fetchBalance': False,
                'fetchBorrowInterest': False,
                'fetchBorrowRateHistories': False,
                'fetchBorrowRateHistory': False,
                'fetchClosedOrders': False,
                'fetchCrossBorrowRate': False,
                'fetchCrossBorrowRates': False,
                'fetchCurrencies': False,
                'fetchDepositAddress': False,
                'fetchDeposits': False,
                'fetchFundingHistory': False,
                'fetchFundingRate': False,
                'fetchFundingRateHistory': False,
                'fetchFundingRates': False,
                'fetchIndexOHLCV': False,
                'fetchIsolatedBorrowRate': False,
                'fetchIsolatedBorrowRates': False,
                'fetchL2OrderBook': False,
                'fetchLedger': False,
                'fetchLedgerEntry': False,
                'fetchLeverageTiers': False,
                'fetchMarkets': True,
                'fetchMarkOHLCV': False,
                'fetchMyTrades': False,
                'fetchOHLCV': True,
                'fetchOpenInterestHistory': False,
                'fetchOpenOrders': False,
                'fetchOrder': False,
                'fetchOrderBook': True,
                'fetchOrders': False,
                'fetchOrderTrades': 'emulated',
                'fetchPositions': False,
                'fetchPremiumIndexOHLCV': False,
                'fetchTicker': True,
                'fetchTickers': True,
                'fetchTime': False,
                'fetchTrades': False,
                'fetchTradingFee': False,
                'fetchTradingFees': False,
                'fetchWithdrawals': False,
                'setLeverage': False,
                'setMarginMode': False,
                'transfer': False,
                'withdraw': False,
            },
            'comment': 'This comment is optional',
            'urls': {
                'logo': 'https://cdn.arz.digital/cr-odin/img/exchanges/hitobit/64x64.png',
                'api': {
                    'public': 'https://hitobit.com',
                },
                'www': 'https://hitobit.com/',
                'doc': [
                    'https://hitobit.com/',
                ],
            },
            'timeframes': {
                '1m': 'OneMinute',
                '5m': 'FiveMinutes',
                '15m': 'FifteenMinutes',
                '30m': 'ThirtyMinutes',
                '1h': 'OneHour',
                '1d': 'OneDay',
                '1w': 'OneWeek',
                '1M': 'OneMonth',
            },
            'api': {
                'public': {
                    'get': {
                        'hapi/exchange/v1/public/alltickers/24hr': 1,
                        'hapi/exchange/v1/public/ticker/24hr': 1,
                        'hapi/exchange/v1/public/klines': 1,
                        'hapi/exchange/v1/public/depth': 1,
                    },
                },
            },
            'fees': {
                'trading': {
                    'tierBased': False,
                    'percentage': True,
                    'maker': self.parse_number('0.001'),
                    'taker': self.parse_number('0.001'),
                },
            },
        })

    async def fetch_markets(self, symbols: Strings = None, params={}) -> List[Market]:
        """
        retrieves data on all markets for hitobit
        :see: https://hitobit-docs.github.io/#general-info
        :param dict [params]: extra parameters specific to the exchange API endpoint
        :returns dict[]: an array of objects representing market data
        """
        response = await self.publicGetHapiExchangeV1PublicAlltickers24hr(params)
        result = []
        for i in range(0, len(response)):
            market = await self.parse_market(response[i])
            result.append(market)
        return result

    def parse_market(self, market) -> Market:
        # {
        #     'symbol': 'ENSIRT',
        #     'baseCurrencySymbol': 'ENS',
        #     'quoteCurrencySymbol': 'IRT',
        #     'symbolPublicOfferingDate': 1676263272189,
        #     'isHighlight': False,
        #     'priceChange': -141761,
        #     'priceChangePercent': -9.9,
        #     'weightedAveragePrice': 1302802.5923348605,
        #     'lastPrice': 1290756,
        #     'lastQuantity': 0.06698461538461538,
        #     'openPrice': 1432517,
        #     'highPrice': 1441389,
        #     'lowPrice': 1171122,
        #     'openTime': 1717762920000,
        #     'closeTime': 1717849320000,
        #     'firstTradeId': 9167561172598788,
        #     'lastTradeId': 9180948480278536,
        #     'totalTrades': 9210,
        #     'prevDayClosePrice': 1286855,
        #     'bidPrice': 1288866,
        #     'bidQuantity': 31.0938,
        #     'askPrice': 1290107,
        #     'askQuantity': 1.8,
        #     'baseVolume': 7544.726084104318,
        #     'quoteVolume': 9829288700.827547,
        #     'smartTradeEngine': True,
        #     'lastMarketInfoChangeDate': 1717849693023,
        # },
        id = self.safe_string(market, 'symbol')
        baseId = self.safe_string(market, 'baseCurrencySymbol')
        quoteId = self.safe_string(market, 'quoteCurrencySymbol')
        base = self.safe_currency_code(baseId)
        quote = self.safe_currency_code(quoteId)
        baseId = baseId.lower()
        quoteId = quoteId.lower()
        return {
            'id': id,
            'symbol': base + '/' + quote,
            'base': base,
            'quote': quote,
            'settle': None,
            'baseId': baseId,
            'quoteId': quoteId,
            'settleId': None,
            'type': 'spot',
            'spot': True,
            'margin': False,
            'swap': False,
            'future': False,
            'option': False,
            'active': True,
            'contract': False,
            'linear': None,
            'inverse': None,
            'contractSize': None,
            'expiry': None,
            'expiryDatetime': None,
            'strike': None,
            'optionType': None,
            'precision': {
                'amount': None,
                'price': None,
            },
            'limits': {
                'leverage': {
                    'min': None,
                    'max': None,
                },
                'amount': {
                    'min': None,
                    'max': None,
                },
                'price': {
                    'min': None,
                    'max': None,
                },
                'cost': {
                    'min': None,
                    'max': None,
                },
            },
            'created': None,
            'info': market,
        }

    async 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
        :see: https://hitobit-docs.github.io/#general-info
        :param str[]|None 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>`
        """
        await self.load_markets()
        if symbols is not None:
            symbols = self.market_symbols(symbols)
        response = await self.publicGetHapiExchangeV1PublicAlltickers24hr(params)
        result = {}
        for i in range(0, len(response)):
            ticker = await self.parse_ticker(response[i])
            symbol = ticker['symbol']
            result[symbol] = ticker
        return self.filter_by_array_tickers(result, 'symbol', symbols)

    async def fetch_ticker(self, symbol: str, params={}) -> Ticker:
        """
        fetches a price ticker, a statistical calculation with the information calculated over the past 24 hours for a specific market
        :see: https://hitobit-docs.github.io/#general-info
        :param str symbol: unified symbol of the market to fetch the ticker for
        :param dict [params]: extra parameters specific to the exchange API endpoint
        :returns dict: a `ticker structure <https://docs.ccxt.com/#/?id=ticker-structure>`
        """
        await self.load_markets()
        market = self.market(symbol)
        request = {
            'symbol': market['id'],
        }
        response = await self.publicGetHapiExchangeV1PublicTicker24hr(request)
        ticker = await self.parse_ticker(response)
        return ticker

    def parse_ticker(self, ticker, market: Market = None) -> Ticker:
        # {
        #     'symbol': 'ENSIRT',
        #     'baseCurrencySymbol': 'ENS',
        #     'quoteCurrencySymbol': 'IRT',
        #     'symbolPublicOfferingDate': 1676263272189,
        #     'isHighlight': False,
        #     'priceChange': -141761,
        #     'priceChangePercent': -9.9,
        #     'weightedAveragePrice': 1302802.5923348605,
        #     'lastPrice': 1290756,
        #     'lastQuantity': 0.06698461538461538,
        #     'openPrice': 1432517,
        #     'highPrice': 1441389,
        #     'lowPrice': 1171122,
        #     'openTime': 1717762920000,
        #     'closeTime': 1717849320000,
        #     'firstTradeId': 9167561172598788,
        #     'lastTradeId': 9180948480278536,
        #     'totalTrades': 9210,
        #     'prevDayClosePrice': 1286855,
        #     'bidPrice': 1288866,
        #     'bidQuantity': 31.0938,
        #     'askPrice': 1290107,
        #     'askQuantity': 1.8,
        #     'baseVolume': 7544.726084104318,
        #     'quoteVolume': 9829288700.827547,
        #     'smartTradeEngine': True,
        #     'lastMarketInfoChangeDate': 1717849693023,
        # },
        marketType = 'spot'
        marketId = self.safe_string(ticker, 'symbol')
        symbol = self.safe_symbol(marketId, market, None, marketType)
        high = self.safe_float(ticker, 'highPrice', 0)
        low = self.safe_float(ticker, 'lowPrice', 0)
        bid = self.safe_float(ticker, 'bidPrice', 0)
        ask = self.safe_float(ticker, 'askPrice', 0)
        last = self.safe_float(ticker, 'lastPrice', 0)
        change = self.safe_float(ticker, 'priceChangePercent', 0)
        baseVolume = self.safe_float(ticker, 'baseVolume', 0)
        quoteVolume = self.safe_float(ticker, 'quoteVolume', 0)
        timestamp = self.safe_integer(ticker, 'closeTime')
        return self.safe_ticker({
            'symbol': symbol,
            'timestamp': timestamp,
            'datetime': self.iso8601(timestamp),
            'high': high,
            'low': low,
            'bid': bid,
            'bidVolume': None,
            'ask': ask,
            'askVolume': None,
            'vwap': None,
            'open': last,
            'close': last,
            'last': last,
            'previousClose': None,
            'change': change,
            'percentage': None,
            'average': None,
            'baseVolume': baseVolume,
            'quoteVolume': quoteVolume,
            'info': ticker,
        }, market)

    async def fetch_ohlcv(self, symbol: str, timeframe='1m', since: Int = None, limit: Int = None, params={}) -> List[list]:
        """
        fetches historical candlestick data containing the open, high, low, and close price, and the volume of a market
        :see: https://hitobit-docs.github.io/#general-info
        :param str symbol: unified symbol of the market to fetch OHLCV data for
        :param str timeframe: the length of time each candle represents
        :param int [since]: timestamp in ms of the earliest candle to fetch
        :param int [limit]: the maximum amount of candles to fetch
        :param dict [params]: extra parameters specific to the exchange API endpoint
        :returns int[][]: A list of candles ordered, open, high, low, close, volume
        """
        await self.load_markets()
        market = self.market(symbol)
        endTime = Date.now()
        request = {
            'symbol': market['id'],
            'from': self.iso8601((endTime) - (24 * 60 * 60)),
            'to': self.iso8601(endTime),
            'interval': self.safe_string(self.timeframes, timeframe, timeframe),
            'limit': 300,
        }
        if since is not None:
            request['from'] = self.iso8601(since / 1000)
        if limit is not None:
            request['limit'] = limit
        if timeframe is not None:
            request['interval'] = self.safe_string(self.timeframes, timeframe, timeframe)
        response = await self.publicGetHapiExchangeV1PublicKlines(request)
        ohlcvs = []
        for i in range(0, len(response)):
            ohlcvs.append([
                self.safe_value(response[i], 'closeTime'),
                self.safe_value(response[i], 'open'),
                self.safe_value(response[i], 'high'),
                self.safe_value(response[i], 'low'),
                self.safe_value(response[i], 'close'),
                self.safe_value(response[i], 'baseVolume'),
            ])
        return self.parse_ohlcvs(ohlcvs, market, timeframe, since, limit)

    async 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 for multiple markets
        :see: https://hitobit-docs.github.io/#general-info
        :param str[]|None symbols: list of unified market symbols, all symbols fetched if None, default is None
        :param int [limit]: max number of entries per orderbook to return, default is None
        :param dict [params]: extra parameters specific to the exchange API endpoint
        :returns dict: a dictionary of `order book structures <https://docs.ccxt.com/#/?id=order-book-structure>` indexed by market symbol
        """
        await self.load_markets()
        market = self.market(symbol)
        request = {
            'symbol': market['id'],
            'limit': 30,
        }
        orderBook = await self.publicGetHapiExchangeV1PublicDepth(request)
        timestamp = Date.now()
        return self.parse_order_book(orderBook, symbol, timestamp, 'bids', 'asks')

    def sign(self, path, api='public', method='GET', params={}, headers=None, body=None):
        query = self.omit(params, self.extract_params(path))
        url = self.urls['api']['public'] + '/' + path + '?' + self.urlencode(query)
        headers = {'Content-Type': 'application/json'}
        return {'url': url, 'method': method, 'body': body, 'headers': headers}
