# -*- 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
import hashlib
from ccxt.base.errors import ExchangeError
from ccxt.base.errors import AuthenticationError
from ccxt.base.errors import PermissionDenied
from ccxt.base.errors import AccountSuspended
from ccxt.base.errors import ArgumentsRequired
from ccxt.base.errors import BadSymbol
from ccxt.base.errors import InsufficientFunds
from ccxt.base.errors import InvalidOrder
from ccxt.base.errors import OrderNotFound
from ccxt.base.errors import CancelPending
from ccxt.base.errors import RateLimitExceeded
from ccxt.base.errors import ExchangeNotAvailable
from ccxt.base.errors import OnMaintenance
from ccxt.base.errors import InvalidNonce
from ccxt.base.errors import RequestTimeout
from ccxt.base.decimal_to_precision import DECIMAL_PLACES
from ccxt.base.precise import Precise


class poloniex(Exchange):

    def describe(self):
        return self.deep_extend(super(poloniex, self).describe(), {
            'id': 'poloniex',
            'name': 'Poloniex',
            'countries': ['US'],
            # 200 requests per second for some unauthenticated market endpoints => 1000ms / 200 = 5ms between requests
            'rateLimit': 5,
            'certified': False,
            'pro': False,
            'has': {
                'CORS': None,
                'spot': True,
                'margin': None,  # has but not fully implemented
                'swap': None,  # has but not fully implemented
                'future': None,  # has but not fully implemented
                'option': None,
                'cancelAllOrders': True,
                'cancelOrder': True,
                'createDepositAddress': True,
                'createMarketOrder': None,
                'createOrder': True,
                'editOrder': False,
                'fetchBalance': True,
                'fetchClosedOrder': False,
                'fetchCurrencies': True,
                'fetchDepositAddress': True,
                'fetchDeposits': True,
                'fetchMarginMode': False,
                'fetchMarkets': True,
                'fetchMyTrades': True,
                'fetchOHLCV': True,
                'fetchOpenInterestHistory': False,
                'fetchOpenOrder': False,
                'fetchOpenOrders': True,  # True endpoint for open orders
                'fetchOrder': True,
                'fetchOrderBook': True,
                'fetchOrderBooks': False,
                'fetchOrderTrades': True,  # True endpoint for trades of a single open or closed order
                'fetchPosition': False,
                'fetchPositionMode': False,
                'fetchTicker': True,
                'fetchTickers': True,
                'fetchTime': True,
                'fetchTrades': True,
                'fetchTradingFee': False,
                'fetchTradingFees': True,
                'fetchTransactions': True,
                'fetchTransfer': False,
                'fetchTransfers': False,
                'fetchWithdrawals': True,
                'transfer': True,
                'withdraw': True,
            },
            'timeframes': {
                '1m': 'MINUTE_1',
                '5m': 'MINUTE_5',
                '10m': 'MINUTE_10',
                '15m': 'MINUTE_15',
                '30m': 'MINUTE_30',
                '1h': 'HOUR_1',
                '2h': 'HOUR_2',
                '4h': 'HOUR_4',
                '6h': 'HOUR_6',
                '12h': 'HOUR_12',
                '1d': 'DAY_1',
                '3d': 'DAY_3',
                '1w': 'WEEK_1',
                '1M': 'MONTH_1',
            },
            'urls': {
                'logo': 'https://user-images.githubusercontent.com/1294454/27766817-e9456312-5ee6-11e7-9b3c-b628ca5626a5.jpg',
                'api': 'https://api.poloniex.com',
                'test': 'https://sand-spot-api-gateway.poloniex.com',
                'www': 'https://www.poloniex.com',
                'doc': 'https://docs.poloniex.com',
                'fees': 'https://poloniex.com/fees',
                'referral': 'https://poloniex.com/signup?c=UBFZJRPJ',
            },
            'api': {
                'public': {
                    'get': {
                        'markets': 20,
                        'markets/{symbol}': 1,
                        'currencies': 20,
                        'currencies/{currency}': 20,
                        'timestamp': 1,
                        'markets/price': 1,
                        'markets/{symbol}/price': 1,
                        'markets/{symbol}/orderBook': 1,
                        'markets/{symbol}/candles': 1,
                        'markets/{symbol}/trades': 20,
                        'markets/ticker24h': 20,
                        'markets/{symbol}/ticker24h': 20,
                    },
                },
                'private': {
                    'get': {
                        'accounts': 4,
                        'accounts/activity': 4,
                        'accounts/balances': 4,
                        'accounts/{id}/balances': 4,
                        'accounts/transfer': 20,
                        'accounts/transfer/{id}': 4,
                        'feeinfo': 20,
                        'wallets/addresses': 20,
                        'wallets/activity': 20,
                        'wallets/addresses/{currency}': 20,
                        'orders': 20,
                        'orders/{id}': 4,
                        'orders/history': 20,
                        'smartorders': 20,
                        'smartorders/{id}': 4,
                        'smartorders/history': 20,
                        'trades': 20,
                        'orders/{id}/trades': 4,
                    },
                    'post': {
                        'accounts/transfer': 4,
                        'wallets/address': 20,
                        'wallets/withdraw': 20,
                        'orders': 4,
                        'smartorders': 4,
                    },
                    'delete': {
                        'orders/{id}': 4,
                        'orders/cancelByIds': 20,
                        'orders': 20,
                        'smartorders/{id}': 4,
                        'smartorders/cancelByIds': 20,
                        'smartorders': 20,
                    },
                },
            },
            'fees': {
                'trading': {
                    'feeSide': 'get',
                    # starting from Jan 8 2020
                    'maker': self.parse_number('0.0009'),
                    'taker': self.parse_number('0.0009'),
                },
                'funding': {},
            },
            'commonCurrencies': {
                'AIR': 'AirCoin',
                'APH': 'AphroditeCoin',
                'BCC': 'BTCtalkcoin',
                'BCHABC': 'BCHABC',
                'BDG': 'Badgercoin',
                'BTM': 'Bitmark',
                'CON': 'Coino',
                'GOLD': 'GoldEagles',
                'GPUC': 'GPU',
                'HOT': 'Hotcoin',
                'ITC': 'Information Coin',
                'KEY': 'KEYCoin',
                'MASK': 'NFTX Hashmasks Index',  # conflict with Mask Network
                'MEME': 'Degenerator Meme',  # Degenerator Meme migrated to Meme Inu, self exchange still has the old price
                'PLX': 'ParallaxCoin',
                'REPV2': 'REP',
                'STR': 'XLM',
                'SOC': 'SOCC',
                'TRADE': 'Unitrade',
                'XAP': 'API Coin',
                # self is not documented in the API docs for Poloniex
                # https://github.com/ccxt/ccxt/issues/7084
                # when the user calls withdraw('USDT', amount, address, tag, params)
                # with params = {'currencyToWithdrawAs': 'USDTTRON'}
                # or params = {'currencyToWithdrawAs': 'USDTETH'}
                # fetchWithdrawals('USDT') returns the corresponding withdrawals
                # with a USDTTRON or a USDTETH currency id, respectfully
                # therefore we have map them back to the original code USDT
                # otherwise the returned withdrawals are filtered out
                'USDTTRON': 'USDT',
                'USDTETH': 'USDT',
                'UST': 'USTC',
            },
            'options': {
                'networks': {
                    'BEP20': 'BSC',
                    'ERC20': 'ETH',
                    'TRX': 'TRON',
                    'TRC20': 'TRON',
                },
                'limits': {
                    'cost': {
                        'min': {
                            'BTC': 0.0001,
                            'ETH': 0.0001,
                            'USDT': 1.0,
                            'TRX': 100,
                            'BNB': 0.06,
                            'USDC': 1.0,
                            'USDJ': 1.0,
                            'TUSD': 0.0001,
                            'DAI': 1.0,
                            'PAX': 1.0,
                            'BUSD': 1.0,
                        },
                    },
                },
                'accountsByType': {
                    'spot': 'spot',
                    'future': 'futures',
                },
                'accountsById': {
                    'exchange': 'spot',
                    'futures': 'future',
                },
            },
            'precisionMode': DECIMAL_PLACES,
            'exceptions': {
                'exact': {
                    'You may only place orders that reduce your position.': InvalidOrder,
                    'Invalid order number, or you are not the person who placed the order.': OrderNotFound,
                    'Permission denied': PermissionDenied,
                    'Permission denied.': PermissionDenied,
                    'Connection timed out. Please try again.': RequestTimeout,
                    'Internal error. Please try again.': ExchangeNotAvailable,
                    'Currently in maintenance mode.': OnMaintenance,
                    'Order not found, or you are not the person who placed it.': OrderNotFound,
                    'Invalid API key/secret pair.': AuthenticationError,
                    'Please do not make more than 8 API calls per second.': RateLimitExceeded,
                    'This IP has been temporarily throttled. Please ensure your requests are valid and try again in one minute.': RateLimitExceeded,
                    'Rate must be greater than zero.': InvalidOrder,  # {"error":"Rate must be greater than zero."}
                    'Invalid currency pair.': BadSymbol,  # {"error":"Invalid currency pair."}
                    'Invalid currencyPair parameter.': BadSymbol,  # {"error":"Invalid currencyPair parameter."}
                    'Trading is disabled in self market.': BadSymbol,  # {"error":"Trading is disabled in self market."}
                    'Invalid orderNumber parameter.': OrderNotFound,
                    'Order is beyond acceptable bounds.': InvalidOrder,  # {"error":"Order is beyond acceptable bounds.","fee":"0.00155000","currencyPair":"USDT_BOBA"}
                    'This account is closed.': AccountSuspended,  # {"error":"This account is closed."}
                },
                'broad': {
                    'Total must be at least': InvalidOrder,  # {"error":"Total must be at least 0.0001."}
                    'This account is frozen': AccountSuspended,  # {"error":"This account is frozen for trading."} or {"error":"This account is frozen."}
                    'This account is locked.': AccountSuspended,  # {"error":"This account is locked."}
                    'Not enough': InsufficientFunds,
                    'Nonce must be greater': InvalidNonce,
                    'You have already called cancelOrder': CancelPending,  # {"error":"You have already called cancelOrder, moveOrder, or cancelReplace on self order. Please wait for that call's response."}
                    'Amount must be at least': InvalidOrder,  # {"error":"Amount must be at least 0.000001."}
                    'is either completed or does not exist': OrderNotFound,  # {"error":"Order 587957810791 is either completed or does not exist."}
                    'Error pulling ': ExchangeError,  # {"error":"Error pulling order book"}
                },
            },
        })

    def parse_ohlcv(self, ohlcv, market=None):
        #
        #     [
        #         [
        #             "22814.01",
        #             "22937.42",
        #             "22832.57",
        #             "22937.42",
        #             "3916.58764051",
        #             "0.171199",
        #             "2982.64647063",
        #             "0.130295",
        #             33,
        #             0,
        #             "22877.449915304470460711",
        #             "MINUTE_5",
        #             1659664800000,
        #             1659665099999
        #         ]
        #     ]
        #
        return [
            self.safe_integer(ohlcv, 12),
            self.safe_number(ohlcv, 2),
            self.safe_number(ohlcv, 1),
            self.safe_number(ohlcv, 0),
            self.safe_number(ohlcv, 3),
            self.safe_number(ohlcv, 5),
        ]

    def fetch_ohlcv(self, symbol, timeframe='1m', since=None, limit=None, params={}):
        """
        fetches historical candlestick data containing the open, high, low, and close price, and the volume of a market
        :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|None since: timestamp in ms of the earliest candle to fetch
        :param int|None limit: the maximum amount of candles to fetch
        :param dict params: extra parameters specific to the poloniex api endpoint
        :returns [[int]]: A list of candles ordered as timestamp, open, high, low, close, volume
        """
        self.load_markets()
        market = self.market(symbol)
        request = {
            'symbol': market['id'],
            'interval': self.timeframes[timeframe],
        }
        if since is not None:
            request['startTime'] = since
        if limit is not None:
            # limit should in between 100 and 500
            request['limit'] = limit
        response = self.publicGetMarketsSymbolCandles(self.extend(request, params))
        #
        #     [
        #         [
        #             "22814.01",
        #             "22937.42",
        #             "22832.57",
        #             "22937.42",
        #             "3916.58764051",
        #             "0.171199",
        #             "2982.64647063",
        #             "0.130295",
        #             33,
        #             0,
        #             "22877.449915304470460711",
        #             "MINUTE_5",
        #             1659664800000,
        #             1659665099999
        #         ]
        #     ]
        #
        return self.parse_ohlcvs(response, market, timeframe, since, limit)

    def load_markets(self, reload=False, params={}):
        markets = super(poloniex, self).load_markets(reload, params)
        currenciesByNumericId = self.safe_value(self.options, 'currenciesByNumericId')
        if (currenciesByNumericId is None) or reload:
            self.options['currenciesByNumericId'] = self.index_by(self.currencies, 'numericId')
        return markets

    def fetch_markets(self, params={}):
        """
        retrieves data on all markets for poloniex
        :param dict params: extra parameters specific to the exchange api endpoint
        :returns [dict]: an array of objects representing market data
        """
        markets = self.publicGetMarkets(params)
        #
        #     [
        #         {
        #             "symbol" : "BTS_BTC",
        #             "baseCurrencyName" : "BTS",
        #             "quoteCurrencyName" : "BTC",
        #             "displayName" : "BTS/BTC",
        #             "state" : "NORMAL",
        #             "visibleStartTime" : 1659018816626,
        #             "tradableStartTime" : 1659018816626,
        #             "symbolTradeLimit" : {
        #                 "symbol" : "BTS_BTC",
        #                 "priceScale" : 10,
        #                 "quantityScale" : 0,
        #                 "amountScale" : 8,
        #                 "minQuantity" : "100",
        #                 "minAmount" : "0.00001",
        #                 "highestBid" : "0",
        #                 "lowestAsk" : "0"
        #             }
        #         }
        #     ]
        #
        result = []
        for i in range(0, len(markets)):
            market = self.safe_value(markets, i)
            id = self.safe_string(market, 'symbol')
            baseId = self.safe_string(market, 'baseCurrencyName')
            quoteId = self.safe_string(market, 'quoteCurrencyName')
            base = self.safe_currency_code(baseId)
            quote = self.safe_currency_code(quoteId)
            state = self.safe_string(market, 'state')
            active = state == 'NORMAL'
            symbolTradeLimit = self.safe_value(market, 'symbolTradeLimit')
            # these are known defaults
            result.append({
                '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': active,
                'contract': False,
                'linear': None,
                'inverse': None,
                'contractSize': None,
                'expiry': None,
                'expiryDatetime': None,
                'strike': None,
                'optionType': None,
                'precision': {
                    'amount': self.safe_integer(symbolTradeLimit, 'quantityScale'),
                    'price': self.safe_integer(symbolTradeLimit, 'priceScale'),
                },
                'limits': {
                    'amount': {
                        'min': self.safe_number(symbolTradeLimit, 'minQuantity'),
                        'max': None,
                    },
                    'price': {
                        'min': None,
                        'max': None,
                    },
                    'cost': {
                        'min': self.safe_number(symbolTradeLimit, 'minAmount'),
                        'max': None,
                    },
                },
                'info': market,
            })
        return result

    def fetch_time(self, params={}):
        """
        fetches the current integer timestamp in milliseconds from the exchange server
        :param dict params: extra parameters specific to the poloniex api endpoint
        :returns int: the current integer timestamp in milliseconds from the exchange server
        """
        response = self.publicGetTimestamp(params)
        return self.safe_integer(response, 'serverTime')

    def parse_ticker(self, ticker, market=None):
        #
        #     {
        #         "symbol" : "BTC_USDT",
        #         "open" : "22814.93",
        #         "low" : "22441.90",
        #         "high" : "23413.00",
        #         "close" : "23148.66",
        #         "quantity" : "71.743706",
        #         "amount" : "1638994.52683452",
        #         "tradeCount" : 3893,
        #         "startTime" : 1659605760000,
        #         "closeTime" : 1659692161077,
        #         "displayName" : "BTC/USDT",
        #         "dailyChange" : "0.0152",
        #         "ts" : 1659692169838
        #     }
        #
        timestamp = self.safe_integer(ticker, 'ts')
        marketId = self.safe_string(ticker, 'symbol')
        market = self.market(marketId)
        close = self.safe_string(ticker, 'close')
        relativeChange = self.safe_string(ticker, 'percentChange')
        percentage = Precise.string_mul(relativeChange, '100')
        return self.safe_ticker({
            'id': marketId,
            'symbol': market['symbol'],
            'timestamp': timestamp,
            'datetime': self.iso8601(timestamp),
            'high': self.safe_string(ticker, 'high'),
            'low': self.safe_string(ticker, 'low'),
            'bid': None,
            'bidVolume': None,
            'ask': None,
            'askVolume': None,
            'vwap': None,
            'open': self.safe_string(ticker, 'open'),
            'close': close,
            'last': close,
            'previousClose': None,
            'change': None,
            'percentage': percentage,
            'average': None,
            'baseVolume': self.safe_string(ticker, 'quantity'),
            'quoteVolume': self.safe_string(ticker, 'amount'),
            'info': ticker,
        }, market)

    def fetch_tickers(self, symbols=None, params={}):
        """
        fetches price tickers for multiple markets, statistical calculations with the information calculated over the past 24 hours each market
        :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 poloniex api endpoint
        :returns dict: an array of `ticker structures <https://docs.ccxt.com/en/latest/manual.html#ticker-structure>`
        """
        self.load_markets()
        symbols = self.market_symbols(symbols)
        response = self.publicGetMarketsTicker24h(params)
        #
        #     [
        #         {
        #             "symbol" : "KUB_USDD",
        #             "open" : "0",
        #             "low" : "0",
        #             "high" : "0",
        #             "close" : "0",
        #             "quantity" : "0",
        #             "amount" : "0",
        #             "tradeCount" : 0,
        #             "startTime" : 1659606240000,
        #             "closeTime" : 1659692648742,
        #             "displayName" : "KUB/USDD",
        #             "dailyChange" : "0.00",
        #             "ts" : 1659692648742
        #         }
        #     ]
        #
        return self.parse_tickers(response, symbols)

    def fetch_currencies(self, params={}):
        """
        fetches all available currencies on an exchange
        :param dict params: extra parameters specific to the poloniex api endpoint
        :returns dict: an associative dictionary of currencies
        """
        response = self.publicGetCurrencies(params)
        #
        #     [
        #         {
        #             "1CR": {
        #                 "id": 1,
        #                 "name": "1CRedit",
        #                 "description": "BTC Clone",
        #                 "type": "address",
        #                 "withdrawalFee": "0.01000000",
        #                 "minConf": 10000,
        #                 "depositAddress": null,
        #                 "blockchain": "1CR",
        #                 "delisted": False,
        #                 "tradingState": "NORMAL",
        #                 "walletState": "DISABLED",
        #                 "parentChain": null,
        #                 "isMultiChain": False,
        #                 "isChildChain": False,
        #                 "childChains": []
        #             }
        #         }
        #     ]
        #
        result = {}
        for i in range(0, len(response)):
            item = self.safe_value(response, i)
            ids = list(item.keys())
            id = self.safe_value(ids, 0)
            currency = self.safe_value(item, id)
            code = self.safe_currency_code(id)
            delisted = self.safe_value(currency, 'delisted')
            walletState = self.safe_string(currency, 'walletState')
            enabled = walletState == 'ENABLED'
            listed = not delisted
            active = listed and enabled
            numericId = self.safe_integer(currency, 'id')
            fee = self.safe_number(currency, 'withdrawalFee')
            result[code] = {
                'id': id,
                'numericId': numericId,
                'code': code,
                'info': currency,
                'name': currency['name'],
                'active': active,
                'deposit': None,
                'withdraw': None,
                'fee': fee,
                'precision': None,
                'limits': {
                    'amount': {
                        'min': None,
                        'max': None,
                    },
                    'withdraw': {
                        'min': fee,
                        'max': None,
                    },
                },
            }
        return result

    def fetch_ticker(self, symbol, params={}):
        """
        fetches a price ticker, a statistical calculation with the information calculated over the past 24 hours for a specific market
        :param str symbol: unified symbol of the market to fetch the ticker for
        :param dict params: extra parameters specific to the poloniex api endpoint
        :returns dict: a `ticker structure <https://docs.ccxt.com/en/latest/manual.html#ticker-structure>`
        """
        self.load_markets()
        market = self.market(symbol)
        request = {
            'symbol': market['id'],
        }
        response = self.publicGetMarketsSymbolTicker24h(self.extend(request, params))
        #
        #     {
        #         "symbol" : "BTC_USDT",
        #         "open" : "22814.93",
        #         "low" : "22441.90",
        #         "high" : "23413.00",
        #         "close" : "23148.66",
        #         "quantity" : "71.743706",
        #         "amount" : "1638994.52683452",
        #         "tradeCount" : 3893,
        #         "startTime" : 1659605760000,
        #         "closeTime" : 1659692161077,
        #         "displayName" : "BTC/USDT",
        #         "dailyChange" : "0.0152",
        #         "ts" : 1659692169838
        #     }
        #
        return self.parse_ticker(response, market)

    def parse_trade(self, trade, market=None):
        #
        # fetchTrades
        #
        #     {
        #         "id" : "60014521",
        #         "price" : "23162.94",
        #         "quantity" : "0.00009",
        #         "amount" : "2.0846646",
        #         "takerSide" : "SELL",
        #         "ts" : 1659684602042,
        #         "createTime" : 1659684602036
        #     }
        #
        # fetchMyTrades
        #
        #     {
        #         "id": "32164924331503616",
        #         "symbol": "LINK_USDT",
        #         "accountType": "SPOT",
        #         "orderId": "32164923987566592",
        #         "side": "SELL",
        #         "type": "MARKET",
        #         "matchRole": "TAKER",
        #         "createTime": 1648635115525,
        #         "price": "11",
        #         "quantity": "0.5",
        #         "amount": "5.5",
        #         "feeCurrency": "USDT",
        #         "feeAmount": "0.007975",
        #         "pageId": "32164924331503616",
        #         "clientOrderId": "myOwnId-321"
        #     }
        #
        # fetchOrderTrades(taker trades)
        #
        #     {
        #         "id": "30341456333942784",
        #         "symbol": "LINK_USDT",
        #         "accountType": "SPOT",
        #         "orderId": "30249408733945856",
        #         "side": "BUY",
        #         "type": "LIMIT",
        #         "matchRole": "MAKER",
        #         "createTime": 1648200366864,
        #         "price": "3.1",
        #         "quantity": "1",
        #         "amount": "3.1",
        #         "feeCurrency": "LINK",
        #         "feeAmount": "0.00145",
        #         "pageId": "30341456333942784",
        #         "clientOrderId": ""
        #     }
        #
        #
        id = self.safe_string_2(trade, 'id', 'tradeID')
        orderId = self.safe_string(trade, 'orderId')
        timestamp = self.safe_integer_2(trade, 'ts', 'createTime')
        marketId = self.safe_string(trade, 'symbol')
        market = self.safe_market(marketId, market, '_')
        symbol = market['symbol']
        side = self.safe_string_lower(trade, 'side')
        fee = None
        priceString = self.safe_string(trade, 'price')
        amountString = self.safe_string(trade, 'quantity')
        costString = self.safe_string(trade, 'amount')
        feeCurrencyId = self.safe_string(trade, 'feeCurrency')
        feeCostString = self.safe_string(trade, 'feeAmount')
        if feeCostString is not None:
            feeCurrencyCode = self.safe_currency_code(feeCurrencyId)
            fee = {
                'cost': feeCostString,
                'currency': feeCurrencyCode,
            }
        return self.safe_trade({
            'id': id,
            'info': trade,
            'timestamp': timestamp,
            'datetime': self.iso8601(timestamp),
            'symbol': symbol,
            'order': orderId,
            'type': self.safe_string_lower(trade, 'type'),
            'side': side,
            'takerOrMaker': self.safe_string_lower(trade, 'matchRole'),
            'price': priceString,
            'amount': amountString,
            'cost': costString,
            'fee': fee,
        }, market)

    def fetch_trades(self, symbol, since=None, limit=None, params={}):
        """
        get the list of most recent trades for a particular symbol
        :param str symbol: unified symbol of the market to fetch trades for
        :param int|None since: timestamp in ms of the earliest trade to fetch
        :param int|None limit: the maximum amount of trades to fetch
        :param dict params: extra parameters specific to the poloniex api endpoint
        :returns [dict]: a list of `trade structures <https://docs.ccxt.com/en/latest/manual.html?#public-trades>`
        """
        self.load_markets()
        market = self.market(symbol)
        request = {
            'symbol': market['id'],
        }
        if limit is not None:
            request['limit'] = limit
        trades = self.publicGetMarketsSymbolTrades(self.extend(request, params))
        #
        #     [
        #         {
        #             "id" : "60014521",
        #             "price" : "23162.94",
        #             "quantity" : "0.00009",
        #             "amount" : "2.0846646",
        #             "takerSide" : "SELL",
        #             "ts" : 1659684602042,
        #             "createTime" : 1659684602036
        #         }
        #     ]
        #
        return self.parse_trades(trades, market, since, limit)

    def fetch_my_trades(self, symbol=None, since=None, limit=None, params={}):
        """
        fetch all trades made by the user
        :param str|None symbol: unified market symbol
        :param int|None since: the earliest time in ms to fetch trades for
        :param int|None limit: the maximum number of trades structures to retrieve
        :param dict params: extra parameters specific to the poloniex api endpoint
        :returns [dict]: a list of `trade structures <https://docs.ccxt.com/en/latest/manual.html#trade-structure>`
        """
        self.load_markets()
        market = None
        if symbol is not None:
            market = self.market(symbol)
        request = {
            # 'from': 12345678,  # A 'trade Id'. The query begins at ‘from'.
            # 'direction': 'PRE',  # PRE, NEXT The direction before or after ‘from'.
        }
        if since is not None:
            request['startTime'] = since
        if limit is not None:
            request['limit'] = int(limit)
        response = self.privateGetTrades(self.extend(request, params))
        #
        #     [
        #         {
        #             "id": "32164924331503616",
        #             "symbol": "LINK_USDT",
        #             "accountType": "SPOT",
        #             "orderId": "32164923987566592",
        #             "side": "SELL",
        #             "type": "MARKET",
        #             "matchRole": "TAKER",
        #             "createTime": 1648635115525,
        #             "price": "11",
        #             "quantity": "0.5",
        #             "amount": "5.5",
        #             "feeCurrency": "USDT",
        #             "feeAmount": "0.007975",
        #             "pageId": "32164924331503616",
        #             "clientOrderId": "myOwnId-321"
        #         }
        #     ]
        #
        result = self.parse_trades(response, market)
        return self.filter_by_since_limit(result, since, limit)

    def parse_order_status(self, status):
        statuses = {
            'NEW': 'open',
            'PARTIALLY_FILLED': 'open',
            'FILLED': 'closed',
            'PENDING_CANCEL': 'canceled',
            'PARTIALLY_CANCELED': 'canceled',
            'CANCELED': 'canceled',
            'FAILED': 'canceled',
        }
        return self.safe_string(statuses, status, status)

    def parse_order(self, order, market=None):
        #
        # fetchOpenOrder
        #
        #     {
        #         "id" : "7xxxxxxxxxxxxxxx6",
        #         "clientOrderId" : "",
        #         "symbol" : "ETH_USDT",
        #         "state" : "NEW",
        #         "accountType" : "SPOT",
        #         "side" : "BUY",
        #         "type" : "LIMIT",
        #         "timeInForce" : "GTC",
        #         "quantity" : "0.001",
        #         "price" : "1600",
        #         "avgPrice" : "0",
        #         "amount" : "0",
        #         "filledQuantity" : "0",
        #         "filledAmount" : "0",
        #         "createTime" : 16xxxxxxxxx26,
        #         "updateTime" : 16xxxxxxxxx36
        #     }
        #
        # fetchOpenOrders
        #
        #     {
        #         "id": "24993088082542592",
        #         "clientOrderId": "",
        #         "symbol": "ELON_USDC",
        #         "state": "NEW",
        #         "accountType": "SPOT",
        #         "side": "SELL",
        #         "type": "MARKET",
        #         "timeInForce": "GTC",
        #         "quantity": "1.00",
        #         "price": "0.00",
        #         "avgPrice": "0.00",
        #         "amount": "0.00",
        #         "filledQuantity": "0.00",
        #         "filledAmount": "0.00",
        #         "createTime": 1646925216548,
        #         "updateTime": 1646925216548
        #     }
        #
        # createOrder
        #
        #     {
        #         "id": "29772698821328896",
        #         "clientOrderId": "1234Abc"
        #     }
        #
        timestamp = self.safe_integer_2(order, 'timestamp', 'createTime')
        if timestamp is None:
            timestamp = self.parse8601(self.safe_string(order, 'date'))
        marketId = self.safe_string(order, 'symbol')
        market = self.safe_market(marketId, market, '_')
        symbol = market['symbol']
        resultingTrades = self.safe_value(order, 'resultingTrades')
        if not isinstance(resultingTrades, list):
            resultingTrades = self.safe_value(resultingTrades, self.safe_string(market, 'id', marketId))
        price = self.safe_string_2(order, 'price', 'rate')
        amount = self.safe_string(order, 'quantity')
        filled = self.safe_string(order, 'filledQuantity')
        status = self.parse_order_status(self.safe_string(order, 'state'))
        side = self.safe_string_lower(order, 'side')
        rawType = self.safe_string(order, 'type')
        type = self.parse_order_type(rawType)
        id = self.safe_string_2(order, 'orderNumber', 'id')
        fee = None
        feeCurrency = self.safe_string(order, 'tokenFeeCurrency')
        feeCost = None
        feeCurrencyCode = None
        rate = self.safe_string(order, 'fee')
        if feeCurrency is None:
            feeCurrencyCode = market['base'] if (side == 'buy') else market['quote']
        else:
            # poloniex accepts a 30% discount to pay fees in TRX
            feeCurrencyCode = self.safe_currency_code(feeCurrency)
            feeCost = self.safe_string(order, 'tokenFee')
        if feeCost is not None:
            fee = {
                'rate': rate,
                'cost': feeCost,
                'currency': feeCurrencyCode,
            }
        clientOrderId = self.safe_string(order, 'clientOrderId')
        return self.safe_order({
            'info': order,
            'id': id,
            'clientOrderId': clientOrderId,
            'timestamp': timestamp,
            'datetime': self.iso8601(timestamp),
            'lastTradeTimestamp': self.safe_integer(order, 'updateTime'),
            'status': status,
            'symbol': symbol,
            'type': type,
            'timeInForce': self.safe_string(order, 'timeInForce'),
            'postOnly': None,
            'side': side,
            'price': price,
            'stopPrice': None,
            'cost': None,
            'average': self.safe_string(order, 'avgPrice'),
            'amount': amount,
            'filled': filled,
            'remaining': None,
            'trades': resultingTrades,
            'fee': fee,
        }, market)

    def parse_order_type(self, status):
        statuses = {
            'MARKET': 'market',
            'LIMIT': 'limit',
            'STOP-LIMIT': 'limit',
            'STOP-MARKET': 'market',
        }
        return self.safe_string(statuses, status, status)

    def parse_open_orders(self, orders, market, result):
        for i in range(0, len(orders)):
            order = orders[i]
            extended = self.extend(order, {
                'status': 'open',
                'type': 'limit',
                'side': order['type'],
                'price': order['rate'],
            })
            result.append(self.parse_order(extended, market))
        return result

    def fetch_open_orders(self, symbol=None, since=None, limit=None, params={}):
        """
        fetch all unfilled currently open orders
        :param str|None symbol: unified market symbol
        :param int|None since: the earliest time in ms to fetch open orders for
        :param int|None limit: the maximum number of  open orders structures to retrieve
        :param dict params: extra parameters specific to the poloniex api endpoint
        :returns [dict]: a list of `order structures <https://docs.ccxt.com/en/latest/manual.html#order-structure>`
        """
        self.load_markets()
        market = None
        request = {}
        if symbol is not None:
            market = self.market(symbol)
            request['symbol'] = market['id']
        if limit is not None:
            request['limit'] = limit
        response = self.privateGetOrders(self.extend(request, params))
        #
        #     [
        #         {
        #             "id" : "7xxxxxxxxxxxxxxx6",
        #             "clientOrderId" : "",
        #             "symbol" : "ETH_USDT",
        #             "state" : "NEW",
        #             "accountType" : "SPOT",
        #             "side" : "BUY",
        #             "type" : "LIMIT",
        #             "timeInForce" : "GTC",
        #             "quantity" : "0.001",
        #             "price" : "1600",
        #             "avgPrice" : "0",
        #             "amount" : "0",
        #             "filledQuantity" : "0",
        #             "filledAmount" : "0",
        #             "createTime" : 16xxxxxxxxx26,
        #             "updateTime" : 16xxxxxxxxx36
        #         }
        #     ]
        #
        extension = {'status': 'open'}
        return self.parse_orders(response, market, since, limit, extension)

    def create_order(self, symbol, type, side, amount, price=None, params={}):
        """
        create a trade order
        :param str symbol: unified symbol of the market to create an order in
        :param str type: 'market' or 'limit'
        :param str side: 'buy' or 'sell'
        :param float amount: how much of currency you want to trade in units of base currency
        :param float|None price: the price at which the order is to be fullfilled, in units of the quote currency, ignored in market orders
        :param dict params: extra parameters specific to the poloniex api endpoint
        :returns dict: an `order structure <https://docs.ccxt.com/en/latest/manual.html#order-structure>`
        """
        # if type == 'market':
        #     raise ExchangeError(self.id + ' createOrder() does not accept market orders')
        # }
        self.load_markets()
        market = self.market(symbol)
        upperCaseType = type.upper()
        isMarket = upperCaseType == 'MARKET'
        isPostOnly = self.is_post_only(isMarket, upperCaseType == 'LIMIT_MAKER', params)
        if isPostOnly:
            upperCaseType = 'LIMIT_MAKER'
            params = self.omit(params, 'postOnly')
        request = {
            'symbol': market['id'],
            'side': side,
            'type': upperCaseType,
            # 'timeInForce': timeInForce,
            # 'accountType': 'SPOT',
            # 'amount': amount,
        }
        if isMarket:
            if side == 'buy':
                request['amount'] = self.currency_to_precision(market['quote'], amount)
            else:
                request['quantity'] = self.amount_to_precision(symbol, amount)
        else:
            request['quantity'] = self.amount_to_precision(symbol, amount)
            request['price'] = self.price_to_precision(symbol, price)
        clientOrderId = self.safe_string(params, 'clientOrderId')
        if clientOrderId is not None:
            request['clientOrderId'] = clientOrderId
            params = self.omit(params, 'clientOrderId')
        # remember the timestamp before issuing the request
        response = self.privatePostOrders(self.extend(request, params))
        #
        #     {
        #         "id" : "78923648051920896",
        #         "clientOrderId" : ""
        #     }
        #
        response = self.extend(response, {
            'type': side,
        })
        return self.parse_order(response, market)

    def cancel_order(self, id, symbol=None, params={}):
        """
        cancels an open order
        :param str id: order id
        :param str|None symbol: unified symbol of the market the order was made in
        :param dict params: extra parameters specific to the poloniex api endpoint
        :returns dict: An `order structure <https://docs.ccxt.com/en/latest/manual.html#order-structure>`
        """
        self.load_markets()
        request = {}
        clientOrderId = self.safe_value(params, 'clientOrderId')
        if clientOrderId is not None:
            id = clientOrderId
        request['id'] = id
        params = self.omit(params, 'clientOrderId')
        return self.privateDeleteOrdersId(self.extend(request, params))

    def cancel_all_orders(self, symbol=None, params={}):
        """
        cancel all open orders
        :param str|None symbol: unified market symbol, only orders in the market of self symbol are cancelled when symbol is not None
        :param dict params: extra parameters specific to the poloniex api endpoint
        :returns [dict]: a list of `order structures <https://docs.ccxt.com/en/latest/manual.html#order-structure>`
        """
        self.load_markets()
        request = {
            # 'accountTypes': 'SPOT',
        }
        market = None
        if symbol is not None:
            market = self.market(symbol)
            request['symbols'] = [
                market['id'],
            ]
        response = self.privateDeleteOrders(self.extend(request, params))
        #
        #     [
        #         {
        #             "orderId" : "78xxxxxxxx80",
        #             "clientOrderId" : "",
        #             "state" : "NEW",
        #             "code" : 200,
        #             "message" : ""
        #         }, {
        #             "orderId" : "78xxxxxxxxx80",
        #             "clientOrderId" : "",
        #             "state" : "NEW",
        #             "code" : 200,
        #             "message" : ""
        #         }
        #     ]
        #
        return response

    def fetch_order(self, id, symbol=None, params={}):
        """
        fetch an order by it's id
        :param str id: order id
        :param str|None symbol: unified market symbol, default is None
        :param dict params: extra parameters specific to the poloniex api endpoint
        :returns dict: an `order structure <https://docs.ccxt.com/en/latest/manual.html#order-structure>`
        """
        self.load_markets()
        id = str(id)
        request = {
            'id': id,
        }
        response = self.privateGetOrdersId(self.extend(request, params))
        #
        #     {
        #         "id": "21934611974062080",
        #         "clientOrderId": "123",
        #         "symbol": "TRX_USDC",
        #         "state": "NEW",
        #         "accountType": "SPOT",
        #         "side": "SELL",
        #         "type": "LIMIT",
        #         "timeInForce": "GTC",
        #         "quantity": "1.00",
        #         "price": "10.00",
        #         "avgPrice": "0.00",
        #         "amount": "0.00",
        #         "filledQuantity": "0.00",
        #         "filledAmount": "0.00",
        #         "createTime": 1646196019020,
        #         "updateTime": 1646196019020
        #     }
        #
        return self.extend(self.parse_order(response), {
            'id': id,
        })

    def fetch_order_status(self, id, symbol=None, params={}):
        self.load_markets()
        orders = self.fetch_open_orders(symbol, None, None, params)
        indexed = self.index_by(orders, 'id')
        return 'open' if (id in indexed) else 'closed'

    def fetch_order_trades(self, id, symbol=None, since=None, limit=None, params={}):
        """
        fetch all the trades made from a single order
        :param str id: order id
        :param str|None symbol: unified market symbol
        :param int|None since: the earliest time in ms to fetch trades for
        :param int|None limit: the maximum number of trades to retrieve
        :param dict params: extra parameters specific to the poloniex api endpoint
        :returns [dict]: a list of `trade structures <https://docs.ccxt.com/en/latest/manual.html#trade-structure>`
        """
        self.load_markets()
        request = {
            'id': id,
        }
        trades = self.privateGetOrdersIdTrades(self.extend(request, params))
        #
        #     [
        #         {
        #             "id": "30341456333942784",
        #             "symbol": "LINK_USDT",
        #             "accountType": "SPOT",
        #             "orderId": "30249408733945856",
        #             "side": "BUY",
        #             "type": "LIMIT",
        #             "matchRole": "MAKER",
        #             "createTime": 1648200366864,
        #             "price": "3.1",
        #             "quantity": "1",
        #             "amount": "3.1",
        #             "feeCurrency": "LINK",
        #             "feeAmount": "0.00145",
        #             "pageId": "30341456333942784",
        #             "clientOrderId": ""
        #         }
        #     ]
        #
        return self.parse_trades(trades)

    def parse_balance(self, response):
        result = {
            'info': response,
            'timestamp': None,
            'datetime': None,
        }
        for i in range(0, len(response)):
            account = self.safe_value(response, i, {})
            balances = self.safe_value(account, 'balances')
            for j in range(0, len(balances)):
                balance = self.safe_value(balances, j)
                currencyId = self.safe_string(balance, 'currency')
                code = self.safe_currency_code(currencyId)
                newAccount = self.account()
                newAccount['free'] = self.safe_string(balance, 'available')
                newAccount['used'] = self.safe_string(balance, 'hold')
                result[code] = newAccount
        return self.safe_balance(result)

    def fetch_balance(self, params={}):
        """
        query for balance and get the amount of funds available for trading or funds locked in orders
        :param dict params: extra parameters specific to the poloniex api endpoint
        :returns dict: a `balance structure <https://docs.ccxt.com/en/latest/manual.html?#balance-structure>`
        """
        self.load_markets()
        request = {
            'accountType': 'SPOT',
        }
        response = self.privateGetAccountsBalances(self.extend(request, params))
        #
        #     [
        #         {
        #             "accountId" : "7xxxxxxxxxx8",
        #             "accountType" : "SPOT",
        #             "balances" : [
        #                 {
        #                     "currencyId" : "214",
        #                     "currency" : "USDT",
        #                     "available" : "2.00",
        #                     "hold" : "0.00"
        #                 }
        #             ]
        #         }
        #     ]
        #
        return self.parse_balance(response)

    def fetch_trading_fees(self, params={}):
        """
        fetch the trading fees for multiple markets
        :param dict params: extra parameters specific to the poloniex api endpoint
        :returns dict: a dictionary of `fee structures <https://docs.ccxt.com/en/latest/manual.html#fee-structure>` indexed by market symbols
        """
        self.load_markets()
        response = self.privateGetFeeinfo(params)
        #
        #     {
        #         "trxDiscount" : False,
        #         "makerRate" : "0.00145",
        #         "takerRate" : "0.00155",
        #         "volume30D" : "0.00"
        #     }
        #
        result = {}
        for i in range(0, len(self.symbols)):
            symbol = self.symbols[i]
            result[symbol] = {
                'info': response,
                'symbol': symbol,
                'maker': self.safe_number(response, 'makerRate'),
                'taker': self.safe_number(response, 'takerRate'),
                'percentage': True,
                'tierBased': True,
            }
        return result

    def fetch_order_book(self, symbol, limit=None, params={}):
        """
        fetches information on open orders with bid(buy) and ask(sell) prices, volumes and other data
        :param str symbol: unified symbol of the market to fetch the order book for
        :param int|None limit: the maximum amount of order book entries to return
        :param dict params: extra parameters specific to the poloniex api endpoint
        :returns dict: A dictionary of `order book structures <https://docs.ccxt.com/en/latest/manual.html#order-book-structure>` indexed by market symbols
        """
        self.load_markets()
        market = self.market(symbol)
        request = {
            'symbol': market['id'],
        }
        if limit is not None:
            request['limit'] = limit  # The default value of limit is 10. Valid limit values are: 5, 10, 20, 50, 100, 150.
        response = self.publicGetMarketsSymbolOrderBook(self.extend(request, params))
        #
        #     {
        #         "time" : 1659695219507,
        #         "scale" : "-1",
        #         "asks" : ["23139.82", "0.317981", "23140", "0.191091", "23170.06", "0.01", "23200", "0.107758", "23230.55", "0.01", "23247.2", "0.154", "23254", "0.005121", "23263", "0.038", "23285.4", "0.308", "23300", "0.108896"],
        #         "bids" : ["23139.74", "0.432092", "23139.73", "0.198592", "23123.21", "0.000886", "23123.2", "0.308", "23121.4", "0.154", "23105", "0.000789", "23100", "0.078175", "23069.1", "0.026276", "23068.83", "0.001329", "23051", "0.000048"],
        #         "ts" : 1659695219513
        #     }
        #
        timestamp = self.safe_integer(response, 'time')
        asks = self.safe_value(response, 'asks')
        bids = self.safe_value(response, 'bids')
        asksResult = []
        bidsResult = []
        for i in range(0, len(asks)):
            if (i % 2) < 1:
                price = self.safe_number(asks, i)
                amount = self.safe_number(asks, self.sum(i, 1))
                asksResult.append([price, amount])
        for i in range(0, len(bids)):
            if (i % 2) < 1:
                price = self.safe_number(bids, i)
                amount = self.safe_number(bids, self.sum(i, 1))
                bidsResult.append([price, amount])
        return {
            'symbol': market['symbol'],
            'bids': self.sort_by(bidsResult, 0, True),
            'asks': self.sort_by(asksResult, 0),
            'timestamp': timestamp,
            'datetime': self.iso8601(timestamp),
            'nonce': None,
        }

    def create_deposit_address(self, code, params={}):
        """
        create a currency deposit address
        :param str code: unified currency code of the currency for the deposit address
        :param dict params: extra parameters specific to the poloniex api endpoint
        :returns dict: an `address structure <https://docs.ccxt.com/en/latest/manual.html#address-structure>`
        """
        self.load_markets()
        currency = self.currency(code)
        request = {
            'currency': currency['id'],
        }
        networks = self.safe_value(self.options, 'networks', {})
        network = self.safe_string_upper(params, 'network')  # self line allows the user to specify either ERC20 or ETH
        network = self.safe_string(networks, network, network)  # handle ERC20>ETH alias
        if network is not None:
            request['currency'] += network  # when network the currency need to be changed to currency+network https://docs.poloniex.com/#withdraw on MultiChain Currencies section
            params = self.omit(params, 'network')
        else:
            if currency['id'] == 'USDT':
                raise ArgumentsRequired(self.id + ' createDepositAddress requires a network parameter for ' + code + '.')
        response = self.privatePostWalletsAddress(self.extend(request, params))
        #
        #     {
        #         "address" : "0xfxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxf"
        #     }
        #
        address = self.safe_string(response, 'address')
        tag = None
        self.check_address(address)
        if currency is not None:
            depositAddress = self.safe_string(currency['info'], 'depositAddress')
            if depositAddress is not None:
                tag = address
                address = depositAddress
        return {
            'currency': code,
            'address': address,
            'tag': tag,
            'network': network,
            'info': response,
        }

    def fetch_deposit_address(self, code, params={}):
        """
        fetch the deposit address for a currency associated with self account
        :param str code: unified currency code
        :param dict params: extra parameters specific to the poloniex api endpoint
        :returns dict: an `address structure <https://docs.ccxt.com/en/latest/manual.html#address-structure>`
        """
        self.load_markets()
        currency = self.currency(code)
        request = {
            'currency': currency['id'],
        }
        networks = self.safe_value(self.options, 'networks', {})
        network = self.safe_string_upper(params, 'network')  # self line allows the user to specify either ERC20 or ETH
        network = self.safe_string(networks, network, network)  # handle ERC20>ETH alias
        if network is not None:
            request['currency'] += network  # when network the currency need to be changed to currency+network https://docs.poloniex.com/#withdraw on MultiChain Currencies section
            params = self.omit(params, 'network')
        else:
            if currency['id'] == 'USDT':
                raise ArgumentsRequired(self.id + ' fetchDepositAddress requires a network parameter for ' + code + '.')
        response = self.privateGetWalletsAddresses(self.extend(request, params))
        #
        #     {
        #         "USDTTRON" : "Txxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxp"
        #     }
        #
        address = self.safe_string(response, request['currency'])
        tag = None
        self.check_address(address)
        if currency is not None:
            depositAddress = self.safe_string(currency['info'], 'depositAddress')
            if depositAddress is not None:
                tag = address
                address = depositAddress
        return {
            'currency': code,
            'address': address,
            'tag': tag,
            'network': network,
            'info': response,
        }

    def transfer(self, code, amount, fromAccount, toAccount, params={}):
        """
        transfer currency internally between wallets on the same account
        :param str code: unified currency code
        :param float amount: amount to transfer
        :param str fromAccount: account to transfer from
        :param str toAccount: account to transfer to
        :param dict params: extra parameters specific to the poloniex api endpoint
        :returns dict: a `transfer structure <https://docs.ccxt.com/en/latest/manual.html#transfer-structure>`
        """
        self.load_markets()
        currency = self.currency(code)
        amount = self.currency_to_precision(code, amount)
        accountsByType = self.safe_value(self.options, 'accountsByType', {})
        fromId = self.safe_string(accountsByType, fromAccount, fromAccount)
        toId = self.safe_string(accountsByType, toAccount, fromAccount)
        request = {
            'amount': amount,
            'currency': currency['id'],
            'fromAccount': fromId,
            'toAccount': toId,
        }
        response = self.privatePostAccountsTransfer(self.extend(request, params))
        #
        #    {
        #        success: '1',
        #        message: 'Transferred 1.00000000 USDT from exchange to lending account.'
        #    }
        #
        return self.parse_transfer(response, currency)

    def parse_transfer_status(self, status):
        statuses = {
            '1': 'ok',
        }
        return self.safe_string(statuses, status, status)

    def parse_transfer(self, transfer, currency=None):
        #
        #    {
        #        success: '1',
        #        message: 'Transferred 1.00000000 USDT from exchange to lending account.'
        #    }
        #
        message = self.safe_string(transfer, 'message')
        words = message.split(' ')
        amount = self.safe_number(words, 1)
        currencyId = self.safe_string(words, 2)
        fromAccountId = self.safe_string(words, 4)
        toAccountId = self.safe_string(words, 6)
        accountsById = self.safe_value(self.options, 'accountsById', {})
        return {
            'info': transfer,
            'id': None,
            'timestamp': None,
            'datetime': None,
            'currency': self.safe_currency_code(currencyId, currency),
            'amount': amount,
            'fromAccount': self.safe_string(accountsById, fromAccountId),
            'toAccount': self.safe_string(accountsById, toAccountId),
            'status': self.parse_order_status(self.safe_string(transfer, 'success', 'failed')),
        }

    def withdraw(self, code, amount, address, tag=None, params={}):
        """
        make a withdrawal
        :param str code: unified currency code
        :param float amount: the amount to withdraw
        :param str address: the address to withdraw to
        :param str|None tag:
        :param dict params: extra parameters specific to the poloniex api endpoint
        :returns dict: a `transaction structure <https://docs.ccxt.com/en/latest/manual.html#transaction-structure>`
        """
        tag, params = self.handle_withdraw_tag_and_params(tag, params)
        self.check_address(address)
        self.load_markets()
        currency = self.currency(code)
        request = {
            'currency': currency['id'],
            'amount': amount,
            'address': address,
        }
        if tag is not None:
            request['paymentId'] = tag
        networks = self.safe_value(self.options, 'networks', {})
        network = self.safe_string_upper(params, 'network')  # self line allows the user to specify either ERC20 or ETH
        network = self.safe_string(networks, network, network)  # handle ERC20>ETH alias
        if network is not None:
            request['currency'] += network  # when network the currency need to be changed to currency+network https://docs.poloniex.com/#withdraw on MultiChain Currencies section
            params = self.omit(params, 'network')
        response = self.privatePostWalletsWithdraw(self.extend(request, params))
        #
        #     {
        #         response: 'Withdrew 1.00000000 USDT.',
        #         email2FA: False,
        #         withdrawalNumber: 13449869
        #     }
        #
        return self.parse_transaction(response, currency)

    def fetch_transactions_helper(self, code=None, since=None, limit=None, params={}):
        self.load_markets()
        year = 31104000  # 60 * 60 * 24 * 30 * 12 = one year of history, why not
        now = self.seconds()
        start = int(since / 1000) if (since is not None) else now - 10 * year
        request = {
            'start': start,  # UNIX timestamp, required
            'end': now,  # UNIX timestamp, required
        }
        response = self.privateGetWalletsActivity(self.extend(request, params))
        #
        #     {
        #         "adjustments":[],
        #         "deposits":[
        #             {
        #                 currency: "BTC",
        #                 address: "1MEtiqJWru53FhhHrfJPPvd2tC3TPDVcmW",
        #                 amount: "0.01063000",
        #                 confirmations:  1,
        #                 txid: "952b0e1888d6d491591facc0d37b5ebec540ac1efb241fdbc22bcc20d1822fb6",
        #                 timestamp:  1507916888,
        #                 status: "COMPLETE"
        #             },
        #             {
        #                 currency: "ETH",
        #                 address: "0x20108ba20b65c04d82909e91df06618107460197",
        #                 amount: "4.00000000",
        #                 confirmations: 38,
        #                 txid: "0x4be260073491fe63935e9e0da42bd71138fdeb803732f41501015a2d46eb479d",
        #                 timestamp: 1525060430,
        #                 status: "COMPLETE"
        #             }
        #         ],
        #         "withdrawals":[
        #             {
        #                 "withdrawalNumber":13449869,
        #                 "currency":"USDTTRON",  # not documented in API docs, see commonCurrencies in describe()
        #                 "address":"TXGaqPW23JdRWhsVwS2mRsGsegbdnAd3Rw",
        #                 "amount":"1.00000000",
        #                 "fee":"0.00000000",
        #                 "timestamp":1591573420,
        #                 "status":"COMPLETE: dadf427224b3d44b38a2c13caa4395e4666152556ca0b2f67dbd86a95655150f",
        #                 "ipAddress":"x.x.x.x",
        #                 "canCancel":0,
        #                 "canResendEmail":0,
        #                 "paymentID":null,
        #                 "scope":"crypto"
        #             },
        #             {
        #                 withdrawalNumber: 8224394,
        #                 currency: "EMC2",
        #                 address: "EYEKyCrqTNmVCpdDV8w49XvSKRP9N3EUyF",
        #                 amount: "63.10796020",
        #                 fee: "0.01000000",
        #                 timestamp: 1510819838,
        #                 status: "COMPLETE: d37354f9d02cb24d98c8c4fc17aa42f475530b5727effdf668ee5a43ce667fd6",
        #                 ipAddress: "x.x.x.x"
        #             },
        #             {
        #                 withdrawalNumber: 9290444,
        #                 currency: "ETH",
        #                 address: "0x191015ff2e75261d50433fbd05bd57e942336149",
        #                 amount: "0.15500000",
        #                 fee: "0.00500000",
        #                 timestamp: 1514099289,
        #                 status: "COMPLETE: 0x12d444493b4bca668992021fd9e54b5292b8e71d9927af1f076f554e4bea5b2d",
        #                 ipAddress: "x.x.x.x"
        #             },
        #             {
        #                 withdrawalNumber: 11518260,
        #                 currency: "BTC",
        #                 address: "8JoDXAmE1GY2LRK8jD1gmAmgRPq54kXJ4t",
        #                 amount: "0.20000000",
        #                 fee: "0.00050000",
        #                 timestamp: 1527918155,
        #                 status: "COMPLETE: 1864f4ebb277d90b0b1ff53259b36b97fa1990edc7ad2be47c5e0ab41916b5ff",
        #                 ipAddress: "x.x.x.x"
        #             }
        #         ]
        #     }
        #
        return response

    def fetch_transactions(self, code=None, since=None, limit=None, params={}):
        """
        fetch history of deposits and withdrawals
        :param str|None code: unified currency code for the currency of the transactions, default is None
        :param int|None since: timestamp in ms of the earliest transaction, default is None
        :param int|None limit: max number of transactions to return, default is None
        :param dict params: extra parameters specific to the poloniex api endpoint
        :returns dict: a list of `transaction structure <https://docs.ccxt.com/en/latest/manual.html#transaction-structure>`
        """
        self.load_markets()
        response = self.fetch_transactions_helper(code, since, limit, params)
        currency = None
        if code is not None:
            currency = self.currency(code)
        withdrawals = self.safe_value(response, 'withdrawals', [])
        deposits = self.safe_value(response, 'deposits', [])
        withdrawalTransactions = self.parse_transactions(withdrawals, currency, since, limit)
        depositTransactions = self.parse_transactions(deposits, currency, since, limit)
        transactions = self.array_concat(depositTransactions, withdrawalTransactions)
        return self.filter_by_currency_since_limit(self.sort_by(transactions, 'timestamp'), code, since, limit)

    def fetch_withdrawals(self, code=None, since=None, limit=None, params={}):
        """
        fetch all withdrawals made from an account
        :param str|None code: unified currency code
        :param int|None since: the earliest time in ms to fetch withdrawals for
        :param int|None limit: the maximum number of withdrawals structures to retrieve
        :param dict params: extra parameters specific to the poloniex api endpoint
        :returns [dict]: a list of `transaction structures <https://docs.ccxt.com/en/latest/manual.html#transaction-structure>`
        """
        response = self.fetch_transactions_helper(code, since, limit, params)
        currency = None
        if code is not None:
            currency = self.currency(code)
        withdrawals = self.safe_value(response, 'withdrawals', [])
        transactions = self.parse_transactions(withdrawals, currency, since, limit)
        return self.filter_by_currency_since_limit(transactions, code, since, limit)

    def fetch_deposits(self, code=None, since=None, limit=None, params={}):
        """
        fetch all deposits made to an account
        :param str|None code: unified currency code
        :param int|None since: the earliest time in ms to fetch deposits for
        :param int|None limit: the maximum number of deposits structures to retrieve
        :param dict params: extra parameters specific to the poloniex api endpoint
        :returns [dict]: a list of `transaction structures <https://docs.ccxt.com/en/latest/manual.html#transaction-structure>`
        """
        response = self.fetch_transactions_helper(code, since, limit, params)
        currency = None
        if code is not None:
            currency = self.currency(code)
        deposits = self.safe_value(response, 'deposits', [])
        transactions = self.parse_transactions(deposits, currency, since, limit)
        return self.filter_by_currency_since_limit(transactions, code, since, limit)

    def parse_transaction_status(self, status):
        statuses = {
            'COMPLETE': 'ok',
            'COMPLETED': 'ok',
            'AWAITING APPROVAL': 'pending',
            'AWAITING_APPROVAL': 'pending',
            'PENDING': 'pending',
            'PROCESSING': 'pending',
            'COMPLETE ERROR': 'failed',
            'COMPLETE_ERROR': 'failed',
        }
        return self.safe_string(statuses, status, status)

    def parse_transaction(self, transaction, currency=None):
        #
        # deposits
        #
        #     {
        #         "txid": "f49d489616911db44b740612d19464521179c76ebe9021af85b6de1e2f8d68cd",
        #         "amount": "49798.01987021",
        #         "status": "COMPLETE",
        #         "address": "DJVJZ58tJC8UeUv9Tqcdtn6uhWobouxFLT",
        #         "currency": "DOGE",
        #         "timestamp": 1524321838,
        #         "confirmations": 3371,
        #         "depositNumber": 134587098
        #     }
        #
        # withdrawals
        #
        #     {
        #         "withdrawalRequestsId": 7397527,
        #         "currency": "ETC",
        #         "address": "0x26419a62055af459d2cd69bb7392f5100b75e304",
        #         "amount": "13.19951600",
        #         "fee": "0.01000000",
        #         "timestamp": 1506010932,
        #         "status": "COMPLETED",
        #         "txid": "343346392f82ac16e8c2604f2a604b7b2382d0e9d8030f673821f8de4b5f5bk",
        #         "ipAddress": "1.2.3.4",
        #         "paymentID": null
        #     }
        #
        # withdraw
        #
        #     {
        #         "withdrawalRequestsId": 33485231
        #     }
        #
        timestamp = self.safe_timestamp(transaction, 'timestamp')
        currencyId = self.safe_string(transaction, 'currency')
        code = self.safe_currency_code(currencyId)
        status = self.safe_string(transaction, 'status', 'pending')
        status = self.parse_transaction_status(status)
        txid = self.safe_string(transaction, 'txid')
        type = 'withdrawal' if ('withdrawalRequestsId' in transaction) else 'deposit'
        id = self.safe_string_2(transaction, 'withdrawalRequestsId', 'depositNumber')
        address = self.safe_string(transaction, 'address')
        tag = self.safe_string(transaction, 'paymentID')
        amountString = self.safe_string(transaction, 'amount')
        feeCostString = self.safe_string(transaction, 'fee')
        if type == 'withdrawal':
            amountString = Precise.string_sub(amountString, feeCostString)
        return {
            'info': transaction,
            'id': id,
            'currency': code,
            'amount': self.parse_number(amountString),
            'network': None,
            'address': address,
            'addressTo': None,
            'addressFrom': None,
            'tag': tag,
            'tagTo': None,
            'tagFrom': None,
            'status': status,
            'type': type,
            'updated': None,
            'txid': txid,
            'timestamp': timestamp,
            'datetime': self.iso8601(timestamp),
            'fee': {
                'currency': code,
                'cost': self.parse_number(feeCostString),
            },
        }

    def nonce(self):
        return self.milliseconds()

    def sign(self, path, api='public', method='GET', params={}, headers=None, body=None):
        url = self.urls['api']
        query = self.omit(params, self.extract_params(path))
        implodedPath = self.implode_params(path, params)
        if api == 'public':
            url += '/' + implodedPath
            if query:
                url += '?' + self.urlencode(query)
        else:
            self.check_required_credentials()
            timestamp = str(self.nonce())
            auth = method + "\n"  # eslint-disable-line quotes
            url += '/' + implodedPath
            auth += '/' + implodedPath
            if (method == 'POST') or (method == 'PUT') or (method == 'DELETE'):
                auth += "\n"  # eslint-disable-line quotes
                if query:
                    body = self.json(query)
                    auth += 'requestBody=' + body + '&'
                auth += 'signTimestamp=' + timestamp
            else:
                sortedQuery = self.extend({'signTimestamp': timestamp}, query)
                sortedQuery = self.keysort(sortedQuery)
                auth += "\n" + self.urlencode(sortedQuery)  # eslint-disable-line quotes
                if query:
                    url += '?' + self.urlencode(query)
            signature = self.hmac(self.encode(auth), self.encode(self.secret), hashlib.sha256, 'base64')
            headers = {
                'Content-Type': 'application/json',
                'key': self.apiKey,
                'signTimestamp': timestamp,
                'signature': signature,
            }
        return {'url': url, 'method': method, 'body': body, 'headers': headers}

    def handle_errors(self, code, reason, url, method, headers, body, response, requestHeaders, requestBody):
        if response is None:
            return
        # {"error":"Permission denied."}
        if 'error' in response:
            message = response['error']
            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
