import axios from 'axios';
import cherio from 'cherio';
import FormData from 'form-data';
import moment from 'moment';
import {
	User,
	Exchange,
	Ticker,
	PayType,
	Currency,
	OrderStatus,
} from '../models_nosql';
import {
	MerchantOrder_SQL,
	SpotOrder_SQL,
	Ticker_SQL,
} from '../models_sql';
import {
	getSignature_BN,
	getSignature_HB,
	getSignature_KX,
	getSignature_CX,
	getSignature_BG,
	getSignature_BT,
	getSignature_MG,
	getSignature_KC,
	getSignature_BX,
	getSignature_GT,
	getSignature_XG,
	getSignature_CN,
	getSignature_BM,
	getSignature_CM,
	getSignature_XT,
	// getSignature_CR,
	getToken_GX,
} from '../utilities';
import {
	// TYPE_ENV,
	TG_BOT,
	CONSTANTS_BN,
	CONSTANTS_HB,
	CONSTANTS_KX,
	CONSTANTS_BZ,
	CONSTANTS_GX,
	CONSTANTS_BT,
	CONSTANTS_PX,
	CONSTANTS_MG,
	CONSTANTS_KC,
	CONSTANTS_GT,
	CONSTANTS_BG,
	CONSTANTS_BX,
	CONSTANTS_CX,
	CONSTANTS_BP,
	CONSTANTS_XG,
	CONSTANTS_CN,
	CONSTANTS_BM,
	CONSTANTS_AX,
	CONSTANTS_CM,
	CONSTANTS_XT,
	TEXT_CONSTANTS,
	TICKER_CONSTANTS as tickers,
	HTML_XG as html_XG,
	HTX_ORDERS as htx_orders,
} from '../constants';

// получение текущего времени + 5
export const getTimestamps = () => {
	// Отклонение часового пояса GMT+5
	// const timeDelay = TYPE_ENV === 'production' ? 60000 * 60 * 5 : 0;
	const timeDelay = 0;
	return new Date(new Date().getTime() + timeDelay).toLocaleString('ru', {
		year: 'numeric',
		month: 'numeric',
		day: 'numeric',
		timezone: 'UTC',
		hour: 'numeric',
		minute: 'numeric',
		second: 'numeric',
	});
};

// кроссбраузерное получение localDate
export const getLocalDate = () => {
	return new Date(new Date().getTime()).toLocaleString('ru', {
		year: 'numeric',
		month: 'numeric',
		day: 'numeric',
	});
};

// Получение наименований крипты
export const getBaseQuoteAssets = (ticker) => {
	const result = { baseAsset: '', quoteAsset: '' };
	if (
		ticker.slice(-4) === 'USDT' ||
		ticker.slice(-4) === 'USDC' ||
		ticker.slice(-4) === 'USDE' ||
		ticker.slice(-4) === 'BUSD' ||
		ticker.slice(-4) === 'FUSD' ||
		ticker.slice(-4) === 'TUSD' ||
		ticker.slice(-4) === 'PERP' ||
		ticker.slice(-4) === 'DOGE' ||
		ticker.slice(-4) === 'USDD'
	) {
		result.quoteAsset = ticker.slice(-4);
		result.baseAsset = ticker.split(result.quoteAsset)[0];
	} else if (
		ticker.slice(-3) === 'BTC' ||
		ticker.slice(-3) === 'ETH' ||
		ticker.slice(-3) === 'BNB' ||
		ticker.slice(-3) === 'DAI' ||
		ticker.slice(-3) === 'EUR' ||
		ticker.slice(-3) === 'AED' ||
		ticker.slice(-3) === 'AUD' ||
		ticker.slice(-3) === 'RUB' ||
		ticker.slice(-3) === 'TRY' ||
		ticker.slice(-3) === 'PLN' ||
		ticker.slice(-3) === 'BRZ' ||
		ticker.slice(-3) === 'BRL'
	) {
		result.quoteAsset = ticker.slice(-3);
		result.baseAsset = ticker.split(result.quoteAsset)[0];
	}
	return result;
};

// получение данных MerchantOrders by BZ_API
export const getMerchantOrdersByAPI_BZ = async (params) => {
	const { userId, prefix, config } = params;
	let result = [];

	await axios(config)
		.then((response) => {
			// console.log(response.data);
			result = response.data.data ? response.data.data : [];
			// result = response.data ? response.data : [];
		})
		.catch((error) => {
			console.log(
				`=======// ${getTimestamps()} //=======\n****${userId.slice(
					-4
				)} | ${prefix}: getMerchantOrdersByAPI_BZ request Error!\n${error}`
			);
		});

	return result;
};

// получение массива ордеров мерчанта
export const getMerchantOrders = async (params) => {
	let result = [];
	const { userId, prefix, config } = params;

	const getCurrentOrders_XG = (pageContent) => {
		const $ = cherio.load(pageContent);
		// const count = '1';
		const result = $('#tabactiveTradesCount')
			.text()
			.trim();
		// console.log('activeOrders_XG: ' + result);
		const qwt = 0;
		const count =
			result === `(${qwt})` || result === `${qwt}` ? qwt : qwt + 1;
		// const count = result === '(0)' || result === '0' ? 0 : 1;
		// console.log('activeOrders_XG: ' + count);

		let orders = [];

		if (Number(count) === qwt) {
			orders = getDataFromHTML_XG('tradehistorydiv', html_XG);
		} else if (Number(count) > qwt) {
			orders = [
				{
					amount: '93.46667913',
					asset: 'USDT',
					counterPartyId: '65ba936f73c4111a3c4a3389',
					counterPartyNick: 'XeggeX-User-1a3c4a3389',
					currencyCode: 'RUB',
					currencySymbol: '₽',
					endDate: 0,
					id: '667ad7e6c866ea33f503a729',
					price: '106.99',
					startDate: new Date().getTime(),
					// status: 'Trade Initiated', // Created
					status: 'Trade Completed', // Completed
					type: 'sell',
				},
				{
					amount: '26',
					asset: 'USDT',
					counterPartyId: '63dfbc84d9463e4c197bcbcc',
					counterPartyNick: 'XeggeX-User-4c197bcbcc',
					currencyCode: 'RUB',
					currencySymbol: '₽',
					endDate: 0,
					id: '6638335efa102fcda4ada0b0',
					price: '79.99',
					startDate: new Date().getTime(),
					// status: 'Trade Initiated', // Created
					status: 'Trade Accepted', // Unpaid
					type: 'sell',
				},
				{
					amount: '26',
					asset: 'USDT',
					counterPartyId: '63dfbc84d9463e4c197bcbcc',
					counterPartyNick: 'XeggeX-User-4c197bcbcc',
					currencyCode: 'RUB',
					currencySymbol: '₽',
					endDate: 0,
					id: '6638335efa102fcda4ada0b0',
					price: '79.99',
					startDate: 1714959198195,
					status: 'Trade Cancelled',
					type: 'buy',
				},
			];
			// orders = getDataFromHTML_XG('activetradesdiv', pageContent);
			// console.log(orders);
		}
		return orders;
	};

	const getDataFromHTML_XG = (tagID, pageContent) => {
		const $ = cherio.load(pageContent);
		const orders = [];
		$(`#${tagID} table tbody tr`).each((index, tr) => {
			const trade = {};
			$(tr)
				.find('td')
				.each((index, td) => {
					const nameField = $(td).attr('data-column-id');
					if (nameField === 'user') {
						trade.counterPartyNick = $(td)
							.find('span')
							.text();
						trade.counterPartyId = $(td)
							.find('span a')
							.attr('href')
							.replace('/p2p/profile/', '');
					} else if (nameField === 'time') {
						const startDate = $(td)
							.find('span')
							.text();
						// console.log(startDate)
						// console.log(Date.parse(startDate))
						trade.startDate = Date.parse(startDate);
						if (tagID === 'activetradesdiv') trade.endDate = 0;
					} else if (nameField === 'endtime') {
						const endDate = $(td)
							.find('span')
							.text();
						trade.endDate = Date.parse(endDate);
					} else if (nameField === 'price') {
						const str = $(td)
							.find('span')
							.text();
						// console.log(str);
						const fistSym = str.split('')[0];
						trade.price = str.split(' ')[0].replace(fistSym, '');
						// trade.currencyCode = str.split(' ')[2];
						trade.currencyCode = str.split(' ')[1];
						trade.currencySymbol = fistSym;
					} else if (nameField === 'type') {
						const type = $(td)
							.find('span')
							.text();
						trade.type = type.replace(' Crypto', '').toLowerCase();
					} else if (nameField === 'status') {
						const status = $(td)
							.find('span')
							.text();
						const regex = /\r?\n|\r/g;
						trade.status = regex.test(status)
							? status.replace(regex, '')
							: status;
					} else if (nameField === 'action')
						trade.id = $(td)
							.find('span a')
							.attr('href')
							.replace('/account/p2ptrade/', '');
					else
						trade[nameField] = $(td)
							.find('span')
							.text();
					// console.log(nameField);
				});
			orders.push(trade);
			// console.log(orders[index]);
		});
		return orders;
	};

	// prefix === 'XG' ? console.log(params) : null;
	if (prefix === 'HB') result = htx_orders;
	await axios(config)
		.then((response) => {
			// prefix === 'XG' ? console.log(response.data) : null;
			if (
				prefix === 'BN' ||
				prefix === 'PX' ||
				prefix === 'CX' ||
				prefix === 'MG'
			) {
				result = response.data.data ? response.data.data : [];
			} else if (prefix === 'BN_API' || prefix === 'PX_API') {
				result =
					response.data.message === 'success' ? response.data.data : [];
			} else if (prefix === 'KX') {
				result = response.data.data.items ? response.data.data.items : [];
			} else if (prefix === '_HB') {
				result =
					response.data.success === false || response.data.data[0] === null
						? []
						: response.data.data;
			} else if (prefix === 'BZ' || prefix === 'BZ_API') {
				result = response.data.data ? response.data.data : [];
			} else if (prefix === 'GX') {
				result = response.data ? response.data : [];
			} else if (prefix === 'BT') {
				result =
					response.data.ret_msg === 'SUCCESS'
						? response.data.result.items
						: [];
			} else if (prefix === 'BP') {
				result = response.data.trades;
			} else if (prefix === 'KC') {
				result = response.data.success ? response.data.items : [];
			} else if (prefix === 'AX_API') {
				result = response.data.data;
			} else if (prefix === 'GT') {
				result = response.data.result ? response.data.history_list : [];
			} else if (prefix === 'BG_API') {
				result =
					response.data.msg === 'success'
						? response.data.data.orderList
						: [];
			} else if (prefix === 'CX_API') {
				result = response.data.data;
			} else if (prefix === 'BX') {
				result = response.data.code === 0 ? response.data.data.orders : [];
			} else if (prefix === 'BX_API') {
				// result = response.data.code === 0 ? response.data.data.orders : [];
			} else if (prefix === 'XG_API') {
				result = [{ orderId: '8888888' }];
			} else if (prefix === 'XG') {
				// console.log(response.data);
				result = getCurrentOrders_XG(response.data);
			} else if (prefix === 'CN') {
				result =
					response.data.message === 'Success'
						? response.data.data.orders
						: [];
			} else if (prefix === 'BM') {
				result = response.data.success ? response.data.data.items : [];
			} else if (prefix === 'CM') {
				result =
					response.data.state === 0 ? response.data.result.items : [];
			} else if (prefix === 'XT') {
				result =
					response.data.info === 'Success.' && response.data.code === 200
						? response.data.data.orders
						: [];
			}
		})
		.catch((error) => {
			console.log(
				`=======// ${getTimestamps()} //=======\n****${userId.slice(
					-4
				)} | ${prefix}: getMerchantOrders request Error!\n${error}`
			);
		});
	// console.log(prefix + ': ' + result.length);
	return result;
};

// нормализация массива otc-ордеров пользователя
export const getMerchantOrdersNomalized = (
	orders,
	params,
	arrPayTypes,
	arrOrderStatus
) => {
	const result = [];

	// получение названия и цвета статуса
	const getStatusProps = (strStatus) => {
		const statusProps = { value: '', color: '' };
		for (let i = 0; i < arrOrderStatus.length; i++) {
			const arr = arrOrderStatus[i].values;
			for (let j = 0; j < arr.length; j++) {
				// console.log(params.exchangeId);
				if (
					arr[j].exchangeId === params.exchangeId &&
					arr[j].value === strStatus
				) {
					statusProps.value = arrOrderStatus[i].status;
					statusProps.color = arrOrderStatus[i].colorStatus;
				}
			}
		}
		return statusProps;
	};

	for (let i = 0; i < orders.length; i++) {
		const item = {};
		if (params.prefix === 'BN') {
			const externalPayMethod = orders[i].payMethods
				? orders[i].payMethods.filter((item) => {
						return item.id === orders[i].selectedPayId;
				  })
				: [];
			const PayMethodProps =
				externalPayMethod.length === 0
					? { payId: '', payName: '' }
					: getPayMethodProps(
							params.exchangeId,
							externalPayMethod[0].identifier,
							arrPayTypes
					  );
			const orderStatus =
				typeof orders[i].orderStatus === 'number'
					? orders[i].orderStatus.toString()
					: orders[i].orderStatus;
			item.orderId = orders[i].orderNumber;
			item.statusProps = getStatusProps(orderStatus);
			item.price =
				typeof orders[i].price === 'number'
					? orders[i].price.toString()
					: orders[i].price;
			item.amount =
				typeof orders[i].totalPrice === 'number'
					? orders[i].totalPrice.toString()
					: orders[i].totalPrice; // сумма ордера
			item.volume =
				typeof orders[i].amount === 'number'
					? orders[i].amount.toString()
					: orders[i].amount; // количество крипты
			item.asset = orders[i].asset;
			item.fiat = orders[i].fiat;
			item.tradeType = orders[i].tradeType;
			item.fee = '0';
			item.dateOrder = orders[i].createTime;
			item.payMethodId = PayMethodProps.payId;
			item.payMethodName = PayMethodProps.payName;
			item.conterpartInfo = {
				uid:
					orders[i].tradeType === 'SELL'
						? orders[i].buyerUserNo
						: orders[i].sellerUserNo,
				email: '',
				phone: '',
				realName: '',
				nickName:
					orders[i].tradeType === 'SELL'
						? orders[i].buyerNickname
						: orders[i].sellerNickname,
				bankCart: '',
				clientType: '',
				chatUnreadCount: orders[i].chatUnreadCount
					? orders[i].chatUnreadCount.toString()
					: '0',
				isOnline: '',
				merchant: '',
			};
			item.conterpartStats = {
				registerDays: '',
				finishRateMonth: '',
				completedOrderMonth: '',
			};
		} else if (params.prefix === 'BN_API') {
			const PayMethodProps = { payId: '', payName: '' };
			item.orderId = orders[i].orderNumber;
			item.statusProps = getStatusProps(orders[i].orderStatus);
			item.price = orders[i].unitPrice;
			item.amount = orders[i].totalPrice; // сумма ордера
			item.volume = orders[i].amount; // количество крипты
			item.asset = orders[i].asset;
			item.fiat = orders[i].fiat;
			item.tradeType = orders[i].tradeType;
			item.fee = orders[i].commission;
			item.dateOrder = orders[i].createTime;
			item.payMethodId = PayMethodProps.payId;
			item.payMethodName = PayMethodProps.payName;
			item.conterpartInfo = {
				uid: '',
				email: '',
				phone: '',
				realName: '',
				nickName: orders[i].counterPartNickName,
				bankCart: '',
				clientType: '',
				chatUnreadCount: '0',
				isOnline: '',
				merchant: '',
			};
			item.conterpartStats = {
				registerDays: '',
				finishRateMonth: '',
				completedOrderMonth: '',
			};
		} else if (params.prefix === 'HB') {
			const fiat = orders[i].quoteAssetName;
			const payItem = fiat === 'RUB' ? 'SBP - Fast Bank Transfer' : null;
			const PayMethodProps = getPayMethodProps(
				params.exchangeId,
				payItem,
				arrPayTypes
			);
			item.orderId = orders[i].orderId;
			item.statusProps = getStatusProps(orders[i].orderStatus.toString());
			item.price = orders[i].quote;
			item.amount = orders[i].amount; // сумма ордера
			item.volume = orders[i].quantity; // количество крипты
			item.asset = orders[i].cryptoAssetName;
			item.fiat = fiat;
			item.tradeType = orders[i].sideName.toUpperCase();
			item.fee = orders[i].feeList[0].fee;
			item.dateOrder = +orders[i].gmtCreate;
			item.payMethodId = PayMethodProps.payId;
			item.payMethodName = PayMethodProps.payName;
			item.conterpartInfo = {
				uid: orders[i].counterpartUid,
				email: '',
				phone: '',
				realName:
					orders[i].counterpartRealName === null
						? ''
						: orders[i].counterpartRealName,
				nickName: orders[i].counterpartNickName,
				bankCart: '',
				clientType: '',
				chatUnreadCount:
					orders[i].unread === null ? '0' : orders[i].unread,
				isOnline: '',
				merchant: '',
			};
			item.conterpartStats = {
				registerDays: '',
				finishRateMonth: '',
				completedOrderMonth: '',
			};
		} else if (params.prefix === 'KX') {
			let orderStatus = orders[i].orderProcessStatus.toString();
			if (
				orders[i] !== null &&
				orders[i].orderProcessStatus.toString() === '2' &&
				orders[i].orderStatus === 'new' &&
				orders[i].paymentStatus === 'unpaid'
			) {
				orderStatus = '2';
			} else if (
				orders[i] !== null &&
				orders[i].orderProcessStatus.toString() === '2' &&
				orders[i].orderStatus === 'new' &&
				orders[i].paymentStatus === 'paid' &&
				orders[i].appeal === 0
			) {
				orderStatus = '12';
			} else if (orders[i].appeal === 1 || orders[i].appeal === 2) {
				orderStatus = '5';
			}
			const PayMethodProps = getPayMethodProps(
				params.exchangeId,
				null,
				arrPayTypes
			);
			item.orderId = orders[i].id.toString();
			item.statusProps = getStatusProps(orderStatus);
			item.price = orders[i].price;
			item.amount = orders[i].quoteAmount; // сумма ордера
			item.volume = orders[i].baseAmount; // количество крипты
			item.asset = orders[i].baseCurrency.toUpperCase();
			item.fiat = orders[i].quoteCurrency.toUpperCase();
			item.tradeType = orders[i].side.toUpperCase();
			item.fee = '0';
			item.dateOrder = +orders[i].createdDate;
			item.payMethodId = PayMethodProps.payId;
			item.payMethodName = PayMethodProps.payName;
			item.conterpartInfo = {
				uid: orders[i].detailUser.publicUserId,
				email: '',
				phone: '',
				realName: orders[i].detailUser.realName,
				// nickName: orders[i].detailUser.nickName,
				nickName: '',
				bankCart: '',
				clientType: '',
				chatUnreadCount: '',
				isOnline: '',
				merchant: '',
			};
			item.conterpartStats = {
				registerDays: '',
				finishRateMonth: '',
				completedOrderMonth: '',
			};
		} else if (params.prefix === 'BZ') {
			const PayMethodProps = getPayMethodProps(
				params.exchangeId,
				orders[i].paymethod.toString(),
				arrPayTypes
			);
			item.orderId = orders[i].id.toString();
			item.statusProps = getStatusProps(orders[i].status);
			item.price = orders[i].rate;
			item.amount = orders[i].currency.amount; // сумма ордера
			item.volume = orders[i].cryptocurrency.amount; // количество крипты
			item.asset = orders[i].cryptocurrency.code;
			item.fiat = orders[i].currency.code;
			item.tradeType = orders[i].type === 'purchase' ? 'BUY' : 'SELL';
			item.fee = '0';
			item.dateOrder = +orders[i].date;
			item.payMethodId = PayMethodProps.payId;
			item.payMethodName = PayMethodProps.payName;
			item.conterpartInfo = {
				uid: '',
				email: '',
				phone: '',
				realName: '',
				nickName: orders[i].partner,
				bankCart: '',
				clientType: '',
				chatUnreadCount: '',
				isOnline: '',
				merchant: '',
			};
			item.conterpartStats = {
				registerDays: '',
				finishRateMonth: '',
				completedOrderMonth: '',
			};
		} else if (params.prefix === 'GX') {
			const PayMethodProps = getPayMethodProps(
				params.exchangeId,
				null,
				arrPayTypes
			);
			item.orderId = orders[i].id.toString();
			item.statusProps = getStatusProps(orders[i].state);
			item.price = orders[i].price;
			item.amount = orders[i].amount; // сумма ордера
			item.volume = orders[i].volume; // количество крипты
			item.asset = orders[i].currency.toUpperCase();
			item.fiat = orders[i].fiat_currency.toUpperCase();
			item.tradeType = orders[i].direction.toUpperCase();
			item.fee = orders[i].fee;
			item.dateOrder = Date.parse(orders[i].completed_at);
			item.payMethodId = PayMethodProps.payId;
			item.payMethodName = PayMethodProps.payName;
			item.conterpartInfo = {
				uid:
					orders[i].direction === 'buy'
						? orders[i].seller
						: orders[i].buyer,
				email: '',
				phone: '',
				realName: '',
				nickName:
					orders[i].direction === 'buy'
						? orders[i].seller
						: orders[i].buyer,
				bankCart: '',
				clientType: '',
				chatUnreadCount: '',
				isOnline: '',
				merchant: '',
			};
			item.conterpartStats = {
				registerDays: '',
				finishRateMonth: '',
				completedOrderMonth: '',
			};
		} else if (params.prefix === 'BT') {
			const PayMethodProps = {
				payId: '62ab3f114399fc08ec9725b5',
				payName: 'SBP',
			};
			// const PayMethodProps = getPayMethodProps(
			// 	params.exchangeId,
			// 	orders[i].paymentType.toString(),
			// 	arrPayTypes
			// );
			item.orderId = orders[i].id;
			item.statusProps = getStatusProps(orders[i].status.toString());
			item.price = orders[i].price;
			item.amount = orders[i].amount; // сумма ордера
			item.volume = orders[i].notifyTokenQuantity; // количество крипты
			item.asset = orders[i].tokenId;
			item.fiat = orders[i].currencyId;
			item.tradeType = orders[i].side === 0 ? 'BUY' : 'SELL';
			item.fee = orders[i].fee;
			item.dateOrder = Number(orders[i].createDate);
			item.payMethodId = PayMethodProps.payId;
			item.payMethodName = PayMethodProps.payName;
			item.conterpartInfo = {
				uid: orders[i].targetUserId,
				email: '',
				phone: '',
				realName:
					orders[i].side === 1
						? orders[i].sellerRealName
						: orders[i].buyerRealName,
				nickName: orders[i].targetNickName,
				bankCart: '',
				clientType: '',
				chatUnreadCount: '',
				isOnline: '',
				merchant: '',
			};
			item.conterpartStats = {
				registerDays: '',
				finishRateMonth: '',
				completedOrderMonth: '',
			};
		} else if (params.prefix === 'PX' || params.prefix === 'CX') {
			const externalPayMethod = orders[i].payMethods.filter((item) => {
				return item.payMethodId === orders[i].selectedPayId.toString();
			});
			const PayMethodProps =
				externalPayMethod.length === 0
					? { payId: '', payName: '' }
					: getPayMethodProps(
							params.exchangeId,
							externalPayMethod[0].identifier,
							arrPayTypes
					  );
			item.orderId = orders[i].orderNo;
			item.statusProps = getStatusProps(orders[i].orderStatus.toString());
			item.price = orders[i].price;
			item.amount = orders[i].totalPrice; // сумма ордера
			item.volume = orders[i].amount; // количество крипты
			item.asset = orders[i].asset;
			item.fiat = orders[i].fiat;
			item.tradeType = orders[i].tradeType;
			item.fee = '0';
			item.dateOrder = orders[i].confirmPayEndTime;
			item.payMethodId = PayMethodProps.payId;
			item.payMethodName = PayMethodProps.payName;
			item.conterpartInfo = {
				uid:
					orders[i].tradeType === 'SELL'
						? orders[i].buyerUserNo
						: orders[i].sellerUserNo,
				email: '',
				phone: '',
				realName: '',
				nickName:
					orders[i].tradeType === 'SELL'
						? orders[i].buyerNickname
						: orders[i].sellerNickname,
				bankCart: '',
				clientType: '',
				chatUnreadCount: orders[i].chatUnreadCount.toString(),
				isOnline: '',
				merchant: '',
			};
			item.conterpartStats = {
				registerDays: '',
				finishRateMonth: (orders[i].recentExecuteRate / 100).toString(),
				completedOrderMonth: orders[i].recentOrderNum,
			};
		} else if (params.prefix === 'CX_API') {
			const PayMethodProps = { payId: '', payName: '' };
			item.orderId = orders[i].orderNumber;
			item.statusProps = getStatusProps(orders[i].orderStatus.toString());
			item.price = +orders[i].totalPrice / +orders[i].amount;
			item.amount = orders[i].totalPrice; // сумма ордера
			item.volume = orders[i].amount; // количество крипты
			item.asset = orders[i].asset;
			item.fiat = orders[i].fiat;
			item.tradeType = orders[i].tradeType;
			item.fee = orders[i].commission;
			item.dateOrder = orders[i].createTime;
			item.payMethodId = PayMethodProps.payId;
			item.payMethodName = PayMethodProps.payName;
			item.conterpartInfo = {
				uid: '',
				email: '',
				phone: '',
				realName: '',
				nickName:
					orders[i].tradeType === 'BUY'
						? orders[i].sellerNickname
						: orders[i].buyerNickname,
				bankCart: '',
				clientType: '',
				chatUnreadCount: orders[i].chatUnreadCount.toString(),
				isOnline: '',
				merchant: '',
			};
			item.conterpartStats = {
				registerDays: '',
				finishRateMonth: '',
				completedOrderMonth: '',
			};
		} else if (params.prefix === 'MG') {
			const PayMethodProps = getPayMethodProps(
				params.exchangeId,
				null,
				arrPayTypes
			);
			item.orderId = orders[i].id;
			item.statusProps = getStatusProps(orders[i].state.toString());
			item.price = orders[i].price.toString();
			item.amount = orders[i].amount.toString(); // сумма ордера
			item.volume = orders[i].quantity.toString(); // количество крипты
			item.asset = orders[i].coinName;
			item.fiat = orders[i].currency;
			item.tradeType = orders[i].tradeType === 1 ? 'SELL' : 'BUY';
			item.fee = '0';
			item.dateOrder = orders[i].createTime;
			item.payMethodId = PayMethodProps.payId;
			item.payMethodName = PayMethodProps.payName;
			item.conterpartInfo = {
				uid: orders[i].userInfo.uid
					? orders[i].userInfo.uid.toString()
					: '',
				email: orders[i].userInfo.account,
				phone: orders[i].userInfo.mobile,
				realName: orders[i].userInfo.realName,
				nickName: orders[i].userInfo.nickName,
				bankCart: '',
				clientType: '',
				chatUnreadCount: '0',
				isOnline: '',
				merchant: orders[i].userInfo.merchant,
			};
			item.conterpartStats = {
				registerDays: '',
				finishRateMonth: '',
				completedOrderMonth: '',
			};
		} else if (params.prefix === 'KC') {
			const PayMethodProps = getPayMethodProps(
				params.exchangeId,
				orders[i].payTypeCode,
				arrPayTypes
			);
			const statusProps =
				orders[i].status === 'PAYED_MONEY' &&
				orders[i].appealStatus === 'APPEALING'
					? { value: 'Appealing', color: 'danger' }
					: getStatusProps(orders[i].status);
			item.orderId = orders[i].id;
			item.statusProps = statusProps;
			item.price = orders[i].price;
			item.amount = orders[i].legalCurrencyAmount; // сумма ордера
			item.volume = orders[i].currencyAmount; // количество крипты
			item.asset = orders[i].currency;
			item.fiat = orders[i].legalCurrency;
			item.tradeType = orders[i].buyerRole === false ? 'SELL' : 'BUY';
			item.fee = orders[i].fee;
			item.dateOrder = orders[i].createdAt;
			item.payMethodId = PayMethodProps.payId;
			item.payMethodName = PayMethodProps.payName;
			item.conterpartInfo = {
				uid: '',
				email: '',
				phone: '',
				realName: '',
				nickName: orders[i].opTraderNickName,
				bankCart: '',
				clientType: '',
				chatUnreadCount: '0',
				isOnline: false,
				merchant: false,
			};
			item.conterpartStats = {
				registerDays: '',
				finishRateMonth: '',
				completedOrderMonth: '',
			};
		} else if (params.prefix === 'AX') {
			const PayMethodProps = {
				payId: '62ab3f114399fc08ec9725b5',
				payName: 'SBP',
			};
			item.orderId = orders[i].id;
			item.statusProps = getStatusProps(orders[i].status);
			item.price = orders[i].price;
			item.amount = orders[i].amount; // сумма ордера
			item.volume = orders[i].volume; // количество крипты
			item.asset = orders[i].advertisement.base;
			item.fiat = orders[i].advertisement.quote;
			item.tradeType = orders[i].side.toUpperCase();
			item.fee = '0';
			item.dateOrder = orders[i].datetime;
			item.payMethodId = PayMethodProps.payId;
			item.payMethodName = PayMethodProps.payName;
			item.conterpartInfo = {
				uid:
					orders[i].side === 'buy'
						? orders[i].sellUser.id
						: orders[i].buyUser.id,
				email: '',
				phone: '',
				realName: '',
				nickName:
					orders[i].side === 'buy'
						? orders[i].sellUser.username
						: orders[i].buyUser.username,
				bankCart: '',
				clientType: '',
				chatUnreadCount: '0',
				isOnline: '',
				merchant: '',
			};
			item.conterpartStats = {
				registerDays: '',
				finishRateMonth: '',
				completedOrderMonth: '',
			};
		} else if (params.prefix === 'GT') {
			const PayMethodProps = getPayMethodProps(
				params.exchangeId,
				orders[i].pay_type_num[0].toString(),
				arrPayTypes
			);
			item.orderId = orders[i].txid;
			item.statusProps = getStatusProps(orders[i].status_desc);
			item.price = orders[i].rate;
			item.amount = orders[i].total; // сумма ордера
			item.volume = orders[i].amount; // количество крипты
			item.asset = orders[i].currencyType;
			item.fiat = orders[i].want_type;
			item.tradeType = orders[i].is_sell === '0' ? 'BUY' : 'SELL';
			item.fee = '0';
			item.dateOrder = Date.parse(orders[i].timest);
			item.payMethodId = PayMethodProps.payId;
			item.payMethodName = PayMethodProps.payName;
			item.conterpartInfo = {
				uid: orders[i].its_uid,
				email: '',
				phone: '',
				realName: orders[i].its_realname,
				nickName:
					orders[i].its_nick === ''
						? '=== NO_NICKNAME ==='
						: orders[i].its_nick,
				bankCart: '',
				clientType: '',
				chatUnreadCount: '',
				isOnline: '',
				merchant: '',
			};
			item.conterpartStats = {
				registerDays: '',
				finishRateMonth: '',
				completedOrderMonth: '',
			};
		} else if (params.prefix === 'BP') {
			const payItem =
				orders[i].ad.payment_method_banks.length === 0
					? orders[i].ad.payment_method.name
					: orders[i].ad.payment_method_banks[0].name;
			const PayMethodProps = getPayMethodProps(
				params.exchangeId,
				payItem,
				arrPayTypes
			);
			item.orderId = orders[i].id;
			item.statusProps = getStatusProps(orders[i].status);
			item.price = orders[i].price;
			item.amount = orders[i].cost; // сумма ордера
			item.volume = orders[i].amount; // количество крипты
			item.asset = orders[i].ad.crypto_currency_code;
			item.fiat = orders[i].ad.currency_code;
			item.tradeType = orders[i].ad.type === 'Ad::Sell' ? 'SELL' : 'BUY';
			item.fee = '0';
			item.dateOrder = Date.parse(orders[i].created_at);
			item.payMethodId = PayMethodProps.payId;
			item.payMethodName = PayMethodProps.payName;
			item.conterpartInfo = {
				uid: orders[i].contractor.id,
				email: '',
				phone: '',
				realName: '',
				nickName: orders[i].contractor.user_name,
				bankCart: '',
				clientType: '',
				chatUnreadCount: '',
				isOnline: '',
				merchant: '',
			};
			item.conterpartStats = {
				registerDays: Date.parse(orders[i].contractor.email_verified_date),
				finishRateMonth: '',
				completedOrderMonth: orders[i].contractor.trades_count,
			};
		} else if (params.prefix === 'BG') {
			const PayMethodProps = getPayMethodProps(
				params.exchangeId,
				orders[i].paymentInfo.paymethodId,
				arrPayTypes
			);
			item.orderId = orders[i].orderNo;
			item.advId = orders[i].advNo;
			item.statusProps = getStatusProps(orders[i].status);
			item.price = orders[i].price;
			item.amount = orders[i].amount; // сумма ордера
			item.volume = orders[i].count; // количество крипты
			item.asset = orders[i].coin;
			item.fiat = orders[i].fiat;
			item.tradeType = orders[i].side === 'sell' ? 'BUY' : 'SELL';
			item.fee = '0';
			item.dateOrder = Number(orders[i].cTime);
			item.payMethodId = PayMethodProps.payId;
			item.payMethodName = PayMethodProps.payName;
			item.conterpartInfo = {
				uid: '',
				email: '',
				phone: '',
				realName:
					orders[i].side === 'sell'
						? orders[i].sellerRealName
						: orders[i].buyerRealName,
				nickName: '=== NO_NICKNAME ===',
				bankCart: '',
				clientType: '',
				chatUnreadCount: '',
				isOnline: '',
				merchant: '',
			};
			item.conterpartStats = {
				registerDays: '',
				finishRateMonth: '',
				completedOrderMonth: '',
			};
		} else if (params.prefix === 'BX') {
			const getPayMethodRandom = () => {
				const arr = [
					'SBP',
					'Sberbank',
					'Tinkoff Bank',
					'Raiffeisenbank',
					'QIWI',
				];
				const rand = Math.floor(Math.random() * arr.length);
				return arr[rand];
			};
			// console.log(orders[i]);
			const PayMethodProps = getPayMethodProps(
				params.exchangeId,
				getPayMethodRandom(),
				arrPayTypes
			);
			item.orderId = orders[i].orderNo;
			item.statusProps = getStatusProps(orders[i].status.code.toString());
			item.price = orders[i].price.toString();
			item.amount = orders[i].amount.toString(); // сумма ордера
			item.volume = orders[i].number.toString(); // количество крипты
			item.asset = orders[i].coin.name;
			item.fiat = orders[i].tradeCoin.name;
			item.tradeType = orders[i].type === 1 ? 'BUY' : 'SELL';
			item.fee = '0';
			item.dateOrder = Date.parse(orders[i].createTime);
			item.payMethodId = PayMethodProps.payId;
			item.payMethodName = PayMethodProps.payName;
			item.conterpartInfo = {
				uid:
					orders[i].type === 1
						? orders[i].seller.uid
						: orders[i].buyer.uid,
				email: '',
				phone: '',
				realName: '',
				nickName:
					orders[i].type === 1
						? orders[i].seller.nickName
						: orders[i].buyer.nickName,
				bankCart: '',
				clientType: '',
				chatUnreadCount: orders[i].unreadMsgCount.toString(),
				isOnline: '',
				merchant: '',
			};
			item.conterpartStats = {
				registerDays: '',
				finishRateMonth: '',
				completedOrderMonth: '',
			};
		} else if (params.prefix === 'XG') {
			const PayMethodProps = {
				payId: '62ab3f114399fc08ec9725b5',
				payName: 'SBP',
			};
			item.orderId = orders[i].id;
			item.statusProps = getStatusProps(orders[i].status);
			item.price = orders[i].price;
			item.amount = +orders[i].amount * +orders[i].price; // сумма ордера
			item.volume = orders[i].amount; // количество крипты
			item.asset = orders[i].asset;
			item.fiat = orders[i].currencyCode;
			item.tradeType = orders[i].type.toUpperCase();
			item.fee = '0';
			item.dateOrder =
				orders[i].endDate === 0 ? orders[i].startDate : orders[i].endDate;
			item.payMethodId = PayMethodProps.payId;
			item.payMethodName = PayMethodProps.payName;
			item.conterpartInfo = {
				uid: orders[i].counterPartyId,
				email: '',
				phone: '',
				realName: '',
				nickName: orders[i].counterPartyNick,
				bankCart: '',
				clientType: '',
				chatUnreadCount: '0',
				isOnline: '',
				merchant: '',
			};
			item.conterpartStats = {
				registerDays: '',
				finishRateMonth: '',
				completedOrderMonth: '',
			};
		} else if (params.prefix === 'CN') {
			const PayMethodProps = {
				payId: '62ab3f114399fc08ec9725b5',
				payName: 'SBP',
			};
			item.orderId = orders[i].order_id;
			item.statusProps = getStatusProps(orders[i].status);
			item.price = orders[i].price;
			item.amount = orders[i].quote_amount; // сумма ордера
			item.volume = orders[i].base_amount; // количество крипты
			item.asset = orders[i].base;
			item.fiat = orders[i].quote;
			item.tradeType = orders[i].side;
			item.fee = '0';
			item.dateOrder = orders[i].created_at * 1000;
			item.payMethodId = PayMethodProps.payId;
			item.payMethodName = PayMethodProps.payName;
			item.conterpartInfo = {
				uid: orders[i].opponent_user_info.user_id,
				email: '',
				phone: '',
				realName: orders[i].opponent_user_info.kyc_name,
				nickName: orders[i].opponent_user_info.nickname,
				bankCart: '',
				clientType: '',
				chatUnreadCount: '0',
				isOnline: '',
				merchant: '',
			};
			item.conterpartStats = {
				registerDays: '',
				finishRateMonth: '',
				completedOrderMonth: '',
			};
		} else if (params.prefix === 'BM') {
			const PayMethodProps = {
				payId: '62ab3f114399fc08ec9725b5',
				payName: 'SBP',
			};
			item.orderId = orders[i].orderId.toString();
			item.statusProps = getStatusProps(orders[i].stateLabel.toString());
			item.price = orders[i].price;
			item.amount = orders[i].amount; // сумма ордера
			item.volume = orders[i].size; // количество крипты
			item.asset = orders[i].crypto;
			item.fiat = orders[i].currency;
			item.tradeType = orders[i].side.toUpperCase();
			item.fee = '0';
			item.dateOrder = Number(orders[i].createTime);
			item.payMethodId = PayMethodProps.payId;
			item.payMethodName = PayMethodProps.payName;
			item.conterpartInfo = {
				uid: orders[i].counterpartyCid.toString(),
				email: '',
				phone: '',
				realName: '',
				nickName: orders[i].counterpartyName,
				bankCart: '',
				clientType: '',
				chatUnreadCount: '0',
				isOnline: '',
				merchant: '',
			};
			item.conterpartStats = {
				registerDays: '',
				finishRateMonth: '',
				completedOrderMonth: '',
			};
		} else if (params.prefix === 'CM') {
			const PayMethodProps = {
				payId: '62ab3f114399fc08ec9725b5',
				payName: 'SBP',
			};
			item.orderId = orders[i].id.toString();
			item.statusProps = getStatusProps(orders[i].status.value);
			item.price = orders[i].price.split(' ')[0];
			item.amount = orders[i].total.split(' ')[0]; // сумма ордера
			item.volume = orders[i].amount.split(' ')[0]; // количество крипты
			item.asset = orders[i].currency_code;
			item.fiat = orders[i].fiat_currency_code;
			item.tradeType = orders[i].type.toUpperCase();
			item.fee =
				orders[i].amount_with_commission.toString() === '0'
					? orders[i].amount_with_commission.toString()
					: +orders[i].amount.split(' ')[0] -
					  +orders[i].amount_with_commission;
			item.dateOrder = Date.parse(orders[i].created_at);
			item.payMethodId = PayMethodProps.payId;
			item.payMethodName = PayMethodProps.payName;
			item.conterpartInfo = {
				uid: '',
				email: '',
				phone: '',
				realName: '',
				nickName: orders[i].counterparty,
				bankCart: '',
				clientType: '',
				chatUnreadCount: '0',
				isOnline: orders[i].counterparty_is_online,
				merchant: '',
			};
			item.conterpartStats = {
				registerDays: '',
				finishRateMonth: '',
				completedOrderMonth: '',
			};
		} else if (params.prefix === 'XT') {
			const PayMethodProps = {
				payId: '62ab3f114399fc08ec9725b5',
				payName: 'SBP',
			};
			item.orderId = orders[i].id;
			item.statusProps = getStatusProps(orders[i].preStatus.toString());
			item.price = orders[i].price;
			item.amount = orders[i].money; // сумма ордера
			item.volume = orders[i].amount; // количество крипты
			item.asset = orders[i].ad.market.split('_')[0].toUpperCase();
			item.fiat = orders[i].ad.market.split('_')[1].toUpperCase();
			item.tradeType = orders[i].type === '1' ? 'BUY' : 'SELL';
			item.fee = '0';
			item.dateOrder = Number(orders[i].createTime);
			item.payMethodId = PayMethodProps.payId;
			item.payMethodName = PayMethodProps.payName;
			item.conterpartInfo = {
				uid:
					orders[i].type === '1'
						? orders[i].sellUserId
						: orders[i].buyUserId,
				email: '',
				phone: '',
				realName: '',
				nickName:
					orders[i].type === '1'
						? orders[i].sellUserName
						: orders[i].buyUserName,
				bankCart: '',
				clientType: '',
				chatUnreadCount: '0',
				isOnline: '',
				merchant: '',
			};
			item.conterpartStats = {
				registerDays: '',
				finishRateMonth: '',
				completedOrderMonth: '',
			};
		}
		// проверяем не пустой ли объект
		if (Object.keys(item).length !== 0) {
			item.userId = params.userId;
			item.exchange = params.prefix === 'BN_API' ? 'BN' : params.prefix;
			item.exchangeId = params.exchangeId;
			result.push(item);
		}
		// console.log('=====');
		// console.log(orders[i]);
	}
	// params.prefix === 'XT' ? console.log(result[0]) : null;
	return result;
};

// получение массива p2p-ордеров
export const getP2POrders = async (params) => {
	let result = [];
	const { userId, prefix, config } = params;
	// prefix === 'BP_API' ? console.log(config) : null;
	await axios(config)
		.then((response) => {
			// console.log(response.data);
			if (prefix === 'BN' || prefix === 'PX' || prefix === 'KX') {
				result = response.data.data;
			} else if (prefix === 'HB') {
				result = response.data.data;
			} else if (prefix === 'BZ') {
				result = response.data.data;
			} else if (prefix === 'GX') {
				result = response.data;
			} else if (prefix === 'BT') {
				result =
					!response.data.result.items || response.data.result === null
						? []
						: response.data.result.items;
			} else if (prefix === 'BP_API') {
				result = response.data.ads;
			} else if (prefix === 'MG') {
				result =
					response.data.msg === 'success' && response.data.data
						? response.data.data
						: [];
			} else if (prefix === 'KC') {
				result =
					response.data.success && response.data.items
						? response.data.items
						: [];
			} else if (prefix === 'GT') {
				result =
					response.data.result === true ? response.data.push_order : [];
			} else if (prefix === 'BG_API') {
				result =
					response.data.msg === 'success'
						? response.data.data.resultList
						: [];
			}
		})
		.catch((error) => {
			console.log(
				`=======// ${getTimestamps()} //=======\n****${userId.slice(
					-4
				)} | ${prefix}: ${TEXT_CONSTANTS.P2P_ORDERS_ER}\n${error}`
			);
		});

	return result;
};

// нормализация массива p2p-ордеров пользователя
export const getP2POrdersNomalized = (orders, params, arrPayTypes) => {
	const result = [];

	for (let i = 0; i < orders.length; i++) {
		const item = {};
		if (params.prefix === 'BN') {
			const methods = orders[i].adv.tradeMethods.slice();
			// const methods = [];
			const arrPayMethods = methods.map((k, index) => {
				const PayMethodProps = getPayMethodProps(
					params.exchangeId,
					k.identifier,
					arrPayTypes
				);
				return PayMethodProps;
			});
			// ===========================
			item.advId = orders[i].adv.advNo;
			item.price = orders[i].adv.price;
			item.amount = orders[i].adv.surplusAmount; // сумма ордера
			item.asset = orders[i].adv.asset;
			item.fiat = orders[i].adv.fiatUnit;
			item.tradeType = orders[i].adv.tradeType;
			item.minLimit = orders[i].adv.minSingleTransAmount;
			item.maxLimit = orders[i].adv.maxSingleTransAmount;
			item.payMethods = arrPayMethods;
			item.conterpartInfo = {
				uid: orders[i].advertiser.userNo,
				uidPublic: '',
				isMerchant:
					orders[i].advertiser.userType === 'merchant' ? true : false,
				isOnline: '',
				nickName: orders[i].advertiser.nickName,
				realName: '',
				allOrderCount: '',
				monthOrderCount: orders[i].advertiser.monthOrderCount.toString(),
				// finishRate: orders[i].advertiser.monthFinishRate.toString(),
				finishRate: (+orders[i].advertiser.positiveRate)
					.toFixed(2)
					.toString(),
				// registerDays: orders[
				// 	i
				// ].advertiser.userStatsRet.registerDays.toString(),
				registerDays: '',
				// buyOrdersCompleted:
				// 	orders[i].advertiser.userStatsRet
				// 		.completedBuyOrderNumOfLatest0day,
				buyOrdersCompleted: '',
				// sellOrdersCompleted:
				// 	orders[i].advertiser.userStatsRet
				// 		.completedSellOrderNumOfLatest0day,
				sellOrdersCompleted: '',
			};
		} else if (params.prefix === 'HB') {
			const methods = orders[i].payMethods;
			const arrPayMethods = methods.map((item, index) => {
				const PayMethodProps = getPayMethodProps(
					params.exchangeId,
					item.payMethodId.toString(),
					arrPayTypes
				);
				return PayMethodProps;
			});
			// ===========================
			item.advId = orders[i].id.toString();
			item.price = orders[i].price;
			item.amount = orders[i].tradeCount; // сумма ордера
			item.asset = params.asset;
			item.fiat = params.fiat;
			item.tradeType = orders[i].tradeType === 0 ? 'BUY' : 'SELL';
			item.minLimit = orders[i].minTradeLimit;
			item.maxLimit = orders[i].maxTradeLimit;
			item.payMethods = arrPayMethods;
			item.conterpartInfo = {
				uid: orders[i].uid.toString(),
				uidPublic: '',
				isMerchant: orders[i].merchantLevel === 0 ? false : true,
				isOnline: orders[i].isOnline,
				nickName: orders[i].userName,
				realName: '',
				allOrderCount: '',
				monthOrderCount: orders[i].tradeMonthTimes.toString(),
				finishRate: (+orders[i].orderCompleteRate / 100).toString(),
				registerDays: '',
				buyOrdersCompleted: '',
				sellOrdersCompleted: '',
			};
		} else if (params.prefix === 'KX') {
			const methods = orders[i].paymentMethods;
			const arrPayMethods = methods.map((item, index) => {
				const PayMethodProps = getPayMethodProps(
					params.exchangeId,
					item,
					arrPayTypes
				);
				// console.log(item);
				return PayMethodProps;
			});
			// ===========================
			item.advId = orders[i].id;
			item.price = orders[i].price;
			item.amount = orders[i].availableAmount; // сумма ордера
			item.asset = orders[i].baseCurrency.toUpperCase();
			item.fiat = orders[i].quoteCurrency.toUpperCase();
			item.tradeType = orders[i].side.toUpperCase();
			item.minLimit = orders[i].quoteMinAmountPerOrder;
			item.maxLimit = orders[i].quoteMaxAmountPerOrder;
			item.payMethods = arrPayMethods;
			item.conterpartInfo = {
				uid: orders[i].merchantId,
				uidPublic: orders[i].publicUserId,
				isMerchant: orders[i].merchantId === '' ? false : true,
				isOnline: '',
				nickName: orders[i].nickName,
				realName: '',
				allOrderCount: (
					orders[i].cancelledOrderQuantity +
					orders[i].completedOrderQuantity
				).toString(),
				monthOrderCount: (
					orders[i].cancelledOrderQuantity +
					orders[i].completedOrderQuantity
				).toString(),
				finishRate: orders[i].completedRate,
				registerDays: '',
				buyOrdersCompleted: '',
				sellOrdersCompleted: '',
			};
		} else if (params.prefix === 'BZ') {
			// const methods = orders[i].payMethods;
			// const arrPayMethods = methods.map((item, index) => {
			// 	const PayMethodProps = getPayMethodProps(
			// 		params.exchangeId,
			// 		item.payMethodId.toString(),
			// 		arrPayTypes
			// 	);
			// 	return PayMethodProps;
			// });
			const PayMethodProps = getPayMethodProps(
				params.exchangeId,
				orders[i].paymethodId.toString(),
				arrPayTypes
			);
			const one_hour = 60000 * 60;
			const now = new Date().getTime();
			const diff = now - orders[i].ownerLastActivity;
			// ===========================
			item.advId = orders[i].id.toString();
			item.price = orders[i].rate;
			item.amount = orders[i].limitCurrency.max; // сумма ордера
			item.asset = orders[i].cryptocurrency;
			item.fiat = orders[i].currency;
			item.tradeType = orders[i].type === 'purchase' ? 'BUY' : 'SELL';
			item.minLimit = orders[i].limitCurrency.min;
			item.maxLimit = orders[i].limitCurrency.max;
			item.payMethods = [PayMethodProps];
			item.conterpartInfo = {
				uid: orders[i].owner,
				uidPublic: '',
				isMerchant: orders[i].isOwnerVerificated,
				isOnline: diff < one_hour ? true : false,
				nickName: orders[i].owner,
				realName: '',
				allOrderCount: '',
				monthOrderCount: '',
				finishRate: '',
				registerDays: '',
				buyOrdersCompleted: '',
				sellOrdersCompleted: '',
			};
		} else if (params.prefix === 'GX') {
			const arrPayProps = arrPayTypes.filter((item) => {
				return item.payType === params.payMethod;
			});
			// ===========================
			item.advId = orders[i].id.toString();
			item.price = orders[i].price;
			item.amount = orders[i].max; // сумма ордера
			item.asset = orders[i].currency.toUpperCase();
			item.fiat = orders[i].fiat_currency.toUpperCase();
			item.tradeType = orders[i].direction.toUpperCase();
			item.minLimit = orders[i].min;
			item.maxLimit = orders[i].max;
			item.payMethods =
				arrPayProps.length === 0
					? [{ payName: 'Sberbank', payId: '62ab3f114399fc08ec9725b6' }]
					: [
							{
								payName: arrPayProps[0].payType,
								payId: arrPayProps[0].id,
							},
					  ];
			item.conterpartInfo = {
				uid: orders[i].member,
				uidPublic: '',
				isMerchant: orders[i].verified_only,
				isOnline: '',
				nickName: orders[i].member,
				realName: '',
				allOrderCount: '',
				monthOrderCount: '',
				finishRate: '',
				registerDays: '',
				buyOrdersCompleted: '',
				sellOrdersCompleted: '',
			};
		} else if (params.prefix === 'BT') {
			const methods = orders[i].payments;
			const arrPayMethods = methods.map((item, index) => {
				const PayMethodProps = getPayMethodProps(
					params.exchangeId,
					item.toString(),
					arrPayTypes
				);
				return PayMethodProps;
			});
			// ===========================
			item.advId = orders[i].id;
			item.price = orders[i].price;
			item.amount = orders[i].lastQuantity; // сумма ордера
			item.asset = orders[i].tokenId;
			item.fiat = orders[i].currencyId;
			item.tradeType = orders[i].side === 0 ? 'BUY' : 'SELL';
			item.minLimit = orders[i].minAmount;
			item.maxLimit = orders[i].maxAmount;
			item.payMethods = arrPayMethods;
			item.conterpartInfo = {
				uid: orders[i].userId,
				uidPublic: '',
				isMerchant: orders[i].authStatus === 1 ? true : false,
				isOnline: orders[i].isOnline,
				nickName: orders[i].nickName,
				realName: '',
				allOrderCount: '',
				monthOrderCount: orders[i].recentOrderNum.toString(),
				finishRate: (orders[i].recentExecuteRate / 100).toString(),
				registerDays: '',
				buyOrdersCompleted: '',
				sellOrdersCompleted: '',
			};
		} else if (params.prefix === 'BP') {
			const methods = [
				{
					method:
						orders[i].payment_method_bank_code === null
							? orders[i].payment_method_code
							: orders[i].payment_method_bank_code,
				},
			];
			const arrPayMethods = methods.map((k, index) => {
				const PayMethodProps = getPayMethodProps(
					params.exchangeId,
					k.method,
					arrPayTypes
				);
				// console.log(k.method);
				return PayMethodProps;
			});
			// ===========================
			item.advId = orders[i].id;
			item.price = orders[i].price;
			item.amount = orders[i].amount_max;
			item.asset = orders[i].crypto_currency_code;
			item.fiat = orders[i].currency_code;
			item.tradeType = orders[i].type.toUpperCase();
			item.minLimit = orders[i].limit_min;
			item.maxLimit = orders[i].limit_max;
			item.payMethods = arrPayMethods;
			item.conterpartInfo = {
				uid: orders[i].user.id,
				uidPublic: '',
				isMerchant: orders[i].user.is_verified,
				isOnline: orders[i].user.online,
				nickName: orders[i].user.user_name,
				realName: '',
				allOrderCount: orders[i].user.trades_count.toString(),
				monthOrderCount: '',
				finishRate: '',
				registerDays: '',
				buyOrdersCompleted: '',
				sellOrdersCompleted: '',
			};
		} else if (params.prefix === 'PX') {
			const methods = orders[i].adDetailResp.tradeMethods.slice();
			const arrPayMethods = methods.map((k, index) => {
				const PayMethodProps = getPayMethodProps(
					params.exchangeId,
					k.identifier,
					arrPayTypes
				);
				// console.log(k.identifier);
				return PayMethodProps;
			});
			// ===========================
			item.advId = orders[i].adDetailResp.adNo;
			item.price = orders[i].adDetailResp.price;
			item.amount = orders[i].adDetailResp.initAmount;
			item.asset = orders[i].adDetailResp.asset;
			item.fiat = orders[i].adDetailResp.fiatCurrency;
			item.tradeType = orders[i].adDetailResp.tradeType;
			item.minLimit = orders[i].adDetailResp.minSingleTransAmount;
			item.maxLimit = orders[i].adDetailResp.maxSingleTransAmount;
			item.payMethods = arrPayMethods;
			item.conterpartInfo = {
				uid: orders[i].advertiserVo.userNo,
				uidPublic: '',
				isMerchant:
					orders[i].advertiserVo.userIdentity === 'MASS_MERCHANT'
						? true
						: false,
				isOnline:
					orders[i].advertiserVo.makerOnlineStatus.status === 'on'
						? true
						: false,
				nickName: orders[i].advertiserVo.nickName,
				realName: orders[i].advertiserVo.realName,
				allOrderCount:
					orders[i].advertiserVo.userStatsRet.completedOrderNum !== null
						? orders[
								i
						  ].advertiserVo.userStatsRet.completedOrderNum.toString()
						: '',
				monthOrderCount:
					orders[i].advertiserVo.userStatsRet
						.completedOrderNumOfLatest30day !== null
						? orders[
								i
						  ].advertiserVo.userStatsRet.completedOrderNumOfLatest30day.toString()
						: '',
				finishRate:
					orders[i].advertiserVo.userStatsRet.finishRate !== null
						? orders[i].advertiserVo.userStatsRet.finishRate.toString()
						: '',
				registerDays:
					orders[i].advertiserVo.userStatsRet.registerDays !== null
						? orders[i].advertiserVo.userStatsRet.registerDays.toString()
						: '',
				buyOrdersCompleted:
					orders[i].advertiserVo.userStatsRet
						.completedBuyOrderNumOfLatest30day !== null
						? orders[
								i
						  ].advertiserVo.userStatsRet.completedBuyOrderNumOfLatest30day.toString()
						: '',
				sellOrdersCompleted:
					orders[i].advertiserVo.userStatsRet
						.completedSellOrderNumOfLatest30day !== null
						? orders[
								i
						  ].advertiserVo.userStatsRet.completedSellOrderNumOfLatest30day.toString()
						: '',
			};
		} else if (params.prefix === 'MG') {
			const methods = orders[i].payMethod.split(',');
			const arrPayMethods = methods.map((item, index) => {
				const PayMethodProps = getPayMethodProps(
					params.exchangeId,
					item,
					arrPayTypes
				);
				return PayMethodProps;
			});
			const now = new Date().getTime();
			// ===========================
			item.advId = orders[i].id;
			item.price = orders[i].price.toString();
			item.amount = orders[i].availableQuantity.toString(); // сумма ордера
			item.asset = orders[i].coinName;
			item.fiat = orders[i].currency;
			item.tradeType = orders[i].tradeType === 0 ? 'BUY' : 'SELL';
			item.minLimit = orders[i].minTradeLimit.toString();
			item.maxLimit = orders[i].maxTradeLimit.toString();
			item.payMethods = arrPayMethods;
			item.conterpartInfo = {
				uid: orders[i].merchant.memberId,
				uidPublic: '',
				isMerchant: '',
				isOnline: '',
				nickName: orders[i].merchant.nickName,
				realName: '',
				allOrderCount: (
					orders[i].merchantStatistics.totalBuyCount +
					orders[i].merchantStatistics.totalSellCount
				).toString(),
				monthOrderCount: orders[
					i
				].merchantStatistics.doneLastMonthCount.toString(),
				finishRate: orders[i].merchantStatistics.lastMonthCompleteRate,
				registerDays: (
					(now - orders[i].merchant.registry) /
					(60000 * 60 * 24)
				)
					.toFixed()
					.toString(),
				buyOrdersCompleted: orders[
					i
				].merchantStatistics.totalBuyCount.toString(),
				sellOrdersCompleted: orders[
					i
				].merchantStatistics.totalSellCount.toString(),
			};
		} else if (params.prefix === 'KC') {
			const methods = orders[i].adPayTypes.slice();
			const arrPayMethods = methods.map((k, index) => {
				const PayMethodProps = getPayMethodProps(
					params.exchangeId,
					k.payTypeCode,
					arrPayTypes
				);
				// console.log(k.payTypeCode);
				return PayMethodProps;
			});
			// удаление дублей
			const tempObj = {};
			const uniqueItems = arrPayMethods.filter(
				({ payId }) => !tempObj[payId] && (tempObj[payId] = 1)
			);
			// ===========================
			item.advId = orders[i].id;
			item.price =
				orders[i].limitPrice === null
					? orders[i].floatPrice
					: orders[i].limitPrice;
			item.amount = orders[i].currencyBalanceQuantity; // сумма ордера
			item.asset = orders[i].currency;
			item.fiat = orders[i].legal;
			item.tradeType = orders[i].side;
			item.minLimit = orders[i].limitMinQuote;
			item.maxLimit = orders[i].limitMaxQuote;
			item.payMethods = uniqueItems;
			item.conterpartInfo = {
				uid: orders[i].userId,
				uidPublic: '',
				isMerchant: orders[i].goldMerchants === 0 ? false : true,
				isOnline: '',
				nickName: orders[i].nickName,
				realName: '',
				allOrderCount: '',
				monthOrderCount: orders[i].dealOrderNum,
				finishRate:
					orders[i].dealOrderRate === null
						? '0'
						: orders[i].dealOrderRate.replace('%', '') / 100,
				registerDays: '',
				buyOrdersCompleted: '',
				sellOrdersCompleted: '',
			};
		} else if (params.prefix === 'GT') {
			if (params.tradeType === orders[i].type) {
				const limits = orders[i].limit_total.split('~');
				const methods = orders[i].pay_type_num.split(',');
				const arrPayMethods = methods.map((item, index) => {
					const PayMethodProps = getPayMethodProps(
						params.exchangeId,
						item.toString(),
						arrPayTypes
					);
					return PayMethodProps;
				});
				const now = new Date().getTime();
				// ===========================
				item.advId = orders[i].oid;
				item.price = orders[i].rate;
				item.amount = orders[i].amount; // сумма ордера
				item.asset = orders[i].curr_a;
				item.fiat = orders[i].curr_b;
				item.tradeType = orders[i].type.toUpperCase();
				item.minLimit = limits[0] * orders[i].rate;
				item.maxLimit = limits[1] * orders[i].rate;
				item.payMethods = arrPayMethods;
				item.conterpartInfo = {
					uid: orders[i].uid,
					uidPublic: '',
					isMerchant: orders[i].tier === '3' ? true : false,
					isOnline: orders[i].is_online === 1 ? true : false,
					nickName: orders[i].username,
					realName: '',
					allOrderCount: orders[i].complete_number,
					monthOrderCount: orders[i].complete_number_month,
					finishRate: '1',
					registerDays: (
						(now - Date.parse(orders[i].user_timest)) /
						(60000 * 60 * 24)
					)
						.toFixed()
						.toString(),
					buyOrdersCompleted: '',
					sellOrdersCompleted: '',
				};
			}
		}
		// проверяем не пустой ли объект
		if (Object.keys(item).length) {
			item.userId = params.userId;
			item.exchange = params.prefix;
			item.exchangeId = params.exchangeId;
			result.push(item);
		}
		// console.log('=====');
		// console.log(orders[i]);
	}
	// console.log(result);
	return result;
};

// получение массива future -Active, -History ордеров пользователя
export const getFutureOrders = async (params) => {
	let result = [];
	const { userId, prefix, config } = params;
	// prefix === 'BG_API' ? console.log(params) : null;
	await axios(config)
		.then((response) => {
			// prefix === 'GX_API' ? console.log(response.data) : null;
			if (
				prefix === 'BN' ||
				prefix === 'HB' ||
				prefix === 'KX' ||
				prefix === 'PX'
			) {
				result = response.data.data ? response.data.data : [];
			} else if (
				prefix === 'BN_API' ||
				prefix === 'BZ' ||
				prefix === 'GX_API'
			) {
				result = response.data ? response.data : [];
			} else if (prefix === 'BT') {
				result = response.data.result ? response.data.result : [];
			} else if (prefix === 'BT_API') {
				if (response.data.retMsg === 'Your api key has expired.') {
					console.log(`${prefix}: ${response.data.retMsg}`);
				}
				result =
					response.data.retMsg === 'OK' ? response.data.result.list : [];
			} else if (prefix === 'MG') {
				result = response.data.data.resultList
					? response.data.data.resultList
					: [];
			} else if (prefix === 'KC') {
				result = response.data.success ? response.data.items : [];
			} else if (prefix === 'GT') {
				result = response.data.data;
			} else if (prefix === 'BG_API') {
				// console.log(response.data);
				result = response.data.msg === 'success' ? response.data.data : [];
			}
		})
		.catch((error) => {
			console.log(
				`=======// ${getTimestamps()} //=======\n****${userId.slice(
					-4
				)} | ${prefix}: ${TEXT_CONSTANTS.SPOT_ORDERS_ER}\n${error}`
			);
		});
	return result;
};

// нормализация массива future-ордеров пользователя
export const getFutureOrdersNomalized = (params) => {
	const { arr, prefix, tickers } = params;
	const result = [];

	for (let i = 0; i < arr.length; i++) {
		const item = {};
		if (prefix === 'BN') {
		} else if (prefix === 'history_KX') {
			if (instType === 'SWAP') {
				item.orderId = arr[i].ordId;
				item.price = arr[i].fillPx;
				item.volume = arr[i].fillSz;
				item.tradeType = arr[i].ordType === 'limit' ? 'MAKER' : 'TAKER';
				item.sideType = arr[i].side.toUpperCase();
				item.ticker = arr[i].instId.replace('-', '');
				item.feeUSDT = getValuationUSDT(
					tickers,
					arr[i].feeCcy,
					Math.abs(arr[i].fee)
				);
				item.dateOrder = Number(arr[i].fillTime);
			}
		}
		// проверяем не пустой ли объект
		if (Object.keys(item).length) {
			item.userId = params.userId;
			item.exchange = params.shortName;
			item.exchangeId = params.exchangeId;
			result.push(item);
		}
	}
	return result;
};

// получение массива spot -Active, -History ордеров пользователя
export const getSpotOrders = async (params) => {
	let result = [];
	const { userId, prefix, config } = params;

	// prefix === 'HB_API' ? console.log(config) : null;
	await axios(config)
		.then((response) => {
			// prefix === 'MG_API' ? console.log(response.data) : null;
			if (
				prefix === 'BN' ||
				prefix === 'HB' ||
				prefix === 'KX' ||
				prefix === 'PX' ||
				prefix === 'CX'
			) {
				result = response.data.data ? response.data.data : [];
			} else if (
				prefix === 'BN_API' ||
				prefix === 'BZ' ||
				prefix === 'GX_API' ||
				prefix === 'XG_API'
			) {
				result = response.data ? response.data : [];
			} else if (prefix === 'HB_API') {
				result = response.data.status === 'ok' ? response.data.data : [];
			} else if (prefix === 'BT') {
				result =
					response.data.retMsg === 'Success'
						? response.data.result.result
						: [];
			} else if (prefix === 'BT_API') {
				if (response.data.retMsg === 'Your api key has expired.') {
					console.log(`${prefix}: ${response.data.retMsg}`);
				}
				result =
					response.data.retMsg === 'OK' ? response.data.result.list : [];
			} else if (prefix === 'MG') {
				result = response.data.data.resultList
					? response.data.data.resultList
					: [];
			} else if (prefix === 'MG_API') {
				// console.log(response.data);
				result = response.data;
			} else if (prefix === 'KC') {
				result = response.data.success ? response.data.items : [];
			} else if (prefix === 'GT') {
				result = response.data.code === 0 ? response.data.data : [];
			} else if (prefix === 'GT_API') {
				result = [];
			} else if (prefix === 'BG_API') {
				// console.log(response.data);
				result = response.data.msg === 'success' ? response.data.data : [];
			} else if (prefix === 'AX_API') {
				result = response.data.data;
			} else if (prefix === 'BX_API') {
				// console.log(response.data.data.orders);
				result = response.data.code === 0 ? response.data.data.orders : [];
			}
		})
		.catch((error) => {
			console.log(
				`=======// ${getTimestamps()} //=======\n****${userId.slice(
					-4
				)} | ${prefix}: ${TEXT_CONSTANTS.SPOT_ORDERS_ER}\n${error}`
			);
		});
	return result;
};

// нормализация массива spot-ордеров пользователя
export const getSpotOrdersNomalized = (arr, params, tickers) => {
	// Получение наименований крипты
	// const getBaseQuoteAssets = (ticker) => {
	// 	const result = { baseAsset: '', quoteAsset: '' };
	// 	if (
	// 		ticker.slice(0, 4) === 'USDT' ||
	// 		ticker.slice(0, 4) === 'USDC' ||
	// 		ticker.slice(0, 4) === 'USDD' ||
	// 		ticker.slice(0, 4) === 'BUSD' ||
	// 		ticker.slice(0, 4) === 'DASH' ||
	// 		ticker.slice(0, 4) === 'DOGE' ||
	// 		ticker.slice(0, 4) === 'SHIB' ||
	// 		ticker.slice(0, 4) === 'OCTA' ||
	// 		ticker.slice(0, 4) === 'ETHW'
	// 	) {
	// 		result.baseAsset = ticker.slice(0, 4); // asset
	// 		result.quoteAsset = ticker.slice(4); // fiat
	// 	} else if (ticker.slice(0, 2) === 'MX') {
	// 		result.baseAsset = ticker.slice(0, 2);
	// 		result.quoteAsset = ticker.slice(2);
	// 	} else {
	// 		result.baseAsset = ticker.slice(0, 3);
	// 		result.quoteAsset = ticker.slice(3);
	// 	}
	// 	return result;
	// };

	const result = [];

	for (let i = 0; i < arr.length; i++) {
		const item = {};
		if (params.flag === 'BN') {
			item.orderId = arr[i].orderIdStr;
			item.price = arr[i].price;
			item.volume = arr[i].origQty;
			item.tradeType = arr[i].type;
			item.sideType = arr[i].side;
			item.baseAsset = arr[i].baseAsset;
			item.quoteAsset = arr[i].quoteAsset;
			item.ticker = arr[i].symbol;
			item.dateOrder = arr[i].time;
		} else if (params.flag === 'active_BN_API') {
			item.orderId = arr[i].orderId.toString();
			item.price = arr[i].price;
			item.volume = arr[i].origQty;
			item.tradeType = arr[i].type;
			item.sideType = arr[i].side;
			item.baseAsset = getBaseQuoteAssets(arr[i].symbol).baseAsset;
			item.quoteAsset = getBaseQuoteAssets(arr[i].symbol).quoteAsset;
			item.ticker = arr[i].symbol;
			item.dateOrder = arr[i].time;
		} else if (params.flag === 'history_BN') {
			item.orderId = arr[i].tradeIdStr;
			item.price = arr[i].price;
			item.volume = arr[i].qty;
			item.tradeType = arr[i].role;
			item.sideType = arr[i].side;
			item.baseAsset = getBaseQuoteAssets(arr[i].symbol).baseAsset;
			item.quoteAsset = getBaseQuoteAssets(arr[i].symbol).quoteAsset;
			item.ticker = arr[i].symbol;
			item.feeUSDT = getValuationUSDT(
				tickers,
				arr[i].feeAsset,
				arr[i].fee
			);
			item.dateOrder = arr[i].time;
		} else if (params.flag === 'active_HB') {
			const ticker = arr[i].symbol.toUpperCase();
			const str = arr[i].type.split('-');
			item.orderId = arr[i].id.toString();
			item.price = arr[i].price;
			item.volume = arr[i].amount;
			item.tradeType = str[1].toUpperCase();
			item.sideType = str[0].toUpperCase();
			item.baseAsset = getBaseQuoteAssets(ticker).baseAsset;
			item.quoteAsset = getBaseQuoteAssets(ticker).quoteAsset;
			item.ticker = ticker;
			item.dateOrder = arr[i]['created-at'];
		} else if (params.flag === 'history_HB') {
			const ticker = arr[i].symbol.toUpperCase();
			const tradeType = arr[i].type.split('-')[1];
			item.orderId = arr[i].id.toString();
			item.price = arr[i].price;
			item.volume = arr[i].amount;
			item.tradeType = tradeType === 'limit' ? 'MAKER' : 'TAKER';
			item.sideType = arr[i].type.split('-')[0].toUpperCase();
			item.baseAsset = getBaseQuoteAssets(ticker).baseAsset;
			item.quoteAsset = getBaseQuoteAssets(ticker).quoteAsset;
			item.ticker = ticker;
			item.feeUSDT = arr[i]['field-fees'];
			item.dateOrder = arr[i]['finished-at'];
		} else if (params.flag === 'active_HB_API') {
			const ticker = arr[i].symbol.toUpperCase();
			const str = arr[i].type.split('-');
			item.orderId = arr[i].id.toString();
			item.price = arr[i].price;
			item.volume = arr[i]['amount'];
			item.tradeType = str[1].toUpperCase();
			item.sideType = str[0].toUpperCase();
			item.baseAsset = getBaseQuoteAssets(ticker).baseAsset;
			item.quoteAsset = getBaseQuoteAssets(ticker).quoteAsset;
			item.ticker = ticker;
			item.dateOrder = arr[i]['created-at'];
		} else if (params.flag === 'history_HB_API') {
			if (arr[i].state === 'filled') {
				const ticker = arr[i].symbol.toUpperCase();
				const str = arr[i].type.split('-');
				item.orderId = arr[i].id.toString();
				item.price = arr[i].price;
				item.volume = arr[i].amount;
				item.tradeType =
					str[1].toUpperCase() === 'LIMIT' ? 'MAKER' : 'TAKER';
				item.sideType = str[0].toUpperCase();
				item.baseAsset = getBaseQuoteAssets(ticker).baseAsset;
				item.quoteAsset = getBaseQuoteAssets(ticker).quoteAsset;
				item.ticker = ticker;
				item.feeUSDT = arr[i]['field-fees'];
				item.dateOrder = arr[i]['finished-at'];
			}
		} else if (params.flag === 'active_KX') {
			const ticker = arr[i].instId.replace('-', '');
			item.orderId = arr[i].ordId;
			item.price = arr[i].px;
			item.volume = arr[i].sz;
			item.tradeType = arr[i].ordType.toUpperCase();
			item.sideType = arr[i].side.toUpperCase();
			item.baseAsset = getBaseQuoteAssets(ticker).baseAsset;
			item.quoteAsset = getBaseQuoteAssets(ticker).quoteAsset;
			item.ticker = ticker;
			item.dateOrder = Number(arr[i].cTime);
		} else if (params.flag === 'history_KX') {
			if (arr[i].instType === 'SPOT') {
				const ticker = arr[i].instId.replace('-', '');
				item.orderId = arr[i].ordId;
				item.price = arr[i].fillPx;
				item.volume = arr[i].fillSz;
				item.tradeType = arr[i].ordType === 'limit' ? 'MAKER' : 'TAKER';
				item.sideType = arr[i].side.toUpperCase();
				item.baseAsset = getBaseQuoteAssets(ticker).baseAsset;
				item.quoteAsset = getBaseQuoteAssets(ticker).quoteAsset;
				item.ticker = ticker;
				item.feeUSDT = getValuationUSDT(
					tickers,
					arr[i].feeCcy,
					Math.abs(arr[i].fee)
				);
				item.dateOrder = Number(arr[i].fillTime);
			}
		} else if (params.flag === 'active_BZ') {
			if (arr[i].state === 'wait') {
				const ticker = arr[i].market.replace('_', '').toUpperCase();
				item.orderId = arr[i].id.toString();
				item.price = arr[i].price;
				item.volume = arr[i].origin_volume;
				item.tradeType = arr[i].ord_type.toUpperCase();
				item.sideType = arr[i].side.toUpperCase();
				item.baseAsset = getBaseQuoteAssets(ticker).baseAsset;
				item.quoteAsset = getBaseQuoteAssets(ticker).quoteAsset;
				item.ticker = ticker;
				item.dateOrder = Number(new Date(arr[i].created_at));
			}
		} else if (params.flag === 'history_BZ') {
			if (item.orderId) {
				const ticker = arr[i].market.replace('_', '').toUpperCase();
				item.orderId = arr[i].id.toString();
				item.price = arr[i].price;
				item.volume = arr[i].amount;
				item.tradeType = 'MAKER';
				item.sideType = arr[i].side.toUpperCase();
				item.baseAsset = getBaseQuoteAssets(ticker).baseAsset;
				item.quoteAsset = getBaseQuoteAssets(ticker).quoteAsset;
				item.ticker = ticker;
				item.feeUSDT = getValuationUSDT(tickers, 'USDT', arr[i].fee);
				item.dateOrder = Number(new Date(arr[i].created_at));
			}
		} else if (params.flag === 'active_GX') {
			const ticker = arr[i].market.toUpperCase();
			item.orderId = arr[i].id.toString();
			item.price = arr[i].fix_price;
			item.volume = arr[i].volume;
			item.tradeType = arr[i].ord_type.toUpperCase();
			item.sideType = arr[i].side === 'bid' ? 'BUY' : 'SELL';
			item.baseAsset = getBaseQuoteAssets(ticker).baseAsset;
			item.quoteAsset = getBaseQuoteAssets(ticker).quoteAsset;
			item.ticker = ticker;
			item.dateOrder = Number(new Date(arr[i].created_at));
		} else if (params.flag === 'history_GX') {
			const ticker = arr[i].market.toUpperCase();
			item.orderId = arr[i].order_id.toString();
			item.price = arr[i].price;
			item.volume = arr[i].funds;
			item.tradeType = 'MAKER';
			item.sideType = arr[i].side.toUpperCase();
			item.baseAsset = getBaseQuoteAssets(ticker).baseAsset;
			item.quoteAsset = getBaseQuoteAssets(ticker).quoteAsset;
			item.ticker = ticker;
			item.feeUSDT = getValuationUSDT(
				tickers,
				arr[i].funds_currency.toUpperCase(),
				arr[i].fee_size
			);
			item.dateOrder = Date.parse(arr[i].created_at);
		} else if (params.flag === 'active_BT') {
			item.orderId = arr[i].orderId;
			item.price = arr[i].price;
			item.volume = arr[i].origQty;
			item.tradeType = arr[i].type.toUpperCase();
			item.sideType = arr[i].side.toUpperCase();
			item.baseAsset = arr[i].baseTokenName;
			item.quoteAsset = arr[i].quoteTokenName;
			item.ticker = arr[i].symbolName;
			item.dateOrder = Number(arr[i].time);
		} else if (params.flag === 'active_BT_API') {
			const ticker = arr[i].symbol;
			item.orderId = arr[i].orderId;
			item.price = arr[i].price;
			item.volume = arr[i].qty;
			item.tradeType = arr[i].orderType.toUpperCase();
			item.sideType = arr[i].side.toUpperCase();
			item.baseAsset = getBaseQuoteAssets(ticker).baseAsset;
			item.quoteAsset = getBaseQuoteAssets(ticker).quoteAsset;
			item.ticker = ticker;
			item.dateOrder = Number(arr[i].createdTime);
		} else if (params.flag === 'history_BT') {
			item.orderId = arr[i].tradeId;
			item.price = arr[i].price;
			item.volume = arr[i].quantity;
			item.tradeType = arr[i].type === 'Limit' ? 'MAKER' : 'TAKER';
			item.sideType = arr[i].side.toUpperCase();
			item.baseAsset = arr[i].baseTokenName;
			item.quoteAsset = arr[i].quoteTokenName;
			item.ticker = arr[i].symbolName;
			item.feeUSDT = getValuationUSDT(
				tickers,
				arr[i].feeTokenName,
				arr[i].fee
			);
			item.dateOrder = Number(arr[i].time);
		} else if (params.flag === 'history_BT_API') {
			if (arr[i].orderStatus === 'Filled') {
				const ticker = arr[i].symbol;
				item.orderId = arr[i].orderId;
				item.price = arr[i].price;
				item.volume = arr[i].qty;
				item.tradeType = arr[i].orderType === 'Limit' ? 'MAKER' : 'TAKER';
				item.sideType = arr[i].side.toUpperCase();
				item.baseAsset = getBaseQuoteAssets(ticker).baseAsset;
				item.quoteAsset = getBaseQuoteAssets(ticker).quoteAsset;
				item.ticker = ticker;
				item.feeUSDT = getValuationUSDT(
					tickers,
					item.quoteAsset,
					((item.price * item.volume) / 100) * 0.1
				);
				item.dateOrder = Number(arr[i].createdTime);
			}
		} else if (params.flag === 'active_PX') {
			item.orderId = arr[i].orderNo;
			item.price = arr[i].price;
			item.volume = arr[i].origQty;
			item.tradeType = arr[i].type;
			item.sideType = arr[i].side;
			item.baseAsset = arr[i].baseAsset;
			item.quoteAsset = arr[i].quoteAsset;
			item.ticker = arr[i].symbol;
			item.dateOrder = arr[i].createTime;
		} else if (params.flag === 'history_PX') {
			item.orderId = arr[i].tradeIdStr;
			item.price = arr[i].price;
			item.volume = arr[i].qty;
			item.tradeType = arr[i].role.toUpperCase();
			item.sideType = arr[i].side;
			item.baseAsset = arr[i].baseAsset;
			item.quoteAsset = arr[i].quoteAsset;
			item.ticker = arr[i].symbol;
			item.feeUSDT = getValuationUSDT(
				tickers,
				arr[i].feeAsset,
				arr[i].fee
			);
			item.dateOrder = arr[i].time;
		} else if (params.flag === 'active_MG') {
			const ticker = arr[i].symbol.replace('_', '');
			item.orderId = arr[i].id;
			item.price = arr[i].price;
			item.volume = arr[i].quantity;
			item.tradeType = arr[i].orderType === '1' ? 'LIMIT' : 'STOP';
			item.sideType = arr[i].tradeType === '1' ? 'BUY' : 'SELL';
			item.baseAsset = arr[i].currency;
			item.quoteAsset = arr[i].market;
			item.ticker = ticker;
			item.dateOrder = Number(arr[i].createTime);
		} else if (params.flag === 'history_MG') {
			const ticker = arr[i].symbol.replace('_', '');
			item.orderId = arr[i].id;
			item.price = arr[i].price;
			item.volume = arr[i].quantity;
			item.tradeType = arr[i].isTaker === 0 ? 'MAKER' : 'TAKER';
			item.sideType = arr[i].tradeType;
			item.baseAsset = getBaseQuoteAssets(ticker).baseAsset;
			item.quoteAsset = getBaseQuoteAssets(ticker).quoteAsset;
			item.ticker = ticker;
			item.feeUSDT = getValuationUSDT(
				tickers,
				arr[i].feeCurrency,
				Number(arr[i].fee)
			);
			item.dateOrder = arr[i].createTime;
		} else if (params.flag === 'active_MG_API') {
			const ticker = arr[i].symbol;
			item.orderId = arr[i].orderId;
			item.price = arr[i].price;
			item.volume = arr[i].origQty;
			item.tradeType = arr[i].type;
			item.sideType = arr[i].side;
			item.baseAsset = getBaseQuoteAssets(ticker).baseAsset;
			item.quoteAsset = getBaseQuoteAssets(ticker).quoteAsset;
			item.ticker = ticker;
			item.dateOrder = Number(arr[i].time);
		} else if (params.flag === 'history_MG_API') {
			const ticker = arr[i].symbol;
			item.orderId = arr[i].id;
			item.price = arr[i].price;
			item.volume = arr[i].qty;
			item.tradeType = arr[i].isMaker === true ? 'MAKER' : 'TAKER';
			item.sideType = arr[i].isBuyer === true ? 'BUY' : 'SELL';
			item.baseAsset = getBaseQuoteAssets(ticker).baseAsset;
			item.quoteAsset = getBaseQuoteAssets(ticker).quoteAsset;
			item.ticker = ticker;
			item.feeUSDT = getValuationUSDT(
				tickers,
				arr[i].commissionAsset,
				Number(arr[i].commission)
			);
			item.dateOrder = arr[i].time;
		} else if (params.flag === 'active_KC') {
			const ticker = arr[i].symbol.replace('-', '');
			item.orderId = arr[i].id;
			item.price = arr[i].price;
			item.volume = arr[i].size;
			item.tradeType = arr[i].type.toUpperCase();
			item.sideType = arr[i].side.toUpperCase();
			item.baseAsset = getBaseQuoteAssets(ticker).baseAsset;
			item.quoteAsset = getBaseQuoteAssets(ticker).quoteAsset;
			item.ticker = ticker;
			item.dateOrder = arr[i].orderTime;
		} else if (params.flag === 'history_KC') {
			const ticker = arr[i].symbol.replace('-', '');
			item.orderId = arr[i].orderId;
			item.price = arr[i].price;
			item.volume = arr[i].size;
			item.tradeType = arr[i].liquidity.toUpperCase();
			item.sideType = arr[i].side.toUpperCase();
			item.baseAsset = getBaseQuoteAssets(ticker).baseAsset;
			item.quoteAsset = getBaseQuoteAssets(ticker).quoteAsset;
			item.ticker = ticker;
			item.feeUSDT = getValuationUSDT(
				tickers,
				arr[i].feeCurrency,
				Number(arr[i].fee)
			);
			item.dateOrder = arr[i].createdAt;
		} else if (params.flag === 'active_GT') {
			item.orderId = arr[i].id.toString();
			item.price = arr[i].price;
			item.volume = arr[i].amount;
			item.tradeType = arr[i].orderType === 1 ? 'LIMIT' : 'STOP';
			item.sideType = arr[i].side === 1 ? 'BUY' : 'SELL';
			item.baseAsset = arr[i].currencyType;
			item.quoteAsset = arr[i].exchangeType;
			item.ticker = arr[i].currencyType + arr[i].exchangeType;
			item.dateOrder = new Date().getTime() - arr[i].ctime;
		} else if (params.flag === 'history_GT') {
			if (arr[i].order_status === 'Done') {
				item.orderId = arr[i].id.toString();
				item.price = arr[i].price;
				item.volume = arr[i].amount;
				item.tradeType = arr[i].orderType === 1 ? 'MAKER' : 'TAKER';
				item.sideType = arr[i].side === 1 ? 'BUY' : 'SELL';
				item.baseAsset = arr[i].currencyType;
				item.quoteAsset = arr[i].exchangeType;
				item.ticker = arr[i].currencyType + arr[i].exchangeType;
				item.feeUSDT = getValuationUSDT(
					tickers,
					'USDT',
					+item.price * +item.volume * 0.001
				);
				item.dateOrder = new Date().getTime();
			}
		} else if (params.flag === 'active_AX_API') {
			item.orderId = arr[i].id;
			item.price = arr[i].price;
			item.volume = arr[i].volume;
			item.tradeType = arr[i].orderType === 'limit' ? 'LIMIT' : 'STOP';
			item.sideType = arr[i].side === 'bid' ? 'BUY' : 'SELL';
			item.baseAsset = arr[i].volumeCurrencyId;
			item.quoteAsset = arr[i].amountCurrencyId;
			item.ticker = arr[i].marketId;
			item.dateOrder = Date.parse(arr[i].createdAt);
		} else if (params.flag === 'history_AX_API') {
			item.orderId = arr[i].id;
			item.price = arr[i].price;
			item.volume = arr[i].volume;
			item.tradeType = arr[i].orderType === 'limit' ? 'MAKER' : 'TAKER';
			item.sideType = arr[i].side === 'bid' ? 'BUY' : 'SELL';
			item.baseAsset = arr[i].volumeCurrencyId;
			item.quoteAsset = arr[i].amountCurrencyId;
			item.ticker = arr[i].volumeCurrencyId + arr[i].amountCurrencyId;
			item.feeUSDT = getValuationUSDT(
				tickers,
				arr[i].feeCurrencyId,
				arr[i].fee
			);
			item.dateOrder = Date.parse(arr[i].createdAt);
		} else if (params.flag === 'active_BG_API') {
			const ticker = arr[i].symbol.split('_')[0];
			item.orderId = arr[i].orderId;
			item.price = arr[i].price;
			item.volume = arr[i].quantity;
			item.tradeType = arr[i].orderType.toUpperCase();
			item.sideType = arr[i].side.toUpperCase();
			item.baseAsset = getBaseQuoteAssets(ticker).baseAsset;
			item.quoteAsset = getBaseQuoteAssets(ticker).quoteAsset;
			item.ticker = ticker;
			item.dateOrder = Number(arr[i].cTime);
		} else if (params.flag === 'history_BG_API') {
			if (arr[i].status === 'full_fill') {
				const ticker = arr[i].symbol.split('_')[0];
				item.orderId = arr[i].orderId;
				item.price = arr[i].price;
				item.volume = arr[i].quantity;
				item.tradeType = arr[i].orderType === 'limit' ? 'MAKER' : 'TAKER';
				item.sideType = arr[i].side.toUpperCase();
				item.baseAsset = getBaseQuoteAssets(ticker).baseAsset;
				item.quoteAsset = getBaseQuoteAssets(ticker).quoteAsset;
				item.ticker = ticker;
				item.feeUSDT = getValuationUSDT(
					tickers,
					'USDT',
					+item.price * +item.volume * 0.001
				);
				item.dateOrder = Number(arr[i].cTime);
			}
		} else if (params.flag === 'active_BX_API') {
			const ticker = arr[i].symbol.replace('-', '');
			item.orderId = arr[i].orderId.toString();
			item.price = arr[i].price;
			item.volume = arr[i].origQty;
			item.tradeType = arr[i].type;
			item.sideType = arr[i].side;
			item.baseAsset = getBaseQuoteAssets(ticker).baseAsset;
			item.quoteAsset = getBaseQuoteAssets(ticker).quoteAsset;
			item.ticker = ticker;
			item.dateOrder = Number(arr[i].time);
		} else if (params.flag === 'history_BX_API') {
			const ticker = arr[i].symbol.replace('-', '');
			item.orderId = arr[i].orderId.toString();
			item.price = arr[i].price;
			item.volume = arr[i].origQty;
			item.tradeType = arr[i].type === 'LIMIT' ? 'MAKER' : 'TAKER';
			item.sideType = arr[i].side;
			item.baseAsset = getBaseQuoteAssets(ticker).baseAsset;
			item.quoteAsset = getBaseQuoteAssets(ticker).quoteAsset;
			item.ticker = ticker;
			item.feeUSDT = getValuationUSDT(
				tickers,
				'USDT',
				+item.price * +item.volume * 0.001
			);
			item.dateOrder = arr[i].time;
		} else if (params.flag === 'active_CX') {
			item.orderId = arr[i].orderIdStr;
			item.price = arr[i].price;
			item.volume = arr[i].origQty;
			item.tradeType = arr[i].type;
			item.sideType = arr[i].side;
			item.baseAsset = arr[i].baseAsset;
			item.quoteAsset = arr[i].quoteAsset;
			item.ticker = arr[i].symbol;
			item.dateOrder = arr[i].time;
		} else if (params.flag === 'history_CX') {
			item.orderId = arr[i].tradeIdStr;
			item.price = arr[i].price;
			item.volume = arr[i].qty;
			item.tradeType = arr[i].activeBuy ? 'TAKER' : 'MAKER';
			item.sideType = arr[i].side;
			item.baseAsset = getBaseQuoteAssets(arr[i].symbol).baseAsset;
			item.quoteAsset = getBaseQuoteAssets(arr[i].symbol).quoteAsset;
			item.ticker = arr[i].symbol;
			item.feeUSDT = getValuationUSDT(
				tickers,
				arr[i].feeAsset,
				arr[i].fee
			);
			item.dateOrder = arr[i].time;
		} else if (params.flag === 'active_XG_API') {
			const symbols = arr[i].market.symbol.split('/');
			item.orderId = arr[i].id;
			item.price = arr[i].price;
			item.volume = arr[i].quantity;
			item.tradeType = arr[i].type.toUpperCase();
			item.sideType = arr[i].side.toUpperCase();
			item.baseAsset = symbols[0];
			item.quoteAsset = symbols[1];
			item.ticker = symbols[0] + symbols[1];
			item.dateOrder = arr[i].createdAt;
		} else if (params.flag === 'history_XG_API') {
			const symbols = arr[i].market.symbol.split('/');
			item.orderId = arr[i].id;
			item.price = arr[i].price;
			item.volume = arr[i].quantity;
			item.tradeType = arr[i].triggeredBy === 'buy' ? 'MAKER' : 'TAKER';
			item.sideType = arr[i].side.toUpperCase();
			item.baseAsset = symbols[0];
			item.quoteAsset = symbols[1];
			item.ticker = symbols[0] + symbols[1];
			item.feeUSDT = arr[i].fee;
			item.dateOrder = arr[i].createdAt;
		}
		// проверяем не пустой ли объект
		if (Object.keys(item).length) {
			item.userId = params.userId;
			item.exchange = params.shortName;
			item.exchangeId = params.exchangeId;
			result.push(item);
		}
	}
	return result;
};

// запрос перевода крипты с аккаунта на аккаунт
export const transferAsset = async (config, params) => {
	const { shortName, balances } = params;
	let result;
	for (let i = 0; i < balances.length; i++) {
		if (shortName === 'BN') {
			config.data.asset = balances[i].asset;
			config.data.amount = balances[i].free;
		}
		await axios(config)
			.then((response) => {
				// console.log(response.data);
				result =
					shortName === 'BN' && response.data.success ? true : false;
			})
			.catch((error) => {
				result = false;
				console.log(error);
			});
	}
	return result;
};

// универсальная функция получения балансов spot, p2p, fut
export const getBalance = async (params) => {
	let balance = [];
	const { userId, prefix, config } = params;

	// prefix === 'BT_API' ? console.log(config) : null;
	await axios(config)
		.then((response) => {
			// prefix === 'BT_API' ? console.log(response.data) : null;
			if (prefix === 'BN' || prefix === 'PX' || prefix === 'CX') {
				balance = response.data.data;
			} else if (prefix === 'KX') {
				balance =
					response.data.code === 0 ? response.data.data.balance : [];
			} else if (prefix === 'HB') {
				balance = response.data.data === null ? [] : response.data.data;
			} else if (prefix === 'HB_API') {
				response.data.status === 'ok'
					? (balance = response.data.data)
					: console.log(
							`${prefix}: ${TEXT_CONSTANTS.BALANCE_ER}\n${response.data['err-msg']}`
					  );
			} else if (prefix === 'BZ') {
				balance = response.data.errors ? [] : response.data;
				balance = Array.isArray(balance) ? balance : [];
			} else if (prefix === 'GX') {
				balance = response.data.error ? [] : response.data;
			} else if (prefix === 'BT') {
				balance =
					response.data.result === null ? [] : response.data.result;
			} else if (prefix === 'BT_API') {
				balance =
					response.data.retMsg === 'OK'
						? response.data.result.list[0].coin
						: [];
			} else if (prefix === 'MG') {
				balance = response.data.code === 0 ? response.data.data : [];
				// balance =	response.data.code === 0 ? response.data.data.assets : [];
			} else if (prefix === 'MG_API') {
				balance = response.data.balances ? response.data.balances : [];
			} else if (prefix === 'KC') {
				balance = response.data.success ? response.data.data : [];
			} else if (prefix === 'GT') {
				balance =
					response.data.message === 'success'
						? [
								{
									currency: 'USDT',
									available: '0',
									frozen: response.data.data.spot.usd,
								},
						  ]
						: [];
			} else if (prefix === 'AX_API') {
				balance = response.data.data;
			} else if (prefix === 'BG_API') {
				balance =
					response.data.msg === 'success' ? response.data.data : [];
			} else if (prefix === 'BX') {
				balance =
					response.data.code === 0
						? response.data.data.accountOverviews
						: [];
			} else if (prefix === 'BX_API') {
				balance =
					response.data.code === 0 ? response.data.data.balances : [];
			} else if (prefix === 'BP') {
				balance = response.data.user.balance
					? [
							{
								code: response.data.user.balance.XMR.code,
								value: response.data.user.balance.XMR.value,
							},
							{
								code: response.data.user.balance.USDT.code,
								value: response.data.user.balance.USDT.value,
							},
							{
								code: response.data.user.balance.USDC.code,
								value: response.data.user.balance.USDC.value,
							},
							{
								code: response.data.user.balance.TON.code,
								value: response.data.user.balance.TON.value,
							},
							{
								code: response.data.user.balance.ETH.code,
								value: response.data.user.balance.ETH.value,
							},
							{
								code: response.data.user.balance.BTC.code,
								value: response.data.user.balance.BTC.value,
							},
					  ]
					: [];
			} else if (prefix === 'XG_API') {
				balance = response.data;
			} else if (prefix === 'CN_API') {
				balance = response.data.code === 0 ? response.data.data : [];
				response.data.message === 'access_id not exists'
					? console.log(prefix + ': ' + response.data.message)
					: null;
			} else if (prefix === 'BM_API') {
				balance = response.data.data.wallet;
			} else if (prefix === 'CM') {
				balance =
					response.data.state === 0 ? response.data.result.items : [];
			} else if (prefix === 'CM_API') {
				// balance = response.data.result.balances;
			} else if (prefix === 'XT') {
				balance =
					response.data.mc === 'SUCCESS'
						? response.data.result.assets
						: [];
			}
		})
		.catch((error) => {
			console.log(
				`=======// ${getTimestamps()} //=======\n****${userId.slice(
					-4
				)} | ${prefix}: ${TEXT_CONSTANTS.BALANCE_ER}\n${error}`
			);
		});
	// console.log(balance);
	return balance;
};

// нормализация массива spot- и otc-балансов пользователя
export const getBalancesNormalized = (arr, prefix) => {
	const result = arr.map((item, index) => {
		const itemBalance = {};
		if (prefix === 'MG_spot') {
			itemBalance.currency = item.currency;
			itemBalance.available = item.available;
			itemBalance.frozen = item.frozen;
		} else if (prefix === 'MG_otc') {
			itemBalance.currency = item.coinName;
			itemBalance.available = item.availableBalance;
			itemBalance.frozen = item.frozenBalance;
		} else if (prefix === 'MG_spot_API') {
			itemBalance.currency = item.asset;
			itemBalance.available = item.free;
			itemBalance.frozen = item.locked;
		} else if (prefix === 'BN_spot') {
			itemBalance.currency = item.asset;
			itemBalance.available = item.free;
			itemBalance.frozen = (+item.freeze + +item.locked).toString();
		} else if (prefix === 'BN_otc') {
			itemBalance.currency = item.asset;
			itemBalance.available = item.free;
			itemBalance.frozen = item.freeze;
		} else if (prefix === 'BN_fut') {
			itemBalance.currency = item.asset;
			itemBalance.available = item.walletBalance;
			itemBalance.frozen = item.unrealizedProfit;
		} else if (prefix === 'HB_otc') {
			const sd = 500; // P2P Secutity Deposit
			itemBalance.currency = item.coinName;
			itemBalance.available = (item.total - item.frozen).toString();
			itemBalance.frozen =
				item.coinName === 'USDT'
					? (+item.frozen + sd).toString() // учёт страхового депо
					: item.frozen.toString();
		} else if (prefix === 'KX_spot') {
			itemBalance.currency = item.currency;
			itemBalance.available = item.availBal;
			itemBalance.frozen = item.frozenBal;
		} else if (prefix === 'KX_otc') {
			itemBalance.currency = item.currency;
			itemBalance.available = item.balance.toString();
			itemBalance.frozen = '0';
		} else if (prefix === 'BZ_spot') {
			itemBalance.currency = item.currency_id;
			itemBalance.available = item.market_balance;
			itemBalance.frozen = item.market_hold;
		} else if (prefix === 'BZ_otc') {
			itemBalance.currency = item.currency_id;
			itemBalance.available = item.p2p_balance;
			itemBalance.frozen = item.p2p_hold;
		} else if (prefix === 'GX_otc') {
			itemBalance.currency = item.currency.toUpperCase();
			// itemBalance.available = Math.abs(+item.balance - +item.locked).toString();
			itemBalance.available = item.balance;
			itemBalance.frozen = item.locked;
		} else if (prefix === 'BT_spot_API') {
			itemBalance.currency = item.coin;
			itemBalance.available = item.availableToWithdraw;
			itemBalance.frozen = item.locked;
		} else if (prefix === 'BT_spot') {
			// itemBalance.currency = item.tokenName;
			// itemBalance.available = item.free;
			// itemBalance.frozen = item.locked;
			itemBalance.currency = item.coin;
			itemBalance.available = item.ab;
			itemBalance.frozen = +item.equity - +item.ab;
		} else if (prefix === 'BT_otc') {
			itemBalance.currency = item.currency;
			itemBalance.available = item.balance;
			itemBalance.frozen = item.frozenBalance;
		} else if (prefix === 'BT_fut') {
			itemBalance.currency = 'USDT';
			itemBalance.available = item.originBalance;
			itemBalance.frozen = 0;
		} else if (prefix === 'PX_spot') {
			itemBalance.currency = item.asset;
			itemBalance.available = item.free;
			itemBalance.frozen = (+item.freeze + +item.locked).toString();
		} else if (prefix === 'PX_otc') {
			itemBalance.currency = item.asset;
			itemBalance.available = item.free;
			itemBalance.frozen = item.freeze;
		} else if (prefix === 'KC_spot') {
			itemBalance.currency = item.currency;
			itemBalance.available = item.availableBalance;
			itemBalance.frozen = +item.totalBalance - +item.availableBalance;
		} else if (prefix === 'GT_spot' || prefix === 'GT_otc') {
			itemBalance.currency = item.currency;
			itemBalance.available = item.available;
			itemBalance.frozen = item.frozen;
		} else if (prefix === 'BG_spot' || prefix === 'BG_otc') {
			// const sd = 200+200; // P2P Secutity Deposit USDT+EUR
			itemBalance.currency =
				prefix === 'BG_spot' ? item.coinName : item.coin; // 'BG_otc'
			itemBalance.available = item.available;
			itemBalance.frozen = item.frozen;
		} else if (prefix === 'CX_spot') {
			itemBalance.currency = item.asset;
			itemBalance.available = item.free;
			itemBalance.frozen = (+item.freeze + +item.locked).toString();
		} else if (prefix === 'CX_otc') {
			itemBalance.currency = item.asset;
			itemBalance.available = item.free;
			itemBalance.frozen = item.freeze;
		} else if (prefix === 'BX_spot' || prefix === 'BX_otc') {
			itemBalance.currency = item.assetName;
			itemBalance.available = item.assetAmount;
			itemBalance.frozen = '0';
		} else if (prefix === 'BX_spot_API') {
			itemBalance.currency = item.asset;
			itemBalance.available = +item.free;
			itemBalance.frozen = +item.locked;
		} else if (prefix === 'BP_otc') {
			itemBalance.currency = item.code;
			itemBalance.available = item.value;
			itemBalance.frozen = '0';
		} else if (prefix === 'XG_spot_API') {
			itemBalance.currency = item.asset;
			itemBalance.available = +item.available;
			itemBalance.frozen = +item.held;
		} else if (prefix === 'CN_spot_API') {
			itemBalance.currency = item.ccy;
			itemBalance.available = +item.available;
			itemBalance.frozen = +item.frozen;
		} else if (prefix === 'BM_spot_API') {
			itemBalance.currency = item.currency;
			itemBalance.available = +item.available;
			itemBalance.frozen = +item.frozen;
		} else if (prefix === 'BM_otc') {
			itemBalance.currency = item.asset;
			itemBalance.available = 0;
			itemBalance.frozen = +item.volume;
		} else if (prefix === 'AX_spot_API' || prefix === 'AX_otc_API') {
			itemBalance.currency = item.currencyId;
			itemBalance.available = item.serviceBalance;
			itemBalance.frozen = item.heldBalance;
		} else if (prefix === 'CM_otc') {
			itemBalance.currency = item.currency;
			itemBalance.available = item.balance;
			itemBalance.frozen = 0;
		} else if (prefix === 'CM_otc_API') {
			// itemBalance.currency = item.currencyId;
			// itemBalance.available = item.serviceBalance;
			// itemBalance.frozen = item.heldBalance;
		} else if (prefix === 'XT_spot') {
			itemBalance.currency = item.currency.toUpperCase();
			itemBalance.available = item.availableAmount;
			itemBalance.frozen = item.frozenAmount;
		}
		return itemBalance;
	});
	return result;
};

// получение данных об spot/merchant-ордере
export const getOrderDetails = async (config, shortName, typeOrder) => {
	let orderDetails = {};
	const text =
		typeOrder === 'SPOT'
			? TEXT_CONSTANTS.SPOT_ORDER_DETAILS_ER
			: TEXT_CONSTANTS.USER_ORDER_DETAILS_ER;

	// prefix === 'BT' ? console.log(params) : null;
	await axios(config)
		// prefix === 'BT' ? console.log(response.data) : null;
		.then((response) => {
			// console.log(response.data);
			if (shortName === 'BT') orderDetails = response.data.result;
			// null
			else if (
				shortName === 'BZ' ||
				shortName === 'GX' ||
				shortName === 'AX'
			)
				orderDetails = response.data;
			else if (shortName === 'BP') orderDetails = response.data.trade;
			// BN, HB, KX, PX, MG, KC, GT, BG, CX, BM
			else {
				orderDetails = response.data.data;
			}
		})
		.catch((error) => {
			const time = `=======// ${getTimestamps()} //=======\n`;
			const message = `${shortName}: ${text}\n${error}`;
			console.log(time + message);
		});
	return orderDetails;
};

// нормализация данных полученного merchant-ордера
export const getOrderDetailsNomalized = (params) => {
	const {
		userId,
		shortName,
		exchangeId,
		arrTickers,
		arrPayTypes,
		orderDetails,
	} = params;
	const newOrder = {};

	// получение PayIdHB из ордера
	const getPayIdHB = (userPayId, userPaymentMethods) => {
		let payIdHB = '';
		for (let j = 0; j < userPaymentMethods.length; j++) {
			if (userPaymentMethods[j].id === userPayId)
				payIdHB = userPaymentMethods[j].bankType;
		}
		return payIdHB;
	};

	// Получение строки без спецсимволов
	const normalizeStrBT = (str) => {
		const pattern = /[^a-zа-яё\s]/gi;
		str = str.replace(pattern, '');
		return str;
	};

	// проверка на НЕ пустой объект
	if (Object.keys(orderDetails).length !== 0) {
		newOrder.userId = userId;
		newOrder.exchangeId = exchangeId; // id биржи
		newOrder.exchange = shortName; // биржа

		if (shortName === 'BN') {
			const { asset, fiatUnit, tradeType, orderStatus } = orderDetails;
			const priceAssetUSDT = getTickerPriceUSDT(
				asset,
				fiatUnit,
				arrTickers
			);

			// получение payId, payName для БД
			const payMethodProps = getPayMethodProps(
				exchangeId,
				orderDetails.payType,
				arrPayTypes
			);

			newOrder.orderId = orderDetails.orderNumber; // номер ордера
			newOrder.advId = orderDetails.advOrderNumber; // номер объявления
			newOrder.counterpartId =
				tradeType === 'SELL' // id контрагента
					? orderDetails.buyerUserNo
					: orderDetails.sellerUserNo;
			newOrder.counterpartEmail = ''; // email контрагента
			newOrder.counterpartPhone =
				tradeType === 'SELL' // телефон контрагента
					? orderDetails.buyerMobilePhone
					: orderDetails.sellerMobilePhone;
			newOrder.counterpartNickName =
				tradeType === 'SELL' // никнейм контрагента
					? orderDetails.buyerNickname
					: orderDetails.sellerNickname;
			newOrder.counterpartRealName =
				tradeType === 'SELL' // реальное имя контрагента
					? orderDetails.buyerName
					: orderDetails.sellerName;
			newOrder.counterpartAccount = ''; // карта контрагента
			newOrder.counterpartСlientType = orderDetails.clientType; // клиент контрагента
			newOrder.tradeType = tradeType; // тип ордера																															// тип ордера
			newOrder.payMethodId = payMethodProps.payId; // внутренний id платежного метода
			newOrder.payMethodName = payMethodProps.payName; // внутреннее название платежного метода
			newOrder.payMerchantAccount = getPaySubAccount(payMethodProps.payId); // банк фактического платежа T01, Y02,....
			newOrder.orderStatus = orderDetails.orderStatus.toString(); // id статуса выполнения ордера
			newOrder.orderStatusText = 'Completed'; // название статуса
			newOrder.asset = asset; // криптовалюта ордера
			newOrder.amount = orderDetails.totalPrice; // сумма ордера                					// криптовалюта ордера
			newOrder.volume = orderDetails.amount; // количество крипты
			newOrder.commission = orderDetails.commission.toString(); // комиссия ордера
			newOrder.price = orderDetails.price; // цена ордера asset/fiat
			newOrder.priceAssetUSDT = priceAssetUSDT; // цена ордера asset/USDT
			newOrder.fiat = fiatUnit; // фиатная валюта ордера
			newOrder.dateOrder = orderDetails.createTime; // дата создания ордера на бирже
		} else if (shortName === 'KX') {
			const {
				side,
				orderProcessStatus,
				orderDetailUserVo,
				baseCurrency,
				quoteCurrency,
			} = orderDetails;

			const tradeType = side.toUpperCase();
			const paymentType =
				orderDetailUserVo.sellerSelectedReceiptAccount.type;

			const priceAssetUSDT = getTickerPriceUSDT(
				baseCurrency.toUpperCase(),
				quoteCurrency.toUpperCase(),
				arrTickers
			);

			// получение payId, payName для БД
			const payMethodProps = getPayMethodProps(
				exchangeId,
				paymentType,
				arrPayTypes
			);
			newOrder.orderId = orderDetails.publicOrderId.toString(); // номер ордера
			newOrder.advId = ''; // номер объявления
			newOrder.counterpartId = orderDetails.publicMerchantId; // id контрагента
			newOrder.counterpartEmail = ''; // email контрагента
			newOrder.counterpartPhone = ''; // телефон контрагента
			newOrder.counterpartNickName = orderDetailUserVo.nickName; // никнейм контрагента
			newOrder.counterpartRealName = orderDetailUserVo.realName; // реальное имя контрагента
			newOrder.counterpartAccount = ''; // карта контрагента
			newOrder.counterpartСlientType = ''; // клиент контрагента
			newOrder.tradeType = tradeType; // тип ордера
			newOrder.payMethodId = payMethodProps.payId; // внутренний id платежного метода
			newOrder.payMethodName = payMethodProps.payName; // внутреннее название платежного метода
			newOrder.payMerchantAccount = getPaySubAccount(payMethodProps.payId); // банк фактического платежа T01, Y02,....
			newOrder.orderStatus = orderProcessStatus.toString(); // id статуса выполнения ордера
			newOrder.orderStatusText = 'Completed'; // название статуса
			newOrder.asset = baseCurrency.toUpperCase(); // криптовалюта ордера
			newOrder.amount = orderDetails.quoteAmount; // сумма ордера
			newOrder.volume = orderDetails.baseAmount; // количество крипты
			newOrder.commission = ''; // комиссия ордера
			newOrder.price = orderDetails.price; // цена ордера asset/fiat
			newOrder.priceAssetUSDT = priceAssetUSDT; // цена ордера asset/USDT
			newOrder.fiat = quoteCurrency.toUpperCase(); // фиатная валюта ордера
			newOrder.dateOrder = orderDetails.createdDate; // дата создания ордера на бирже
		} else if (shortName === '_HB') {
			const {
				orderInfo,
				otherInfo,
				c2cOrder,
				paymentMethod,
			} = orderDetails;

			const tradeType = orderInfo.side === 0 ? 'BUY' : 'SELL';
			const payIdHB = getPayIdHB(c2cOrder.buyPayAccount, paymentMethod);

			// получение payId, payName для БД
			const payMethodProps = getPayMethodProps(
				exchangeId,
				payIdHB.toString(),
				arrPayTypes
			);

			const priceAssetUSDT = getTickerPriceUSDT(
				c2cOrder.cryptoAssetName,
				c2cOrder.quoteAssetName,
				arrTickers
			);
			newOrder.orderId = orderInfo.orderId; // номер ордера
			newOrder.advId = ''; // номер объявления
			newOrder.counterpartId = otherInfo.uid.toString(); // id контрагента
			newOrder.counterpartEmail = ''; // email контрагента
			newOrder.counterpartPhone = ''; // телефон контрагента
			newOrder.counterpartNickName = otherInfo.nickName; // никнейм контрагента
			newOrder.counterpartRealName = otherInfo.realName; // реальное имя контрагента
			newOrder.counterpartAccount = ''; // карта контрагента
			newOrder.counterpartСlientType = ''; // клиент контрагента
			newOrder.tradeType = tradeType; // тип ордера																														// тип ордера
			newOrder.payMethodId = payMethodProps.payId; // внутренний id платежного метода
			newOrder.payMethodName = payMethodProps.payName; // внутреннее название платежного метода
			newOrder.payMerchantAccount = getPaySubAccount(payMethodProps.payId); // банк фактического платежа T01, Y02,....
			newOrder.orderStatus = orderInfo.orderStatus.toString(); // id статуса выполнения ордера
			newOrder.orderStatusText = 'Completed'; // название статуса
			newOrder.asset = c2cOrder.cryptoAssetName; // криптовалюта ордера
			newOrder.amount = c2cOrder.amount; // сумма ордера
			newOrder.volume = c2cOrder.quantity; // количество крипты
			newOrder.commission = orderDetails.feeInfo.totalFee; // комиссия ордера
			newOrder.price = c2cOrder.quote; // цена ордера asset/fiat
			newOrder.priceAssetUSDT = priceAssetUSDT; // цена ордера asset/USDT
			newOrder.fiat = c2cOrder.quoteAssetName; // фиатная валюта ордера
			newOrder.dateOrder = Number(orderInfo.gmtCreate); // дата создания ордера на бирже
		} else if (shortName === 'BZ') {
			const { type, currency, cryptocurrency } = orderDetails;
			const tradeType = type === 'purchase' ? 'BUY' : 'SELL';

			// получение payId, payName для БД
			const payMethodProps = getPayMethodProps(
				exchangeId,
				currency.paymethod.toString(),
				arrPayTypes
			);

			const priceAssetUSDT = getTickerPriceUSDT(
				cryptocurrency.code,
				currency.code,
				arrTickers
			);
			newOrder.orderId = orderDetails.id; // номер ордера
			newOrder.advId = ''; // номер объявления
			newOrder.counterpartId = null; // id контрагента
			newOrder.counterpartEmail = ''; // email контрагента
			newOrder.counterpartPhone = ''; // телефон контрагента
			newOrder.counterpartNickName = orderDetails.partner; // никнейм контрагента
			newOrder.counterpartRealName = null; // реальное имя контрагента
			newOrder.counterpartAccount = ''; // карта контрагента
			newOrder.counterpartСlientType = ''; // клиент контрагента
			newOrder.tradeType = tradeType; // тип ордера
			newOrder.payMethodId = payMethodProps.payId; // внутренний id платежного метода
			newOrder.payMethodName = payMethodProps.payName; // внутреннее название платежного метода
			newOrder.payMerchantAccount = getPaySubAccount(payMethodProps.payId); // банк фактического платежа T01, Y02,....
			newOrder.orderStatus = 'confirm_payment'; // id статуса выполнения ордера
			newOrder.orderStatusText = 'Completed'; // название статуса
			newOrder.asset = cryptocurrency.code; // криптовалюта ордера
			newOrder.amount = currency.amount; // сумма ордера
			newOrder.volume = cryptocurrency.amount; // количество крипты
			newOrder.commission = orderDetails.fee; // комиссия ордера
			newOrder.price = orderDetails.rate; // цена ордера asset/fiat
			newOrder.priceAssetUSDT = priceAssetUSDT; // цена ордера asset/USDT
			newOrder.fiat = currency.code; // фиатная валюта ордера
			newOrder.dateOrder = orderDetails.times.created; // дата создания ордера на бирже
		} else if (shortName === 'GX') {
			const { id, ad, created_at } = orderDetails;
			const tradeType = ad.direction.toUpperCase();
			const asset = ad.currency.toUpperCase();
			const fiat = ad.fiat_currency.toUpperCase();
			const payNameGX = ad.payment_method;
			const nickName =
				tradeType === 'BUY' ? orderDetails.seller : orderDetails.buyer;
			const priceAssetUSDT = getTickerPriceUSDT(
				asset === 'RUB' ? 'USDT' : asset,
				fiat,
				arrTickers
			);
			newOrder.orderId = id; // номер ордера
			newOrder.advId = ad.id; // номер объявления
			newOrder.counterpartId = null; // id контрагента
			newOrder.counterpartEmail = ''; // email контрагента
			newOrder.counterpartPhone = ''; // телефон контрагента
			newOrder.counterpartNickName = nickName; // никнейм контрагента
			newOrder.counterpartRealName = null; // реальное имя контрагента
			newOrder.counterpartAccount = ''; // карта контрагента
			newOrder.counterpartСlientType = ''; // клиент контрагента
			newOrder.tradeType = tradeType; // тип ордера
			newOrder.payMethodId = '62ab3f114399fc08ec9725b6'; // id банка Sberbank
			newOrder.payMethodName = 'Sberbank'; // название банка
			newOrder.payMerchantAccount = 'S01'; // банк фактического платежа T01, Y02,....
			newOrder.orderStatus = orderDetails.state; // id статуса выполнения ордера
			newOrder.orderStatusText = 'Completed'; // название статуса
			newOrder.asset = asset; // криптовалюта ордера
			newOrder.amount = orderDetails.volume; // сумма ордера
			newOrder.volume = orderDetails.amount; // количество крипты
			newOrder.commission = orderDetails.fee; // комиссия ордера
			newOrder.price = orderDetails.price; // цена ордера asset/fiat
			newOrder.priceAssetUSDT = priceAssetUSDT; // цена ордера asset/USDT
			newOrder.fiat = fiat; // фиатная валюта ордера
			newOrder.dateOrder = Number(new Date(created_at)); // дата создания ордера на бирже
		} else if (shortName === 'BT') {
			const {
				side,
				status,
				paymentType,
				tokenName,
				currencyId,
			} = orderDetails;
			const tradeType = side === 0 ? 'BUY' : 'SELL';

			// получение payId, payName для БД
			const payMethodProps = getPayMethodProps(
				exchangeId,
				paymentType.toString(),
				arrPayTypes
			);

			const priceAssetUSDT = getTickerPriceUSDT(
				tokenName,
				currencyId,
				arrTickers
			);
			newOrder.orderId = orderDetails.id; // номер ордера
			newOrder.advId = ''; // номер объявления
			newOrder.counterpartId = orderDetails.targetUserId; // id контрагента
			newOrder.counterpartEmail = ''; // email контрагента
			newOrder.counterpartPhone = ''; // телефон контрагента
			newOrder.counterpartNickName = orderDetails.targetNickName; // никнейм контрагента
			newOrder.counterpartRealName =
				tradeType === 'SELL' // реальное имя контрагента
					? normalizeStrBT(orderDetails.buyerRealName)
					: normalizeStrBT(orderDetails.sellerRealName);
			newOrder.counterpartAccount = ''; // карта контрагента
			newOrder.counterpartСlientType = ''; // клиент контрагента
			newOrder.tradeType = tradeType; // тип ордера
			newOrder.payMethodId = payMethodProps.payId; // внутренний id платежного метода
			newOrder.payMethodName = payMethodProps.payName; // внутреннее название платежного метода
			newOrder.payMerchantAccount = getPaySubAccount(payMethodProps.payId); // банк фактического платежа T01, Y02,....
			newOrder.orderStatus = status.toString(); // id статуса выполнения ордера
			newOrder.orderStatusText = 'Completed'; // название статуса
			newOrder.asset = tokenName; // криптовалюта ордера
			newOrder.amount = orderDetails.amount; // сумма ордера
			newOrder.volume = orderDetails.quantity; // количество крипты
			newOrder.commission = ''; // комиссия ордера
			newOrder.price = orderDetails.price; // цена ордера asset/fiat
			newOrder.priceAssetUSDT = priceAssetUSDT; // цена ордера asset/USDT
			newOrder.fiat = currencyId; // фиатная валюта ордера
			newOrder.dateOrder = Number(orderDetails.createDate); // дата создания ордера на бирже
		} else if (shortName === 'PX' || shortName === 'CX') {
			const { asset, fiatCurrency, tradeType, orderStatus } = orderDetails;

			// получение payId, payName для БД
			const payMethodProps = getPayMethodProps(
				exchangeId,
				orderDetails.payType,
				arrPayTypes
			);

			const priceAssetUSDT = getTickerPriceUSDT(
				asset,
				fiatCurrency,
				arrTickers
			);
			newOrder.orderId = orderDetails.orderNo; // номер ордера
			newOrder.advId = orderDetails.adOrderNo; // номер объявления
			newOrder.counterpartId =
				tradeType === 'SELL' // id контрагента
					? orderDetails.buyerUserNo
					: orderDetails.sellerUserNo;
			newOrder.counterpartEmail = ''; // email контрагента
			newOrder.counterpartPhone =
				tradeType === 'SELL' // телефон контрагента
					? orderDetails.buyerMobilePhone
					: orderDetails.sellerMobilePhone;
			newOrder.counterpartNickName =
				tradeType === 'SELL' // никнейм контрагента
					? orderDetails.buyerNickname
					: orderDetails.sellerNickname;
			newOrder.counterpartRealName =
				tradeType === 'SELL' // реальное имя контрагента
					? orderDetails.buyerName
					: orderDetails.sellerName;
			newOrder.counterpartAccount = ''; // карта контрагента
			newOrder.counterpartСlientType = orderDetails.clientType; // клиент контрагента
			newOrder.tradeType = tradeType; // тип ордера																																// тип ордера
			newOrder.payMethodId = payMethodProps.payId; // внутренний id платежного метода
			newOrder.payMethodName = payMethodProps.payName; // внутреннее название платежного метода
			newOrder.payMerchantAccount = getPaySubAccount(payMethodProps.payId); // банк фактического платежа T01, Y02,....
			newOrder.orderStatus = orderStatus.toString(); // id статуса выполнения ордера
			newOrder.orderStatusText = 'Completed'; // название статуса
			newOrder.asset = asset; // криптовалюта ордера
			newOrder.amount = orderDetails.totalPrice; // сумма ордера                					// криптовалюта ордера
			newOrder.volume = orderDetails.amount; // количество крипты
			newOrder.commission = orderDetails.commission.toString(); // комиссия ордера
			newOrder.price = orderDetails.price; // цена ордера asset/fiat
			newOrder.priceAssetUSDT = priceAssetUSDT; // цена ордера asset/USDT
			newOrder.fiat = fiatCurrency; // фиатная валюта ордера
			newOrder.dateOrder = orderDetails.createTime; // дата создания ордера на бирже
		} else if (shortName === 'MG') {
			const { confirmPaymentInfo } = orderDetails;

			// получение payId, payName для БД
			const payMethodProps = getPayMethodProps(
				exchangeId,
				confirmPaymentInfo.payMethod.toString(),
				arrPayTypes
			);

			const priceAssetUSDT = getTickerPriceUSDT(
				orderDetails.coinName,
				orderDetails.currency,
				arrTickers
			);
			newOrder.orderId = orderDetails.id; // номер ордера
			newOrder.advId = ''; // номер объявления
			newOrder.counterpartId = orderDetails.userInfo.uid
				? orderDetails.userInfo.uid.toString()
				: ''; // id контрагента
			newOrder.counterpartEmail = orderDetails.userInfo.account; // email контрагента
			newOrder.counterpartPhone = orderDetails.userInfo.mobile; // телефон контрагента
			newOrder.counterpartNickName = orderDetails.userInfo.nickName; // никнейм контрагента
			newOrder.counterpartRealName = orderDetails.userInfo.realName
				? orderDetails.userInfo.realName
				: ''; // настоящее имя контрагента
			newOrder.counterpartAccount = ''; // карта контрагента
			newOrder.counterpartСlientType = ''; // клиент контрагента
			newOrder.tradeType = orderDetails.tradeType === 0 ? 'SELL' : 'BUY'; // тип ордера
			newOrder.payMethodId = payMethodProps.payId; // внутренний id платежного метода
			newOrder.payMethodName = payMethodProps.payName; // внутреннее название платежного метода
			newOrder.payMerchantAccount = getPaySubAccount(payMethodProps.payId); // банк subAccount T01, Y02,....
			newOrder.orderStatus = orderDetails.state.toString(); // id статуса выполнения ордера
			newOrder.orderStatusText = 'Completed'; // название статуса
			newOrder.asset = orderDetails.coinName; // криптовалюта ордера
			newOrder.amount = orderDetails.amount.toString(); // сумма ордера
			newOrder.volume = orderDetails.quantity.toString(); // количество крипты
			newOrder.commission = ''; // комиссия ордера
			newOrder.price = orderDetails.price.toString(); // цена ордера asset/fiat
			newOrder.priceAssetUSDT = priceAssetUSDT; // цена ордера asset/USDT
			newOrder.fiat = orderDetails.currency; // фиатная валюта ордера
			newOrder.dateOrder = Number(orderDetails.createTime); // дата создания ордера на бирже
		} else if (shortName === 'KC') {
			// получение payId, payName для БД
			const payMethodProps = getPayMethodProps(
				exchangeId,
				orderDetails.payTypeCode,
				arrPayTypes
			);
			const priceAssetUSDT = getTickerPriceUSDT(
				orderDetails.currency, // криптовалюта ордера
				orderDetails.legalCurrency, // фиатная валюта ордера
				arrTickers
			);
			newOrder.orderId = orderDetails.id; // номер ордера
			newOrder.advId = orderDetails.adId; // номер объявления
			newOrder.counterpartId = ''; // id контрагента
			newOrder.counterpartEmail = ''; // email контрагента
			newOrder.counterpartPhone = ''; // телефон контрагента
			newOrder.counterpartNickName = orderDetails.opTraderNickName; // никнейм контрагента
			newOrder.counterpartRealName = orderDetails.opTraderName; // настоящее имя контрагента
			newOrder.counterpartAccount = ''; // карта контрагента
			newOrder.counterpartСlientType = ''; // клиент контрагента
			newOrder.tradeType = orderDetails.buyerRole ? 'BUY' : 'SELL'; // тип ордера
			newOrder.payMethodId = payMethodProps.payId; // внутренний id платежного метода
			newOrder.payMethodName = payMethodProps.payName; // внутреннее название платежного метода
			newOrder.payMerchantAccount = getPaySubAccount(payMethodProps.payId); // банк subAccount T01, Y02,....
			newOrder.orderStatus = orderDetails.status; // id статуса выполнения ордера
			newOrder.orderStatusText = 'Completed'; // название статуса
			newOrder.asset = orderDetails.currency; // криптовалюта ордера
			newOrder.amount = orderDetails.legalCurrencyAmount; // сумма ордера
			newOrder.volume = orderDetails.currencyAmount; // количество крипты
			newOrder.commission = orderDetails.rateAmount; // комиссия ордера
			newOrder.price = orderDetails.price; // цена ордера asset/fiat
			newOrder.priceAssetUSDT = priceAssetUSDT; // цена ордера asset/USDT
			newOrder.fiat = orderDetails.legalCurrency; // фиатная валюта ордера
			newOrder.dateOrder = orderDetails.createdAt; // дата создания ордера на бирже
		} else if (
			shortName === 'GT' ||
			shortName === 'HB' ||
			shortName === 'BX' ||
			shortName === 'XG' ||
			shortName === 'CN' ||
			shortName === 'CM' ||
			shortName === 'XT'
		) {
			const { conterpartInfo } = orderDetails;
			newOrder.orderId = orderDetails.orderId; // номер ордера
			newOrder.advId = ''; // номер объявления
			newOrder.counterpartId = conterpartInfo.uid; // id контрагента
			newOrder.counterpartEmail = conterpartInfo.email; // email контрагента
			newOrder.counterpartPhone = conterpartInfo.phone; // телефон контрагента
			newOrder.counterpartNickName = conterpartInfo.nickName; // никнейм контрагента
			newOrder.counterpartRealName = conterpartInfo.realName; // настоящее имя контрагента
			newOrder.counterpartAccount = conterpartInfo.bankCart; // карта контрагента
			newOrder.counterpartСlientType = conterpartInfo.clientType; // клиент контрагента
			newOrder.tradeType = orderDetails.tradeType; // тип ордера
			newOrder.payMethodId = orderDetails.payMethodId; // внутренний id платежного метода
			newOrder.payMethodName = orderDetails.payMethodName; // внутреннее название платежного метода
			newOrder.payMerchantAccount = getPaySubAccount(
				orderDetails.payMethodId
			); // банк subAccount T01, Y02,....
			newOrder.orderStatus = 'completed'; // id статуса выполнения ордера
			newOrder.orderStatusText = orderDetails.statusProps.value; // название статуса
			newOrder.asset = orderDetails.asset; // криптовалюта ордера
			newOrder.amount = orderDetails.amount; // сумма ордера
			newOrder.volume = orderDetails.volume; // количество крипты
			newOrder.commission = orderDetails.fee; // комиссия ордера
			newOrder.price = orderDetails.price; // цена ордера asset/fiat
			// цена ордера asset/USDT
			newOrder.priceAssetUSDT = getTickerPriceUSDT(
				orderDetails.asset, // криптовалюта ордера
				orderDetails.fiat, // фиатная валюта ордера
				arrTickers
			);
			newOrder.fiat = orderDetails.fiat; // фиатная валюта ордера
			newOrder.dateOrder = orderDetails.dateOrder; // дата создания ордера на бирже
		} else if (shortName === 'BG') {
			const { conterpartInfo } = orderDetails;
			newOrder.orderId = orderDetails.orderId; // номер ордера
			newOrder.advId = orderDetails.advId; // номер объявления
			newOrder.counterpartId = conterpartInfo.uid; // id контрагента
			newOrder.counterpartEmail = conterpartInfo.email; // email контрагента
			newOrder.counterpartPhone = conterpartInfo.phone; // телефон контрагента
			newOrder.counterpartNickName = conterpartInfo.nickName; // никнейм контрагента
			newOrder.counterpartRealName = conterpartInfo.realName; // настоящее имя контрагента
			newOrder.counterpartAccount = conterpartInfo.bankCart; // карта контрагента
			newOrder.counterpartСlientType = conterpartInfo.clientType; // клиент контрагента
			newOrder.tradeType = orderDetails.tradeType; // тип ордера
			newOrder.payMethodId = orderDetails.payMethodId; // внутренний id платежного метода
			newOrder.payMethodName = orderDetails.payMethodName; // внутреннее название платежного метода
			newOrder.payMerchantAccount = getPaySubAccount(
				orderDetails.payMethodId
			); // банк subAccount T01, Y02,....
			newOrder.orderStatus = 'completed'; // id статуса выполнения ордера
			newOrder.orderStatusText = orderDetails.statusProps.value; // название статуса
			newOrder.asset = orderDetails.asset; // криптовалюта ордера
			newOrder.amount = orderDetails.amount; // сумма ордера
			newOrder.volume = orderDetails.volume; // количество крипты
			newOrder.commission = orderDetails.fee; // комиссия ордера
			newOrder.price = orderDetails.price; // цена ордера asset/fiat
			// цена ордера asset/USDT
			newOrder.priceAssetUSDT = getTickerPriceUSDT(
				orderDetails.asset, // криптовалюта ордера
				orderDetails.fiat, // фиатная валюта ордера
				arrTickers
			);
			newOrder.fiat = orderDetails.fiat; // фиатная валюта ордера
			newOrder.dateOrder = orderDetails.dateOrder; // дата создания ордера на бирже
		} else if (shortName === 'BP') {
			const { ad, contractor } = orderDetails;
			const payItem =
				ad.payment_method_banks.length === 0
					? ad.payment_method.name // QIWI, USDT Tether
					: ad.payment_method_banks[0].name;
			const PayMethodProps = getPayMethodProps(
				exchangeId,
				payItem,
				arrPayTypes
			);
			const priceAssetUSDT = getTickerPriceUSDT(
				orderDetails.ad.crypto_currency_code, // криптовалюта ордера
				orderDetails.ad.currency_code, // фиатная валюта ордера
				arrTickers
			);
			const feeSize = 0.95;
			newOrder.orderId = orderDetails.id; // номер ордера
			newOrder.advId = orderDetails.ad.id; // номер объявления
			newOrder.counterpartId = contractor.id; // id контрагента
			newOrder.counterpartEmail = ''; // email контрагента
			newOrder.counterpartPhone = ''; // телефон контрагента
			newOrder.counterpartNickName = contractor.user_name; // никнейм контрагента
			newOrder.counterpartRealName = ''; // настоящее имя контрагента
			newOrder.counterpartAccount = ''; // карта контрагента
			newOrder.counterpartСlientType = orderDetails.device_type; // клиент контрагента
			newOrder.tradeType = ad.type === 'Ad::Sell' ? 'SELL' : 'BUY'; // тип ордера
			newOrder.payMethodId = PayMethodProps.payId; // внутренний id платежного метода
			newOrder.payMethodName = PayMethodProps.payName; // внутреннее название платежного метода
			newOrder.payMerchantAccount = getPaySubAccount(PayMethodProps.payId); // банк subAccount T01, Y02,....
			newOrder.orderStatus = orderDetails.status; // id статуса выполнения ордера
			newOrder.orderStatusText = 'Completed'; // название статуса
			newOrder.asset = ad.crypto_currency_code; // криптовалюта ордера
			newOrder.amount = orderDetails.cost; // сумма ордера
			newOrder.volume = orderDetails.amount; // количество крипты
			newOrder.commission = (orderDetails.amount / 100) * feeSize; // комиссия ордера
			newOrder.price = orderDetails.price; // цена ордера asset/fiat
			newOrder.priceAssetUSDT = priceAssetUSDT; // цена ордера asset/USDT
			newOrder.fiat = ad.currency_code; // фиатная валюта ордера
			newOrder.dateOrder = Date.parse(orderDetails.created_at); // дата создания ордера на бирже}
		} else if (shortName === 'AX') {
			const { advertisement } = orderDetails;
			const PayMethodProps = getPayMethodProps(
				exchangeId,
				orderDetails.paymentMethod.id,
				arrPayTypes
			);
			const priceAssetUSDT = getTickerPriceUSDT(
				orderDetails.quote, // криптовалюта ордера
				orderDetails.base, // фиатная валюта ордера
				arrTickers
			);
			newOrder.orderId = orderDetails.id; // номер ордера
			newOrder.advId = advertisement.id; // номер объявления
			newOrder.counterpartId =
				advertisement.side === 'buy'
					? orderDetails.sellUser.id
					: orderDetails.buyUser.id;
			newOrder.counterpartEmail = ''; // email контрагента
			newOrder.counterpartPhone = ''; // телефон контрагента
			newOrder.counterpartNickName =
				advertisement.side === 'buy'
					? orderDetails.sellUser.username
					: orderDetails.buyUser.username;
			newOrder.counterpartRealName = ''; // настоящее имя контрагента
			newOrder.counterpartAccount = ''; // карта контрагента
			newOrder.counterpartСlientType = ''; // клиент контрагента
			newOrder.tradeType = advertisement.side.toUpperCase(); // тип ордера
			newOrder.payMethodId = PayMethodProps.payId; // внутренний id платежного метода
			newOrder.payMethodName = PayMethodProps.payName; // внутреннее название платежного метода
			newOrder.payMerchantAccount = getPaySubAccount(PayMethodProps.payId); // банк subAccount T01, Y02,....
			newOrder.orderStatus = orderDetails.status; // id статуса выполнения ордера
			newOrder.orderStatusText = 'Completed'; // название статуса
			newOrder.asset = orderDetails.quote; // криптовалюта ордера
			newOrder.amount = orderDetails.amount; // сумма ордера
			newOrder.volume = orderDetails.volume; // количество крипты
			newOrder.commission = '0'; // комиссия ордера
			newOrder.price = orderDetails.price; // цена ордера asset/fiat
			newOrder.priceAssetUSDT = priceAssetUSDT; // цена ордера asset/USDT
			newOrder.fiat = orderDetails.base; // фиатная валюта ордера
			newOrder.dateOrder = orderDetails.datetime; // дата создания ордера на бирже}
		} else if (shortName === 'BM') {
			// const { advertisement } = orderDetails;
			const PayMethodProps = getPayMethodProps(
				exchangeId,
				orderDetails.payType,
				arrPayTypes
			);
			const priceAssetUSDT = getTickerPriceUSDT(
				orderDetails.crypto, // криптовалюта ордера
				orderDetails.currency, // фиатная валюта ордера
				arrTickers
			);
			newOrder.orderId = orderDetails.orderId.toString(); // номер ордера
			newOrder.advId = ''; // номер объявления
			newOrder.counterpartId = orderDetails.counterpartyCid.toString();
			newOrder.counterpartEmail = ''; // email контрагента
			newOrder.counterpartPhone = ''; // телефон контрагента
			newOrder.counterpartNickName = orderDetails.userName;
			newOrder.counterpartRealName = ''; // настоящее имя контрагента
			newOrder.counterpartAccount = ''; // карта контрагента
			newOrder.counterpartСlientType = ''; // клиент контрагента
			newOrder.tradeType = orderDetails.side.toUpperCase(); // тип ордера
			newOrder.payMethodId = PayMethodProps.payId; // внутренний id платежного метода
			newOrder.payMethodName = PayMethodProps.payName; // внутреннее название платежного метода
			newOrder.payMerchantAccount = getPaySubAccount(PayMethodProps.payId); // банк subAccount T01, Y02,....
			newOrder.orderStatus = orderDetails.stateLabel.toString(); // id статуса выполнения ордера
			newOrder.orderStatusText = 'Completed'; // название статуса
			newOrder.asset = orderDetails.crypto; // криптовалюта ордера
			newOrder.amount = orderDetails.amount; // сумма ордера
			newOrder.volume = orderDetails.size; // количество крипты
			newOrder.commission = '0'; // комиссия ордера
			newOrder.price = orderDetails.price; // цена ордера asset/fiat
			newOrder.priceAssetUSDT = priceAssetUSDT; // цена ордера asset/USDT
			newOrder.fiat = orderDetails.currency; // фиатная валюта ордера
			newOrder.dateOrder = Number(orderDetails.createTime); // дата создания ордера на бирже}
		}
	} else console.log(shortName + ': orderDetails is empty');
	// shortName === 'CN' ? console.log(newOrder) : null;
	return newOrder;
};

// получение массива объявлений пользователя
export const getMerchantAdvs = async (params) => {
	const { userId, config, prefix } = params;
	let result = [];

	// prefix === 'BM' ? console.log(params) : null;
	await axios(config)
		.then((response) => {
			// prefix === 'BM' ? console.log(response.data) : null;
			if (prefix === 'GX' || prefix === 'BZ') {
				result = response.data;
			} else if (prefix === 'BT') {
				result = response.data.result.items;
			} else if (prefix === 'KC') {
				result =
					response.data.msg === 'success' ? response.data.items : [];
			} else if (prefix === 'GT') {
				result = response.data.result ? response.data.order : [];
			} else if (prefix === 'GT_unp') {
				result =
					response.data.result && response.data.transaction
						? response.data.transaction
						: [];
			} else if (prefix === 'BG_API') {
				result =
					response.data.msg === 'success'
						? response.data.data.advList
						: [];
			} else if (prefix === 'TG') {
				result =
					response.data.status === 'SUCCESS' ? response.data.data : [];
			} else if (prefix === 'BM') {
				result = response.data.success ? response.data.data.items : [];
			} else {
				result = response.data.data;
			}
		})
		.catch((error) => {
			console.log(
				`=======// ${getTimestamps()} //=======\n****${userId.slice(
					-4
				)} | ${prefix}: ${TEXT_CONSTANTS.USER_ADVS_ER}\n${error}`
			);
		});
	return result;
};

// нормализация массива объявлений пользователя
export const getMerchantAdvsNomalized = (advs, params, arrPayTypes) => {
	const result = [];

	for (let i = 0; i < advs.length; i++) {
		const item = {};
		if (params.prefix === 'BN') {
			const methods = advs[i].tradeMethods;
			const arrPayMethods = methods.map((k, index) => {
				const PayMethodProps = getPayMethodProps(
					params.exchangeId,
					k.identifier,
					arrPayTypes
				);
				return PayMethodProps;
			});
			// ===========================
			item.advId = advs[i].advNo;
			item.price = advs[i].price;
			item.rateFloat = advs[i].priceFloatingRatio;
			item.volume = advs[i].surplusAmount;
			item.amount = advs[i].initAmount;
			item.asset = advs[i].asset;
			item.fiat = advs[i].fiatUnit;
			item.tradeType = advs[i].tradeType;
			item.minLimit = advs[i].minSingleTransAmount;
			item.maxLimit = advs[i].maxSingleTransAmount;
			item.payMethods = arrPayMethods;
			item.advStatus = advs[i].advStatus === 1 ? true : false;
			item.createAt = advs[i].createTime;
			item.updateAt = advs[i].advUpdateTime;
			item.timeLimit = advs[i].payTimeLimit.toString();
		} else if (params.prefix === 'HB') {
			const methods = advs[i].payMethods;
			const arrPayMethods = methods.map((k, index) => {
				const PayMethodProps = getPayMethodProps(
					params.exchangeId,
					k.payMethodId.toString(),
					arrPayTypes
				);
				return PayMethodProps;
			});
			// ===========================
			item.advId = advs[i].id.toString();
			item.price = advs[i].price;
			item.rateFloat = null;
			item.volume = advs[i].tradeCount;
			// item.amount = advs[i].tradeCount;
			item.amount = '0';
			item.asset = getPropsCurrencyReverse(
				params.exchangeId,
				advs[i].coinId.toString(),
				params.arrCurrencies,
				'coin'
			).coinName;
			item.fiat = getPropsCurrencyReverse(
				params.exchangeId,
				advs[i].currency.toString(),
				params.arrCurrencies,
				'fiat'
			).coinName;
			item.tradeType = advs[i].tradeType === 0 ? 'BUY' : 'SELL';
			item.minLimit = advs[i].minTradeLimit;
			item.maxLimit = advs[i].maxTradeLimit;
			item.payMethods = arrPayMethods;
			item.advStatus = advs[i].status === 1 ? true : false;
			item.createAt = Date.parse(advs[i].gmtCreate);
			item.updateAt = null;
			item.timeLimit = '0';
		} else if (params.prefix === 'KX') {
			const methods = advs[i].paymentMethods;
			const arrPayMethods = methods.map((k, index) => {
				const PayMethodProps = getPayMethodProps(
					params.exchangeId,
					k,
					arrPayTypes
				);
				return PayMethodProps;
			});
			// ===========================
			item.advId = advs[i].publicId;
			item.price = advs[i].price;
			item.rateFloat = advs[i].floatRate;
			item.volume = advs[i].availableAmount;
			// item.amount = advs[i].completedAmount;
			// item.amount = advs[i].completedOrderTotal;
			item.amount = +advs[i].availableAmount + +advs[i].completedAmount;
			item.asset = advs[i].baseCurrency.toUpperCase();
			item.fiat = advs[i].quoteCurrency.toUpperCase();
			item.tradeType = advs[i].side.toUpperCase();
			item.minLimit = advs[i].quoteMinAmountPerOrder;
			item.maxLimit = advs[i].quoteMaxAmountPerOrder;
			item.payMethods = arrPayMethods;
			// item.advStatus = advs[i].status === 'new' ? true : false;
			item.advStatus = !advs[i].hidden;
			item.createAt = advs[i].createdDate;
			item.updateAt = null;
			item.timeLimit = advs[i].unpaidOrderTimeoutMinutes.toString();
		} else if (params.prefix === 'BZ') {
			const PayMethodProps = getPayMethodProps(
				params.exchangeId,
				advs[i].paymethod.toString(),
				arrPayTypes
			);
			// ===========================
			item.advId = advs[i].id.toString();
			item.price = advs[i].rateValue;
			item.rateFloat = advs[i].ratePercent;
			item.volume = advs[i].minAmount;
			item.amount = +advs[i].maxAmount;
			item.asset = advs[i].cryptocurrency;
			item.fiat = advs[i].paymethod_currency;
			item.tradeType = advs[i].type === 'purchase' ? 'BUY' : 'SELL';
			item.minLimit = advs[i].minAmount;
			item.maxLimit = advs[i].maxAmount;
			item.payMethods = [PayMethodProps];
			item.advStatus = advs[i].status === 'active' ? true : false;
			item.createAt = advs[i].ownerLastActivity;
			item.updateAt = null;
			item.timeLimit = '0';
		} else if (params.prefix === 'GX') {
			const methods = advs[i].payment_method.split('|');
			const arrPayMethods = methods.map((k, index) => {
				const PayMethodProps = getPayMethodProps(
					params.exchangeId,
					k.trim(),
					arrPayTypes
				);
				return PayMethodProps;
			});
			// ===========================
			item.advId = advs[i].id.toString();
			item.price = advs[i].price;
			item.rateFloat = advs[i].price;
			item.volume = advs[i].max;
			item.amount = advs[i].max;
			item.asset = advs[i].currency.toUpperCase();
			item.fiat = advs[i].fiat_currency.toUpperCase();
			item.tradeType = advs[i].direction.toUpperCase();
			item.minLimit = advs[i].min;
			item.maxLimit = advs[i].max;
			item.payMethods = arrPayMethods.filter((item) => {
				return item.payId !== '' && item.payName !== '';
			});
			item.advStatus = advs[i].active;
			item.createAt = Date.parse(advs[i].created_at);
			item.updateAt = Date.parse(advs[i].edited_at);
			item.timeLimit = '0';
		} else if (params.prefix === 'BT') {
			const methods = advs[i].payments;
			const arrPayMethods = methods.map((k, index) => {
				const PayMethodProps = getPayMethodProps(
					params.exchangeId,
					k.toString(),
					arrPayTypes
				);
				return PayMethodProps;
			});
			// ===========================
			item.advId = advs[i].id;
			item.price = advs[i].price;
			item.rateFloat = null;
			item.volume = advs[i].quantity;
			item.amount = +advs[i].lastQuantity;
			item.asset = advs[i].tokenId;
			item.fiat = advs[i].currencyId;
			item.tradeType = advs[i].side === 0 ? 'BUY' : 'SELL';
			item.minLimit = advs[i].minAmount;
			item.maxLimit = advs[i].maxAmount;
			item.payMethods = arrPayMethods;
			item.advStatus = advs[i].status === 10 ? true : false;
			item.createAt = Number(advs[i].createDate);
			item.updateAt = Number(advs[i].updateDate);
			item.timeLimit = advs[i].paymentPeriod.toString();
		} else if (params.prefix === 'PX') {
			const methods = advs[i].tradeMethods;
			const arrPayMethods = methods.map((k, index) => {
				const PayMethodProps = getPayMethodProps(
					params.exchangeId,
					k.identifier,
					arrPayTypes
				);
				return PayMethodProps;
			});
			// ===========================
			item.advId = advs[i].adNo;
			item.price = advs[i].price;
			item.rateFloat = advs[i].priceFloatingRatio;
			item.volume = advs[i].remainingAmount;
			item.amount = advs[i].initAmount;
			item.asset = advs[i].asset;
			item.fiat = advs[i].fiatCurrency;
			item.tradeType = advs[i].tradeType;
			item.minLimit = advs[i].minSingleTransAmount;
			item.maxLimit = advs[i].maxSingleTransAmount;
			item.payMethods = arrPayMethods;
			item.advStatus = advs[i].adStatus === 1 ? true : false;
			item.createAt = advs[i].createTime;
			item.updateAt = advs[i].adUpdateTime;
			item.timeLimit = advs[i].payTimeLimit.toString();
		} else if (params.prefix === 'MG') {
			const methods = advs[i].paymentInfo;
			const arrPayMethods = methods.map((k, index) => {
				const PayMethodProps = getPayMethodProps(
					params.exchangeId,
					k.payMethod.toString(),
					arrPayTypes
				);
				return PayMethodProps;
			});
			// ===========================
			item.advId = `****${advs[i].id.slice(-16)}`;
			item.price = advs[i].price.toString();
			item.rateFloat = null;
			item.volume = advs[i].availableQuantity.toString();
			item.amount = advs[i].amount.toString();
			item.asset = advs[i].coinName;
			item.fiat = advs[i].currency;
			item.tradeType = advs[i].tradeType === 0 ? 'BUY' : 'SELL';
			item.minLimit = advs[i].minTradeLimit.toString();
			item.maxLimit = advs[i].maxTradeLimit.toString();
			item.payMethods = arrPayMethods;
			item.advStatus = advs[i].state === 1 ? true : false;
			item.createAt = advs[i].createTime;
			item.updateAt = advs[i].updateTime;
			item.timeLimit = advs[i].expirationTime.toString();
		} else if (params.prefix === 'KC') {
			const methods = advs[i].adPayTypes;
			const arrPayMethods = methods.map((k, index) => {
				const PayMethodProps = getPayMethodProps(
					params.exchangeId,
					k.payTypeCode.toString(),
					arrPayTypes
				);
				return PayMethodProps;
			});
			// ===========================
			item.advId = `****${advs[i].id.slice(-16)}`;
			item.price = advs[i].floatPrice;
			item.rateFloat = null;
			item.volume = advs[i].currencyBalanceQuantity;
			item.amount = advs[i].currencyQuantity;
			item.asset = advs[i].currency;
			item.fiat = advs[i].legal;
			item.tradeType = advs[i].side;
			item.minLimit = advs[i].limitMinQuote;
			item.maxLimit = advs[i].limitMaxQuote;
			item.payMethods = arrPayMethods;
			item.advStatus = advs[i].displayStatus === 'NORMAL' ? true : false;
			item.createAt = null;
			item.updateAt = advs[i].updatedAt;
			item.timeLimit = '0';
		} else if (params.prefix === 'GT') {
			const methods = advs[i].pay_type_num.split(',');
			const arrPayMethods = methods.map((k, index) => {
				const PayMethodProps = getPayMethodProps(
					params.exchangeId,
					k.toString(),
					arrPayTypes
				);
				return PayMethodProps;
			});
			const limits = advs[i].limit_total.split('~');
			const priceOrder = advs[i].rate.replaceAll(',', '').toString();
			// ===========================
			item.advId = advs[i].orderid;
			item.price = priceOrder;
			item.rateFloat = null;
			item.volume = Number(advs[i].amount.replaceAll(',', '')).toString();
			item.amount = Number(advs[i].total.replaceAll(',', '')).toString();
			item.asset = advs[i].currencyType;
			item.fiat = advs[i].want_type;
			item.tradeType = advs[i].type.toUpperCase();
			item.minLimit = (limits[0] * priceOrder).toString();
			item.maxLimit = (limits[1] * priceOrder).toString();
			item.payMethods = arrPayMethods;
			item.advStatus = advs[i].status === 'OPEN' ? true : false;
			item.createAt = Date.parse(
				new Date().getFullYear() + '-' + advs[i].time
			);
			item.updateAt = null;
			item.timeLimit = '20';
		} else if (params.prefix === 'BG') {
			const methods = advs[i].paymentMethod;
			const arrPayMethods = methods.map((k, index) => {
				const PayMethodProps = getPayMethodProps(
					params.exchangeId,
					k.paymentId,
					arrPayTypes
				);
				return PayMethodProps;
			});
			// ===========================
			item.advId = advs[i].advNo;
			item.price = advs[i].price;
			item.rateFloat = null;
			item.volume = advs[i].amount;
			item.amount = advs[i].dealAmount;
			item.asset = advs[i].coin;
			item.fiat = advs[i].fiatCode;
			item.tradeType = advs[i].type.toUpperCase();
			item.minLimit = advs[i].minAmount;
			item.maxLimit = advs[i].maxAmount;
			item.payMethods = arrPayMethods;
			item.advStatus = advs[i].status === 'online' ? true : false;
			item.createAt = Number(advs[i].ctime);
			item.updateAt = null;
			item.timeLimit = advs[i].payDuration;
		} else if (params.prefix === 'BP') {
		} else if (params.prefix === 'CX') {
			const methods = advs[i].tradeMethods;
			const arrPayMethods = methods.map((k, index) => {
				const PayMethodProps = getPayMethodProps(
					params.exchangeId,
					k.identifier,
					arrPayTypes
				);
				return PayMethodProps;
			});
			// ===========================
			item.advId = advs[i].adNo;
			item.price = advs[i].price;
			item.rateFloat = advs[i].priceFloatingRatio;
			item.volume = advs[i].remainingAmount;
			item.amount = advs[i].initAmount;
			item.asset = advs[i].asset;
			item.fiat = advs[i].fiatCurrency;
			item.tradeType = advs[i].tradeType;
			item.minLimit = advs[i].minSingleTransAmount;
			item.maxLimit = advs[i].maxSingleTransAmount;
			item.payMethods = arrPayMethods;
			item.advStatus = advs[i].advStatus === 1 ? true : false;
			item.createAt = advs[i].createTime;
			item.updateAt = advs[i].adUpdateTime;
			item.timeLimit = '0';
		} else if (params.prefix === 'BX') {
		} else if (params.prefix === 'TG') {
			const tradeType = advs[i].type === 'PURCHASE' ? 'BUY' : 'SELL';
			const methods =
				tradeType === 'BUY'
					? advs[i].paymentMethods
					: advs[i].paymentDetails;
			const arrPayMethods = methods.map((k, index) => {
				const paymentItem =
					tradeType === 'BUY' ? k.nameEng : k.paymentMethod.nameEng;
				const PayMethodProps = getPayMethodProps(
					params.exchangeId,
					paymentItem,
					arrPayTypes
				);
				return PayMethodProps;
			});
			// ===========================
			item.advId = advs[i].number;
			item.price = advs[i].price.estimated;
			item.rateFloat =
				advs[i].price.type === 'FLOATING' ? advs[i].price.value : null;
			item.volume = advs[i].orderVolumeLimits.max;
			item.amount = +advs[i].availableVolume.amount;
			item.asset = advs[i].price.baseCurrencyCode;
			item.fiat = advs[i].price.quoteCurrencyCode;
			item.tradeType = tradeType;
			item.minLimit = advs[i].orderAmountLimits.min;
			item.maxLimit = advs[i].orderAmountLimits.max;
			item.payMethods = arrPayMethods;
			item.advStatus = advs[i].status === 'ACTIVE' ? true : false;
			item.createAt = null;
			item.updateAt = null;
			item.timeLimit = '0';
		} else if (params.prefix === 'BM') {
			const methods = advs[i].payTypeList;
			const arrPayMethods = methods.map((k, index) => {
				const PayMethodProps = getPayMethodProps(
					params.exchangeId,
					k.payType,
					arrPayTypes
				);
				return PayMethodProps;
			});
			// ===========================
			item.advId = advs[i].adId.toString();
			item.price = advs[i].price;
			item.rateFloat = null; // all fixed
			item.volume = advs[i].availableSize;
			item.amount = advs[i].maxAmount;
			item.asset = advs[i].crypto;
			item.fiat = advs[i].currency;
			item.tradeType = advs[i].side.toUpperCase();
			item.minLimit = advs[i].minAmount;
			item.maxLimit = advs[i].maxAmount;
			item.payMethods = arrPayMethods;
			item.advStatus = advs[i].state === 'active' ? true : false;
			item.createAt = advs[i].createTime;
			item.updateAt = null;
			item.timeLimit = '0';
		}
		// проверяем не пустой ли объект
		if (Object.keys(item).length) {
			item.userId = params.userId;
			item.exchange = params.prefix;
			item.exchangeId = params.exchangeId;
			result.push(item);
		}
		// console.log('=====');
		// console.log(advs[i]);
	}
	// console.log(result);
	return result;
};

// получение статуса успешности advUpdate
export const getResultAdvUpdate = async (config, postfix) => {
	let result = false;
	await axios(config)
		.then((response) => {
			// console.log(response.data)
			result = response.data.success;
		})
		.catch((error) => {
			console.log(
				`=======// ${getTimestamps()} //=======\n${postfix}: ${
					TEXT_CONSTANTS.ADV_EDIT_ER
				}\n${error}`
			);
		});
	return result;
};

// получение массива способов оплат пользователя
export const getUserPayMethods = async (config, postfix) => {
	let result = [];
	await axios(config)
		.then((response) => {
			// console.log(response.data)
			result = response.data.data;
		})
		.catch((error) => {
			console.log(
				`=======// ${getTimestamps()} //=======\n${postfix} getUserPayMethods request Error!\n${error}`
			);
		});
	return result;
};

// Получение массива Данных с заданными полями
export const getArrayItemsCustomed = (arr, flagName) => {
	let result = arr;
	if (flagName === 'arrExchanges') {
		const sortedArray = getArraySortedByProp('ALL', arr, 'createdAt');
		result = sortedArray.map((item) => {
			return {
				id: item._id.toString(),
				shortName: item.shortName,
				nameStorage: item.nameStorage,
				name: item.name,
				logo: item.logo,
				bg: item.bg,
				status: item.status,
				merchantDetail: item.merchantDetail,
				orderDetail: item.orderDetail,
				advDetail: item.advDetail,
				spotTrade: item.spotTrade,
			};
		});
	} else if (flagName === 'arrTickers') {
		result = arr.map((item) => {
			return {
				// id: item._id,
				shortName: item.shortName,
				asset: item.asset,
				course: item.course,
				exchange: item.exchange,
				ticker: item.ticker,
			};
		});
	} else if (flagName === 'arrCurrencies') {
		const sortedArray = getArraySortedByProp('ALL', arr, 'createdAt');
		result = sortedArray.map((item) => {
			return {
				id: item._id,
				currency: item.currency,
				currencyProps: item.currencyProps,
				currencyName: item.currencyName,
				currencyType: item.currencyType,
				symbol: item.symbol,
				iconUrl: item.iconUrl,
				tickerUSDT: item.tickerUSDT,
			};
		});
	} else if (flagName === 'arrPayTypes') {
		result = arr.map((item) => {
			return {
				id: item._id,
				iconUrlColor: item.iconUrlColor,
				payTypeProps: item.payTypeProps,
				payType: item.payType,
			};
		});
	} else if (flagName === 'arrOrderStatus') {
		const sortedArray = getArraySortedByProp('ALL', arr, 'createdAt');
		result = sortedArray.map((item) => {
			return {
				id: item._id,
				status: item.status,
				colorStatus: item.colorStatus,
				values: item.values,
			};
		});
	}
	return result;
};

// сортировка массива ордеров по возрастанию/убыванию propName
export const getArraySortedByProp = (prefix, arr, propName) => {
	const arraySorted = arr.sort((a, b) => {
		if (prefix === 'HB' || prefix === 'KX' || prefix === 'GX') {
			if (propName === 'buy') {
				if (Number(a.price) > Number(b.price)) return -1;
				if (Number(a.price) < Number(b.price)) return 1;
				return 0;
			} else {
				if (Number(a.price) < Number(b.price)) return -1;
				if (Number(a.price) > Number(b.price)) return 1;
				return 0;
			}
		} else if (prefix === 'BZ') {
			if (propName === 'selling') {
				if (Number(a.rate) > Number(b.rate)) return -1;
				if (Number(a.rate) < Number(b.rate)) return 1;
				return 0;
			} else {
				if (Number(a.rate) < Number(b.rate)) return -1;
				if (Number(a.rate) > Number(b.rate)) return 1;
				return 0;
			}
		} else if (prefix === 'BT') {
			if (propName === 0) {
				if (Number(a.price) > Number(b.price)) return -1;
				if (Number(a.price) < Number(b.price)) return 1;
				return 0;
			} else if (propName === 1) {
				if (Number(a.price) < Number(b.price)) return -1;
				if (Number(a.price) > Number(b.price)) return 1;
				return 0;
			} else if (propName === 'createDate') {
				if (Number(a.createDate) > Number(b.createDate)) return -1;
				if (Number(a.createDate) < Number(b.createDate)) return 1;
				return 0;
			}
		} else if (prefix === 'ALL') {
			if (propName === 'dateOrder') {
				if (Number(a.dateOrder) > Number(b.dateOrder)) return -1;
				if (Number(a.dateOrder) < Number(b.dateOrder)) return 1;
				return 0;
			} else if (propName === 'createdAt') {
				if (Number(a.createdAt) > Number(b.createdAt)) return 1;
				if (Number(a.createdAt) < Number(b.createdAt)) return -1;
				return 0;
			} else if (propName === 'priceDESC') {
				if (Number(a.price) > Number(b.price)) return -1;
				if (Number(a.price) < Number(b.price)) return 1;
				return 0;
			} else if (propName === 'priceASC') {
				if (Number(a.price) < Number(b.price)) return -1;
				if (Number(a.price) > Number(b.price)) return 1;
				return 0;
			}
		} else if (prefix === 'GT') {
			if (propName === 'buy') {
				if (Number(a.rate) > Number(b.rate)) return -1;
				if (Number(a.rate) < Number(b.rate)) return 1;
				return 0;
			} else {
				if (Number(a.rate) < Number(b.rate)) return -1;
				if (Number(a.rate) > Number(b.rate)) return 1;
				return 0;
			}
		}
	});
	return arraySorted;
};

// получаем массив ордеров по уникальным значениям id
export const getArrayFilteredByProp = (arr, prop) => {
	var order = {};
	var result = arr.filter((item) => {
		if (order[item[prop]]) {
			return false;
		} else {
			order[item[prop]] = true;
			return true;
		}
	});
	return result;
};

// получение конкретного свойства юзера
export const getSingleUserProperty = (
	nameProperty,
	paramExchange,
	userProperties
) => {
	// console.log(userProperties);
	let userProperty = null;
	for (let i = 0; i < userProperties.length; i++) {
		if (
			userProperties[i].exchange === paramExchange ||
			userProperties[i].exchangeId === paramExchange
		) {
			for (const key in userProperties[i]) {
				if (key === nameProperty)
					userProperty = userProperties[i][nameProperty];
			}
		}
	}
	return userProperty;
};

// получение цены тикера в USDT из локального хранилища тикеров
export const getTickerPriceUSDT = (asset, fiat, arrTickers) => {
	let price = '0.0000';
	let nameTicker =
		fiat === 'RUB' &&
		(asset === 'DAI' ||
			asset === 'HUSD' ||
			asset === 'BUSD' ||
			asset === 'TUSD' ||
			asset === 'USDC' ||
			asset === 'USDT')
			? asset + fiat
			: asset + 'USDT';
	if (
		nameTicker === 'DAIRUB' ||
		nameTicker === 'HUSDRUB' ||
		nameTicker === 'TUSDRUB' ||
		nameTicker === 'BUSDRUB' ||
		nameTicker === 'USDCRUB'
	)
		nameTicker = 'USDTRUB';
	if (nameTicker === 'RUBRUB') return (price = '1.0000');
	for (let i = 0; i < arrTickers.length; i++) {
		// console.log(nameTicker+": "+arrTickers[i].course)
		if (arrTickers[i].ticker === nameTicker) {
			price = arrTickers[i].course;
		}
	}
	return price;
};

// получение из биржи рыночной цены тикера
export const getPriceTicker = async (exchange, ticker) => {
	const result = {
		priceTicker: null,
		message: 'Empty price',
	};

	// значения по умолчанию
	const reqConfig = {
		method: CONSTANTS_BN.GET_DATA_TICKER.method,
		url: `${CONSTANTS_BN.GET_DATA_TICKER.url}?symbol=${ticker}`,
		data: null,
		headers: null,
	};

	if (exchange === 'Huobi') {
		reqConfig.method = CONSTANTS_HB.GET_DATA_TICKER.method;
		reqConfig.url = `${
			CONSTANTS_HB.GET_DATA_TICKER.url
		}?symbol=${ticker.toLowerCase()}`;
	} else if (exchange === 'Mexc') {
		reqConfig.method = CONSTANTS_MG.GET_DATA_TICKER.method;
		reqConfig.url = `${CONSTANTS_MG.GET_DATA_TICKER.url}?symbol=${ticker}`;
	} else if (exchange === 'Garantex') {
		reqConfig.method = CONSTANTS_GX.GET_DATA_TICKER.method;
		reqConfig.url = `${
			CONSTANTS_GX.GET_DATA_TICKER.url
		}?market=${ticker.toLowerCase()}&limit=1`;
	} else if (exchange === 'Xeggex') {
		const xg_ticker = ticker.replace('USDT', '_USDT');
		reqConfig.method = CONSTANTS_XG.GET_DATA_TICKER.method;
		reqConfig.url = CONSTANTS_XG.GET_DATA_TICKER.url + xg_ticker;
	}
	await axios(reqConfig)
		.then((response) => {
			if (response.data) {
				// exchange === 'Xeggex' ? console.log(response.data) : null;
				result.message = "Ticker's price was loaded!";
				if (exchange === 'Binance' || exchange === 'Mexc') {
					result.priceTicker = response.data.price;
				} else if (exchange === 'Huobi') {
					result.priceTicker = response.data.tick.close;
				} else if (exchange === 'Xeggex') {
					result.priceTicker = response.data.lastPrice;
				} else if (exchange === 'Garantex') {
					result.priceTicker = response.data.error
						? null
						: response.data[0].price;
				}
			} else {
				result.message = 'Uknown price!';
				console.log(result.message);
			}
		})
		.catch((error) => {
			result.message = "Ticker's price was not loaded!";
			result.error = error;
			console.log(
				`=======// ${getTimestamps()} //=======
				// \n${result.message}
				// \n${ticker.toLowerCase()}
				\ngetPriceTicker request Error!\n${error}`
			);
		});
	return result;
};

// получение стоимости актива в USDT по текущемку курсу
export const getValuationUSDT = (coursesArray, assetName, assetVolume) => {
	let result = +assetVolume * 1;
	if (coursesArray.length !== 0 && assetName) {
		const tickerName =
			assetName === 'DAI' ||
			assetName === 'RUB' ||
			assetName === 'UAH' ||
			assetName === 'HUSD'
				? 'USDT' + assetName
				: assetName + 'USDT';
		for (let i = 0; i < coursesArray.length; i++) {
			if (coursesArray[i].ticker === tickerName) {
				if (
					tickerName === 'USDTDAI' ||
					tickerName === 'USDTRUB' ||
					tickerName === 'USDTUAH' ||
					tickerName === 'USDTHUSD'
				) {
					result = +assetVolume / +coursesArray[i].course;
				} else {
					result = +assetVolume * +coursesArray[i].course;
				}
			}
		}
	}
	return parseFloat(result).toFixed(2);
};

// добавление spot/merchant-ордера в БД
export const insertOrderToDB = async (typeOrder, orderObj) => {
	const newOrder =
		typeOrder === 'MERCHANT'
			? new MerchantOrder_SQL(orderObj)
			: new SpotOrder_SQL(orderObj);
	// вставляем запись в БД
	await newOrder
		.save()
		.then(() => {
			console.log(
				`${orderObj.exchange}: Order ${orderObj.orderId} inserted`
			);
		})
		.catch((error) => console.log(error));
};

// проверка наличия spot/merchant-ордера в БД
export const checkOrderInDB = async (
	userId,
	typeOrder,
	orderId,
	shortName
) => {
	const queryDB = { where: { userId, orderId, exchange: shortName } };
	const order =
		typeOrder === 'MERCHANT'
			? await MerchantOrder_SQL.findOne(queryDB)
			: await SpotOrder_SQL.findOne(queryDB);

	const result = !order
		? { isUnique: true, message: `Order ${orderId} is unique` }
		: { isUnique: false, message: `Order ${orderId} exists in DB`, order };

	return result;
};

// получение payId or payName by payType
export const getPayMethodPropsReverse = (
	exchangeId,
	flagPayProps, // payId or payName
	internalPayMethod,
	arrPayTypes
) => {
	let externalPayMethod = null;
	for (let i = 0; i < arrPayTypes.length; i++) {
		if (arrPayTypes[i].payType === internalPayMethod) {
			const { payTypeProps } = arrPayTypes[i];
			for (let j = 0; j < payTypeProps.length; j++) {
				if (payTypeProps[j].exchangeId === exchangeId) {
					externalPayMethod =
						flagPayProps === 'payId'
							? payTypeProps[j].payId
							: payTypeProps[j].payName;
				}
			}
		}
	}
	// console.log(externalPayMethod);
	return externalPayMethod;
};

// получение payType by payId or payName
export const getPayMethodProps = (
	exchangeId,
	externalPayMethod,
	arrPayTypes
) => {
	const props = { payName: '', payId: '' };
	for (let i = 0; i < arrPayTypes.length; i++) {
		const { payTypeProps } = arrPayTypes[i];
		for (let j = 0; j < payTypeProps.length; j++) {
			if (
				payTypeProps[j].exchangeId === exchangeId &&
				(payTypeProps[j].payName === externalPayMethod ||
					payTypeProps[j].payId === externalPayMethod)
			) {
				props.payName = arrPayTypes[i].payType;
				props.payId = arrPayTypes[i]._id.toString();
			}
		}
	}
	// console.log(props);
	return props;
};

// получение coinId or coinName by currency
export const getPropsCurrency = (
	exchangeId,
	nameCurrency,
	typeCurrency,
	arrCurrencies
) => {
	const props = { coinName: '', coinId: '' };
	for (let i = 0; i < arrCurrencies.length; i++) {
		const { currencyProps } = arrCurrencies[i];
		if (
			arrCurrencies[i].currencyType === typeCurrency &&
			arrCurrencies[i].currency === nameCurrency
		) {
			for (let j = 0; j < currencyProps.length; j++) {
				if (currencyProps[j].exchangeId === exchangeId) {
					props.coinName = currencyProps[j].coinName;
					props.coinId = currencyProps[j].coinId;
				}
			}
		}
	}
	// console.log(props);
	return props;
};

// получение  currency by coinId
export const getPropsCurrencyReverse = (
	exchangeId,
	externalCurrencyId,
	arrCurrencies,
	typeCurrency
) => {
	const props = { coinName: '', coinId: '' };
	for (let i = 0; i < arrCurrencies.length; i++) {
		if (arrCurrencies[i].currencyType === typeCurrency) {
			const { currencyProps } = arrCurrencies[i];
			for (let j = 0; j < currencyProps.length; j++) {
				if (
					currencyProps[j].exchangeId === exchangeId &&
					currencyProps[j].coinId === externalCurrencyId
				) {
					props.coinName = arrCurrencies[i].currency;
					props.coinId = currencyProps[j].coinId;
				}
			}
		}
	}
	// console.log(props);
	return props;
};

// получение наименования PaySubAccount
export const getPaySubAccount = (payMethodId) => {
	let sub = '';
	// Sber
	if (payMethodId === '62ab3f114399fc08ec9725b6') sub = 'S01';
	// Tink
	else if (payMethodId === '62ab3f124399fc08ec9725b7') sub = 'T01';
	// Trans
	else if (payMethodId === '62ab3f124399fc08ec9725b8') sub = 'T01';
	// Qiwi
	else if (payMethodId === '62ab3f144399fc08ec9725bf') sub = 'Q21';
	// Yndx
	else if (payMethodId === '62ab3f154399fc08ec9725c0') sub = 'Y02';
	// YMon
	else if (payMethodId === '62ab3f154399fc08ec9725c1') sub = 'Y02';
	// SPB
	else if (payMethodId === '62ab3f114399fc08ec9725b5') sub = 'T04';
	// Riff
	else if (payMethodId === '62ab3f164399fc08ec9725c4') sub = 'R01';
	// Alfa
	else if (payMethodId === '62ab3f114399fc08ec9725b4') sub = 'A02';
	// VTB
	else if (payMethodId === '62ab3f144399fc08ec9725be') sub = 'V02';
	// Open
	else if (payMethodId === '62ab3f154399fc08ec9725c2') sub = 'S01';
	// Gazprom
	else if (payMethodId === '62ab3f164399fc08ec9725c5') sub = 'T01';
	// RussianStandart
	else if (payMethodId === '62ab3f174399fc08ec9725c7') sub = 'T04';
	// Post
	else if (payMethodId === '62ab3f194399fc08ec9725cc') sub = 'T04';
	// Sovcom
	else if (payMethodId === '62ab3f1b4399fc08ec9725d4') sub = 'M01';
	// RosB
	else if (payMethodId === '62ab3f184399fc08ec9725cb') sub = 'RS1';
	// C2C
	else if (payMethodId === '634e63ea4185891994e350d3') sub = 'T04';
	// MTS
	else if (payMethodId === '62ab3f1b4399fc08ec9725d4') sub = 'T04';
	// Uralsib
	else if (payMethodId === '62ab3f214399fc08ec9725e4') sub = 'T04';
	// AkBars
	else if (payMethodId === '62ab3f1c4399fc08ec9725d7') sub = 'T04';
	// BankSaintPetersburg
	else if (payMethodId === '62ab3f1d4399fc08ec9725da') sub = 'PSB';
	// RosBank
	else if (payMethodId === '62ab3f184399fc08ec9725cb') sub = 'RS2';
	// HomeCredit
	else if (payMethodId === '62ab3f174399fc08ec9725c8') sub = 'T04';
	// BankTransferRussia
	else if (payMethodId === '62ab3f124399fc08ec9725b9') sub = 'T01';
	// AdvCash
	else if (payMethodId === '62ab3f194399fc08ec9725ce') sub = 'AD1';
	// Payeer
	else if (payMethodId === '62ab3f1a4399fc08ec9725d0') sub = 'PY1';
	// PerfectMoney
	else if (payMethodId === '62ab3f214399fc08ec9725e6') sub = 'PM1';
	// AirTM
	else if (payMethodId === '62ab3f244399fc08ec9725ed') sub = 'AT1';
	// Pay by USDT
	else if (payMethodId === '65649efd06ec8519c8ffaa5f') sub = 'MG1';
	// Kyrgystan banks KAV
	else if (
		payMethodId === '635d601f1406470ca4ad01d0' ||
		payMethodId === '668530c2e2cbdd2170e30352' ||
		payMethodId === '66853174e2cbdd2170e30354' ||
		payMethodId === '66853219e2cbdd2170e30356' ||
		payMethodId === '668532a2e2cbdd2170e30358' ||
		payMethodId === '6685332ae2cbdd2170e3035a' ||
		payMethodId === '6685339ce2cbdd2170e3035c' || // Bakai
		payMethodId === '66853442e2cbdd2170e30360' ||
		payMethodId === '6685349ee2cbdd2170e30362' ||
		payMethodId === '668534f8e2cbdd2170e30364' ||
		payMethodId === '6685354be2cbdd2170e30366'
	)
		sub = 'KGS';
	// Kazahstan banks KAV
	else if (
		payMethodId === '671b4bf400b2dc0de491a832' || // Kaspi
		payMethodId === '671b4d1400b2dc0de491a834' || // Forte
		payMethodId === '671b4d9600b2dc0de491a837' // Freedom
	)
		sub = 'KZT';
	return sub;
};

// Log inserting spot-, merchant- orders
export const consoleProcessed = (
	userId,
	prefix,
	arrOrds,
	count,
	typeOrd
) => {
	const postText =
		typeOrd === 'SPOT'
			? TEXT_CONSTANTS.SPOT_ORDER_DETAILS_DB_OK
			: TEXT_CONSTANTS.USER_ORDER_DETAILS_DB_OK;
	const msg = `${prefix}: ${postText}: ${count} | processed: ${arrOrds.length}`;
	console.log('****' + userId.slice(-4) + ' | ' + msg);
};

// Обновление авторизационного токена _BZ, _GX
export const updateAuthToken_BZ_GX = async (
	exchange,
	userProperties,
	userId,
	requestHeader
) => {
	for (let i = 0; i < userProperties.length; i++) {
		if (
			userProperties[i].exchange === exchange ||
			userProperties[i].exchangeId === exchange
		) {
			if (exchange === 'Garantex') {
				userProperties[i].requestHeader = {
					...requestHeader,
					token: await getToken_GX(userId),
				};
			} else if (exchange === 'Bitzlato') {
				userProperties[i].requestHeader = {
					...requestHeader,
					token: await getToken_P2P_BZ(userId),
				};
			} else userProperties[i].requestHeader = requestHeader;
		}
	}
	return userProperties;
};

// получение obj exchange по id биржи
export const getObjExchangeById = (arr, exchangeId) => {
	const objExchanges = arr.filter((item) => {
		return item._id.toString() === exchangeId;
	});
	return objExchanges[0];
};

// Получение объекта параметров для запросов by API or requestHeader
export const getObjectRequestParams = (params) => {
	const {
		userId,
		prefix,
		apiKeys,
		requestHeader,
		constants,
		additionals,
	} = params;
	const objParams = { userId, prefix };

	const endTime = new Date().getTime();
	const startTime = endTime - 60000 * 60 * 24 * 60; // 60 days ago

	const getFilteredRequestHeaderBX = (typeReq, requestHeader) => {
		// "running" | "completed" | "balances"
		const arr = requestHeader.additionals.slice();
		const rh = arr.filter((item) => {
			return item.typeRequest === typeReq;
		});
		// console.log(rh[0]);
		return rh[0];
	};

	if (prefix === 'otc_BN') {
		objParams.prefix = 'BN';
		objParams.config = {
			withCredentials: true,
			method: constants.GET_MERCHANT_ORDERS.method,
			url: constants.GET_MERCHANT_ORDERS.url,
			data: {
				page: 1,
				rows: 20,
				endDate: endTime,
				orderStatusList: null,
				startDate: startTime, // 60 days
			},
			headers: {
				'access-control-allow-credentials': true,
				'Access-Control-Allow-Origin': '*',
				'content-type': 'application/json;charset=UTF-8',
				clienttype: 'web',
				cookie: requestHeader.cookie,
				csrftoken: requestHeader.csrftoken,
				'device-info': requestHeader.deviceInfo,
				'user-agent': requestHeader.userAgent,
			},
		};
	} else if (prefix === 'otc_BN_API') {
		const query_string = `tradeType=${additionals.side}&rows=20&timestamp=${endTime}`;
		const signature = getSignature_BN(query_string, apiKeys.secretKey);
		objParams.prefix = 'BN_API';
		objParams.config = {
			withCredentials: true,
			method: constants.GET_MERCHANT_ORDERS_BY_API.method,
			url: `${constants.GET_MERCHANT_ORDERS_BY_API.url}?${query_string}&signature=${signature}`,
			data: null,
			headers: {
				'X-MBX-APIKEY': apiKeys.publicKey,
				'x-gray-env': '',
				'x-trace-id': '',
				'x-user-id': '',
				clientType: 'web',
			},
		};
	} else if (prefix === 'otcDetails_BN') {
		objParams.prefix = 'BN';
		objParams.config = {
			method: constants.GET_MERCHANT_ORDER_DETAILS.method,
			url: constants.GET_MERCHANT_ORDER_DETAILS.url,
			data: { orderNumber: additionals.order },
			headers: {
				'access-control-allow-credentials': true,
				'Access-Control-Allow-Origin': '*',
				'content-type': 'application/json;charset=UTF-8',
				clienttype: 'web',
				cookie: requestHeader.cookie,
				csrftoken: requestHeader.csrftoken,
				'device-info': requestHeader.deviceInfo,
				'user-agent': requestHeader.userAgent,
			},
		};
	} else if (prefix === 'balance_BN') {
		const objArgs = {
			method: 'GET',
			url: '',
			data: null,
		};
		if (additionals.typeBalance === 'SPOT') {
			objArgs.method = constants.GET_SPOT_BALANCE.method;
			objArgs.url = constants.GET_SPOT_BALANCE.url;
			objArgs.data = { needBtcValuation: true };
		} else if (additionals.typeBalance === 'P2P') {
			objArgs.method = constants.GET_P2P_BALANCE.method;
			objArgs.url = constants.GET_P2P_BALANCE.url;
		} else if (additionals.typeBalance === 'FUT') {
			objArgs.method = constants.GET_FUT_BALANCE.method;
			objArgs.url = constants.GET_FUT_BALANCE.url;
			objArgs.data = { asset: '' };
		} else if (additionals.typeBalance === 'EARN') {
			objArgs.method = constants.GET_EARN_BALANCE.method;
			objArgs.url = constants.GET_EARN_BALANCE.url;
		} else if (additionals.typeBalance === 'LOCK') {
			objArgs.method = constants.GET_DATA_LOCKED.method;
			objArgs.url = constants.GET_DATA_LOCKED.url;
			objArgs.data = { coin: 'BTC' };
		}
		objParams.prefix = 'BN';
		objParams.config = {
			withCredentials: true,
			method: objArgs.method,
			url: objArgs.url,
			data: objArgs.data,
			headers: {
				'access-control-allow-credentials': true,
				'Access-Control-Allow-Origin': '*',
				'content-type': 'application/json;charset=UTF-8',
				clienttype: 'web',
				cookie: requestHeader.cookie,
				csrftoken: requestHeader.csrftoken,
				'device-info': requestHeader.deviceInfo,
				'user-agent': requestHeader.userAgent,
			},
		};
	} else if (prefix === 'active_BN_API') {
		// const timestamp = Date.now();
		const query_string = `timestamp=${endTime}`;
		const signature = getSignature_BN(query_string, apiKeys.secretKey);
		objParams.prefix = 'BN_API';
		objParams.config = {
			withCredentials: true,
			method: constants.GET_ACTIVE_SPOT_ORDERS_BY_API.method,
			url: `${constants.GET_ACTIVE_SPOT_ORDERS_BY_API.url}?${query_string}&signature=${signature}`,
			data: null, // for GETs
			// data: {}, // for POSTs
			// data: payload, // for POSTs
			headers: {
				// 'access-control-allow-credentials': true,
				// 'Access-Control-Allow-Origin': '*',
				// 'content-type':'application/json;charset=UTF-8',
				'X-MBX-APIKEY': apiKeys.publicKey,
				'x-gray-env': '',
				'x-trace-id': '',
				'x-user-id': '',
				clientType: 'web',
			},
		};
	} else if (prefix === 'history_BN') {
		objParams.prefix = 'BN';
		objParams.config = {
			withCredentials: true,
			method: constants.GET_HISTORY_SPOT_ORDERS.method,
			url: constants.GET_HISTORY_SPOT_ORDERS.url,
			data: {
				baseAsset: '',
				direction: '',
				endTime,
				hideCancel: false,
				page: 1,
				quoteAsset: '',
				rows: 20,
				startTime,
			},
			headers: {
				'access-control-allow-credentials': true,
				'Access-Control-Allow-Origin': '*',
				'content-type': 'application/json;charset=UTF-8',
				c2ctype: 'c2c_merchant',
				clienttype: 'web',
				cookie: requestHeader.cookie,
				csrftoken: requestHeader.csrftoken,
				'device-info': requestHeader.deviceInfo,
				'user-agent': requestHeader.userAgent,
			},
		};
	} else if (prefix === 'p2p_BN') {
		objParams.prefix = 'BN';
		objParams.config = {
			withCredentials: true,
			method: constants.GET_P2P_ORDERS.method,
			url: constants.GET_P2P_ORDERS.url,
			data: {
				page: additionals.page,
				rows: additionals.rows,
				fiat: additionals.fiat,
				asset: additionals.asset,
				tradeType: additionals.tradeType,
				transAmount: additionals.transAmount,
				payTypes: additionals.payTypes,
				proMerchantAds: false,
				publisherType: null,
				shieldMerchantAds: false,
				countries: [],
			},
			headers: null,
		};
	} else if (prefix === 'spot_tickers_BN_API') {
		// recvWindow=5000&
		const query_string = `timestamp=${endTime}`;
		const signature = getSignature_BN(query_string, apiKeys.secretKey);
		objParams.typeMarket = additionals.typeMarket;
		objParams.prefix = 'BN_API';
		objParams.config = {
			withCredentials: true,
			method: constants.GET_ALL_TICKERS_SPOT_BY_API.method,
			url: `${constants.GET_ALL_TICKERS_SPOT_BY_API.url}?${query_string}&signature=${signature}`,
			data: null,
			headers: {
				'X-MBX-APIKEY': apiKeys.publicKey,
				'x-gray-env': '',
				'x-trace-id': '',
				'x-user-id': '',
				clientType: 'web',
			},
		};
	} else if (prefix === 'fut_tickers_BN_API') {
		const query_string = `timestamp=${endTime}`;
		const signature = getSignature_BN(query_string, apiKeys.secretKey);
		objParams.typeMarket = additionals.typeMarket;
		objParams.prefix = 'BN_API';
		objParams.config = {
			withCredentials: true,
			method: constants.GET_ALL_TICKERS_FUT_BY_API.method,
			url: `${constants.GET_ALL_TICKERS_FUT_BY_API.url}?${query_string}&signature=${signature}`,
			data: null,
			headers: {
				'X-MBX-APIKEY': apiKeys.publicKey,
				'x-gray-env': '',
				'x-trace-id': '',
				'x-user-id': '',
				clientType: 'web',
			},
		};
	} else if (prefix === 'advs_BN') {
	} else if (prefix === 'otc_HB') {
		const query_string = `orderStatus=all&currPage=1&orderType=all&exactOrderStatus=all&side=all&isUnread=false`;
		objParams.prefix = 'HB';
		objParams.config = {
			withCredentials: true,
			method: constants.GET_MERCHANT_ORDERS.method,
			url: `${constants.GET_MERCHANT_ORDERS.url}?${query_string}`,
			data: null,
			headers: {
				'access-control-allow-credentials': true,
				'Access-Control-Allow-Origin': '*',
				'content-type': 'application/json;charset=UTF-8',
				portal: 'web',
				token: requestHeader.token,
				// token: "MuPhvMTyvlaNLy6m1YK7XncLyRIczMs9qioBlz-sVaBaBW1Dc7l9QPyYmHeh2Lb5GPrjj9ptPoL4xOe2ndagxQ",
				'user-agent': requestHeader.userAgent,
			},
		};
	} else if (prefix === 'otcDetails_HB') {
		const query_string = `orderId=${additionals.order}`;
		objParams.prefix = 'HB';
		objParams.config = {
			method: constants.GET_MERCHANT_ORDER_DETAILS.method,
			url: `${constants.GET_MERCHANT_ORDER_DETAILS.url}?${query_string}`,
			data: null,
			headers: {
				'access-control-allow-credentials': true,
				'Access-Control-Allow-Origin': '*',
				'content-type': 'application/json;charset=UTF-8',
				portal: 'web',
				token: requestHeader.token,
				'user-agent': requestHeader.userAgent,
			},
		};
	} else if (prefix === 'balance_HB') {
		const { typeBalance } = additionals;
		let method = constants.GET_SPOT_BALANCE.method;
		let url = constants.GET_SPOT_BALANCE.url;
		let headers = {
			Accept: '*/*',
			'Access-Control-Allow-Origin': '*',
			'hb-pro-token': requestHeader.token,
			'user-agent': requestHeader.userAgent,
			cookie: requestHeader.cookie,
		};
		if (typeBalance === 'FUT') {
			method = constants.GET_FUT_BALANCE.method;
			url = constants.GET_FUT_BALANCE.url;
		}
		// 'P2P'
		else if (typeBalance === 'P2P') {
			method = constants.GET_P2P_BALANCE.method;
			url = constants.GET_P2P_BALANCE.url;
			headers = {
				Accept: '*/*',
				'Access-Control-Allow-Origin': '*',
				// 'accept-encoding':'gzip, deflate, br',
				token: requestHeader.token,
				'user-agent': requestHeader.userAgent,
			};
		}
		objParams.prefix = 'HB';
		objParams.config = {
			withCredentials: true,
			method,
			url,
			data: typeBalance === 'P2P' ? { trade_partition: 'ALL' } : null,
			headers,
		};
	} else if (prefix === 'balance_HB_API') {
		const { typeBalance, accountId } = additionals;
		const details = typeBalance === 'ALL' ? '' : `${accountId}/balance`;

		const url = `${constants.GET_USER_BALANCES_BY_API.url + details}`;
		const method = constants.GET_USER_BALANCES_BY_API.method;

		const tsParsed = new Date(endTime)
			.toISOString()
			.split('.')[0]
			.replaceAll(':', '%3A');
		const query_string = `AccessKeyId=${apiKeys.publicKey}&SignatureMethod=HmacSHA256&SignatureVersion=2&Timestamp=${tsParsed}`;
		const preSignedText =
			method +
			'\n' +
			`api.huobi.pro\n/v1/account/accounts/${details}\n` +
			query_string;
		const signature = getSignature_HB(preSignedText, apiKeys.secretKey);
		objParams.prefix = 'HB_API';
		objParams.config = {
			withCredentials: true,
			method,
			url: `${url}?${query_string}&Signature=${signature}`,
			data: null,
			headers: {
				'Content-Type': 'application/json',
				'user-agent': requestHeader.userAgent,
			},
		};
	} else if (prefix === 'active_HB') {
		const query_string = `direction=all&size=11&currentPage=0&types=buy-limit,sell-limit`;
		objParams.prefix = 'HB';
		objParams.config = {
			withCredentials: true,
			method: constants.GET_ACTIVE_SPOT_ORDERS.method,
			url: `${constants.GET_ACTIVE_SPOT_ORDERS.url}?${query_string}`,
			data: null,
			headers: {
				'access-control-allow-credentials': true,
				'Access-Control-Allow-Origin': '*',
				'content-type': 'application/json;charset=UTF-8',
				portal: 'web',
				'hb-pro-token': requestHeader.token,
				'user-agent': requestHeader.userAgent,
			},
		};
	} else if (prefix === 'history_HB') {
		const timeStart = new Date(startTime).toISOString().split('T')[0];
		const timeEnd = new Date(endTime).toISOString().split('T')[0];
		const size = additionals.size;
		const query_string = `states=filled&start-date=${timeStart}&end-date=${timeEnd}&direction=all&size=${size}&currentPage=0&types=buy-limit,sell-limit,buy-market,sell-market,buy-ioc,sell-ioc,buy-limit-maker,sell-limit-maker,buy-limit-fok,sell-limit-fok`;
		objParams.prefix = 'HB';
		objParams.config = {
			withCredentials: true,
			method: constants.GET_HISTORY_SPOT_ORDERS.method,
			url: `${constants.GET_HISTORY_SPOT_ORDERS.url}?${query_string}`,
			data: null,
			headers: {
				'access-control-allow-credentials': true,
				'Access-Control-Allow-Origin': '*',
				'content-type': 'application/json;charset=UTF-8',
				portal: 'web',
				'hb-pro-token': requestHeader.token,
				'user-agent': requestHeader.userAgent,
			},
		};
	} else if (prefix === 'active_HB_API') {
		const url = constants.GET_ACTIVE_SPOT_ORDERS_BY_API.url;
		const method = constants.GET_ACTIVE_SPOT_ORDERS_BY_API.method;

		const tsParsed = new Date(endTime)
			.toISOString()
			.split('.')[0]
			.replaceAll(':', '%3A');
		const query_string = `AccessKeyId=${apiKeys.publicKey}&SignatureMethod=HmacSHA256&SignatureVersion=2&Timestamp=${tsParsed}`;
		const preSignedText =
			method +
			'\n' +
			`api.huobi.pro\n/v1/order/openOrders\n` +
			query_string;
		const signature = getSignature_HB(preSignedText, apiKeys.secretKey);
		objParams.prefix = 'HB_API';
		objParams.config = {
			withCredentials: true,
			method,
			url: `${url}?${query_string}&Signature=${signature}`,
			data: null,
			headers: {
				'Content-Type': 'application/json',
				'user-agent': requestHeader.userAgent,
			},
		};
	} else if (prefix === 'history_HB_API') {
		const url = constants.GET_HISTORY_SPOT_ORDERS_BY_API.url;
		const method = constants.GET_HISTORY_SPOT_ORDERS_BY_API.method;

		const tsParsed = new Date(endTime)
			.toISOString()
			.split('.')[0]
			.replaceAll(':', '%3A');
		const query_string = `AccessKeyId=${apiKeys.publicKey}&SignatureMethod=HmacSHA256&SignatureVersion=2&Timestamp=${tsParsed}`;
		const preSignedText =
			method + '\n' + `api.huobi.pro\n/v1/order/history\n` + query_string;
		const signature = getSignature_HB(preSignedText, apiKeys.secretKey);
		objParams.prefix = 'HB_API';
		objParams.config = {
			withCredentials: true,
			method,
			url: `${url}?${query_string}&Signature=${signature}`,
			data: null,
			headers: {
				'Content-Type': 'application/json',
				'user-agent': requestHeader.userAgent,
			},
		};
	} else if (prefix === 'p2p_HB') {
	} else if (prefix === 'spot_tickers_HB_API') {
		const url = constants.GET_ALL_TICKERS_SPOT_BY_API.url;
		const method = constants.GET_ALL_TICKERS_SPOT_BY_API.method;
		const tsParsed = new Date(endTime)
			.toISOString()
			.split('.')[0]
			.replaceAll(':', '%3A');
		const query_string = `AccessKeyId=${apiKeys.publicKey}&SignatureMethod=HmacSHA256&SignatureVersion=2&Timestamp=${tsParsed}`;
		const preSignedText =
			method + '\n' + `api.huobi.pro\n/market/tickers\n` + query_string;
		const signature = getSignature_HB(preSignedText, apiKeys.secretKey);
		objParams.typeMarket = additionals.typeMarket;
		objParams.prefix = 'HB_API';
		objParams.config = {
			withCredentials: true,
			method,
			url: `${url}?${query_string}&Signature=${signature}`,
			data: null,
			headers: {
				'Content-Type': 'application/json',
				'user-agent': requestHeader.userAgent,
			},
		};
	} else if (prefix === 'fut_tickers_HB_API') {
		const url = constants.GET_ALL_TICKERS_FUT_BY_API.url;
		const method = constants.GET_ALL_TICKERS_FUT_BY_API.method;
		const tsParsed = new Date(endTime)
			.toISOString()
			.split('.')[0]
			.replaceAll(':', '%3A');
		const query_string = `AccessKeyId=${apiKeys.publicKey}&SignatureMethod=HmacSHA256&SignatureVersion=2&Timestamp=${tsParsed}`;
		const preSignedText =
			method +
			'\n' +
			`api.hbdm.com\n/v2/linear-swap-ex/market/detail/batch_merged\n` +
			query_string;
		const signature = getSignature_HB(preSignedText, apiKeys.secretKey);
		objParams.typeMarket = additionals.typeMarket;
		objParams.prefix = 'HB_API';
		objParams.config = {
			withCredentials: true,
			method,
			url: `${url}?${query_string}&Signature=${signature}`,
			data: null,
			headers: {
				'Content-Type': 'application/json',
				'user-agent': requestHeader.userAgent,
			},
		};
	} else if (prefix === 'advs_HB') {
	} else if (prefix === 'otc_KX') {
		const query_string = `t=${endTime}&side=all&status=all&startTime=${startTime}&endTime=${endTime}&halfAYear=true&pageSize=${20}&topAppealOrders=false&pageType=true&pageIndex=${1}`;
		objParams.prefix = 'KX';
		objParams.config = {
			withCredentials: true,
			method: constants.GET_MERCHANT_ORDERS.method,
			url: `${constants.GET_MERCHANT_ORDERS.url}?${query_string}`,
			data: null,
			headers: {
				'access-control-allow-credentials': true,
				'Access-Control-Allow-Origin': '*',
				'content-type': 'application/json;charset=UTF-8',
				authorization: requestHeader.authorization,
				cookie: requestHeader.cookie,
				devid: requestHeader.devId,
				'user-agent': requestHeader.userAgent,
			},
		};
	} else if (prefix === 'otcDetails_KX') {
		const query_string = `${additionals.order}?${endTime}`;
		objParams.prefix = 'KX';
		objParams.config = {
			method: constants.GET_MERCHANT_ORDER_DETAILS.method,
			url: `${constants.GET_MERCHANT_ORDER_DETAILS.url}/${query_string}`,
			data: null,
			headers: {
				'access-control-allow-credentials': true,
				'Access-Control-Allow-Origin': '*',
				'content-type': 'application/json;charset=UTF-8',
				authorization: requestHeader.authorization,
				cookie: requestHeader.cookie,
				devid: requestHeader.devId,
				'user-agent': requestHeader.userAgent,
			},
		};
	} else if (prefix === 'balance_KX') {
		const { typeBalance } = additionals;
		const method =
			typeBalance === 'SPOT'
				? constants.GET_SPOT_BALANCE.method
				: constants.GET_P2P_BALANCE.method;
		const url =
			typeBalance === 'SPOT'
				? `${constants.GET_SPOT_BALANCE.url}?transferFrom=18&valuationUnit=USDT&t=${endTime}&pagination=true&pageNum=1&pageSize=30`
				: `${constants.GET_P2P_BALANCE.url}?transferFrom=6&valuationUnit=USDT&t=${endTime}`;
		objParams.prefix = 'KX';
		objParams.config = {
			withCredentials: true,
			method,
			url,
			data: null,
			headers: {
				'Access-Control-Allow-Origin': '*',
				'accept-encoding': 'gzip, deflate, br',
				authorization: requestHeader.authorization,
				'user-agent': requestHeader.userAgent,
				cookie: requestHeader.cookie,
			},
		};
	} else if (prefix === 'active_KX') {
		const query_string = `t=${endTime}&ordType=limit,market,mmp&limit=20&_feReq=true`;
		objParams.prefix = 'KX';
		objParams.config = {
			withCredentials: true,
			method: constants.GET_ACTIVE_SPOT_ORDERS.method,
			url: `${constants.GET_ACTIVE_SPOT_ORDERS.url}?${query_string}`,
			data: null,
			headers: {
				'access-control-allow-credentials': true,
				'Access-Control-Allow-Origin': '*',
				'content-type': 'application/json;charset=UTF-8',
				authorization: requestHeader.authorization,
				cookie: requestHeader.cookie,
				devid: requestHeader.devId,
				'user-agent': requestHeader.userAgent,
			},
		};
	} else if (prefix === 'history_KX') {
		const query_string = `t=${endTime}&ordType=limit,market,mmp&_start=${startTime}&_end=${endTime}&limit=${20}&_feReq=true&state=filled&_sortType=filledTime`;
		objParams.prefix = 'KX';
		objParams.config = {
			withCredentials: true,
			method: constants.GET_HISTORY_SPOT_ORDERS.method,
			url: `${constants.GET_HISTORY_SPOT_ORDERS.url}?${query_string}`,
			data: null,
			headers: {
				'access-control-allow-credentials': true,
				'Access-Control-Allow-Origin': '*',
				'content-type': 'application/json;charset=UTF-8',
				authorization: requestHeader.authorization,
				cookie: requestHeader.cookie,
				devid: requestHeader.devId,
				'user-agent': requestHeader.userAgent,
			},
		};
	} else if (prefix === 'p2p_KX') {
	} else if (prefix === 'spot_tickers_KX_API') {
		const tsParsed = new Date(endTime).toISOString();
		const method = constants.GET_ALL_TICKERS_SPOT_BY_API.method;
		const url = constants.GET_ALL_TICKERS_SPOT_BY_API.url;
		const query_string = `instType=SPOT`;
		const signature = getSignature_KX(
			`${tsParsed}${method}${url}?${query_string}`,
			apiKeys.secretKey
		);
		objParams.typeMarket = additionals.typeMarket;
		objParams.prefix = 'KX_API';
		objParams.config = {
			withCredentials: true,
			method,
			url: `${url}?${query_string}`,
			data: null,
			headers: {
				'content-type': 'application/json;charset=UTF-8',
				'OK-ACCESS-KEY': `${apiKeys.publicKey}`,
				'OK-ACCESS-SIGN': `${signature}`,
				'OK-ACCESS-TIMESTAMP': `${tsParsed}`,
				'OK-ACCESS-PASSPHRASE': 'TCAe2e9Fyy',
			},
		};
	} else if (prefix === 'fut_tickers_KX_API') {
		const tsParsed = new Date(endTime).toISOString();
		const method = constants.GET_ALL_TICKERS_SPOT_BY_API.method;
		const url = constants.GET_ALL_TICKERS_SPOT_BY_API.url;
		const query_string = `instType=SWAP`;
		const signature = getSignature_KX(
			`${tsParsed}${method}${url}?${query_string}`,
			apiKeys.secretKey
		);
		objParams.typeMarket = additionals.typeMarket;
		objParams.prefix = 'KX_API';
		objParams.config = {
			withCredentials: true,
			method,
			url: `${url}?${query_string}`,
			data: null,
			headers: {
				'content-type': 'application/json;charset=UTF-8',
				'OK-ACCESS-KEY': `${apiKeys.publicKey}`,
				'OK-ACCESS-SIGN': `${signature}`,
				'OK-ACCESS-TIMESTAMP': `${tsParsed}`,
				'OK-ACCESS-PASSPHRASE': 'TCAe2e9Fyy',
			},
		};
	} else if (prefix === 'advs_KX') {
	} else if (prefix === 'otc_GX') {
		const query_string = `limit=${20}`;
		objParams.prefix = 'GX';
		objParams.config = {
			// withCredentials: true,
			method: constants.GET_MERCHANT_ORDERS.method,
			url: `${constants.GET_MERCHANT_ORDERS.url}?${query_string}`,
			data: null,
			headers: { Authorization: `Bearer ${requestHeader.token}` },
		};
	} else if (prefix === 'otcDetails_GX') {
		const query_string = `${additionals.order}`;
		objParams.prefix = 'GX';
		objParams.config = {
			method: constants.GET_MERCHANT_ORDER_DETAILS.method,
			url: `${constants.GET_MERCHANT_ORDER_DETAILS.url}${query_string}`,
			data: null,
			headers: { Authorization: `Bearer ${requestHeader.token}` },
		};
	} else if (prefix === 'balance_GX') {
		objParams.prefix = 'GX';
		objParams.config = {
			withCredentials: true,
			method: constants.GET_P2P_BALANCE.method,
			url: constants.GET_P2P_BALANCE.url,
			data: null,
			headers: {
				Authorization: `Bearer ${requestHeader.token}`,
			},
		};
	} else if (prefix === 'active_GX') {
		objParams.prefix = 'GX_API';
		objParams.config = {
			withCredentials: true,
			method: constants.GET_ACTIVE_SPOT_ORDERS.method,
			url: `${constants.GET_ACTIVE_SPOT_ORDERS.url}?market=usdtrub&state=wait`,
			data: null,
			headers: { Authorization: `Bearer ${requestHeader.token}` },
		};
	} else if (prefix === 'history_GX') {
		objParams.prefix = 'GX_API';
		objParams.config = {
			withCredentials: true,
			method: constants.GET_HISTORY_SPOT_ORDERS.method,
			url: `${constants.GET_HISTORY_SPOT_ORDERS.url}?limit=${50}`,
			data: null,
			headers: { Authorization: `Bearer ${requestHeader.token}` },
		};
	} else if (prefix === 'p2p_GX') {
	} else if (prefix === 'advs_GX') {
	} else if (prefix === 'otc_BT') {
		const query_string = `tokenId=${
			additionals.token
		}&page=${1}&size=${20}`;
		objParams.prefix = 'BT';
		objParams.config = {
			// withCredentials:true,
			method: constants.GET_MERCHANT_ORDERS.method,
			// url: `${constants.GET_MERCHANT_ORDERS.url}?${query_string}`,
			url: constants.GET_MERCHANT_ORDERS.url,
			data: { page: 1, size: 20 },
			headers: {
				'Access-Control-Allow-Origin': '*',
				accept: 'application/json',
				// 'user-agent': 'PostmanRuntime/7.41.2',
				cookie: requestHeader.cookie,
			},
		};
	} else if (prefix === 'otcDetails_BT') {
		// const query_string = `orderId=${additionals.order}`;
		objParams.prefix = 'BT';
		objParams.config = {
			method: constants.GET_MERCHANT_ORDER_DETAILS.method,
			url: constants.GET_MERCHANT_ORDER_DETAILS.url,
			data: { orderId: additionals.order },
			headers: {
				'Access-Control-Allow-Origin': '*',
				// 'accept-encoding': 'gzip, deflate, br',
				accept: 'application/json',
				// 'user-agent': 'PostmanRuntime/7.29.0',
				// 'user-agent':requestHeaderBT.userAgent,
				cookie: requestHeader.cookie,
			},
		};
	} else if (prefix === 'balance_BT') {
		const { typeBalance } = additionals;
		// 'SPOT'
		let method = constants.GET_SPOT_BALANCE.method;
		let url = constants.GET_SPOT_BALANCE.url;
		let headers = {
			'Access-Control-Allow-Origin': '*',
			'accept-encoding': 'gzip, deflate, br',
			'user-agent': 'PostmanRuntime/7.29.0',
			// cookie: req.body.requestHeader.cookie,
			// usertoken: req.body.requestHeader.usertoken,
			cookie: requestHeader.cookie,
			usertoken: requestHeader.usertoken,
		};
		// 'SPOT_API'
		if (typeBalance === 'SPOT_API') {
			const recv_window = '5000';
			const query_string = `accountType=UNIFIED`;
			const paramStr = `${endTime}${apiKeys.publicKey}${recv_window}`;
			const signature = getSignature_BT(
				paramStr + query_string,
				apiKeys.secretKey
			);
			method = constants.GET_SPOT_BALANCE_BY_API.method;
			url = `${constants.GET_SPOT_BALANCE_BY_API.url}?${query_string}`;
			headers = {
				'X-BAPI-SIGN': `${signature}`,
				'X-BAPI-API-KEY': `${apiKeys.publicKey}`,
				'X-BAPI-TIMESTAMP': `${endTime}`,
				'X-BAPI-RECV-WINDOW': `${recv_window}`,
			};
		} else if (typeBalance === 'FUT') {
			method = constants.GET_FUT_BALANCE.method;
			url = `${constants.GET_FUT_BALANCE.url}?quoteCoin=USDT&balanceType=1`;
		}
		// 'P2P'
		else if (typeBalance === 'P2P') {
			method = constants.GET_P2P_BALANCE.method;
			url = constants.GET_P2P_BALANCE.url;
		}
		objParams.prefix = typeBalance === 'SPOT_API' ? 'BT_API' : 'BT';
		objParams.config = {
			withCredentials: true,
			method,
			url,
			data: null,
			headers,
		};
	} else if (prefix === 'active_BT') {
		// const query_string = `limit=21&s=getOrders&from_order_id=0`;
		objParams.prefix = 'BT';
		objParams.config = {
			withCredentials: true,
			method: constants.GET_ACTIVE_SPOT_ORDERS.method,
			url: constants.GET_ACTIVE_SPOT_ORDERS.url,
			// url: `${constants.GET_ACTIVE_SPOT_ORDERS.url}?${query_string}`,
			data: {
				specialTradeFrom: 1,
				direction: 'next',
				limit: 11,
				type: 'Limit',
				planType: -1,
			},
			headers: {
				'Access-Control-Allow-Origin': '*',
				'accept-encoding': 'gzip, deflate, br',
				'user-agent': 'PostmanRuntime/7.29.0',
				cookie: requestHeader.cookie,
				usertoken: requestHeader.usertoken,
			},
		};
	} else if (prefix === 'history_BT') {
		// const query_string = `limit=${20}&s=getOrders&from_trade_id=0&start_time=${startTime}&end_time=${endTime}`;
		objParams.prefix = 'BT';
		objParams.config = {
			withCredentials: true,
			method: constants.GET_HISTORY_SPOT_ORDERS.method,
			url: constants.GET_HISTORY_SPOT_ORDERS.url,
			// url: `${constants.GET_HISTORY_SPOT_ORDERS.url}?${query_string}`,
			data: {
				startTime,
				endTime,
				specialTradeFrom: 1,
				leverageType: 0,
				direction: 'next',
				limit: 11,
			},
			headers: {
				'Access-Control-Allow-Origin': '*',
				'accept-encoding': 'gzip, deflate, br',
				'user-agent': 'PostmanRuntime/7.29.0',
				cookie: requestHeader.cookie,
				usertoken: requestHeader.usertoken,
			},
		};
	} else if (prefix === 'active_BT_API') {
		const recv_window = '5000';
		const query_string = `category=spot&limit=21`;
		const paramStr = `${endTime}${apiKeys.publicKey}${recv_window}`;
		const signature = getSignature_BT(
			paramStr + query_string,
			apiKeys.secretKey
		);
		objParams.prefix = 'BT_API';
		objParams.config = {
			withCredentials: true,
			method: constants.GET_ACTIVE_SPOT_ORDERS_BY_API.method,
			url: `${constants.GET_ACTIVE_SPOT_ORDERS_BY_API.url}?${query_string}`,
			data: null,
			headers: {
				'X-BAPI-SIGN': `${signature}`,
				'X-BAPI-API-KEY': `${apiKeys.publicKey}`,
				'X-BAPI-TIMESTAMP': `${endTime}`,
				'X-BAPI-RECV-WINDOW': `${recv_window}`,
				// clientType: 'web',
			},
		};
	} else if (prefix === 'history_BT_API') {
		const recv_window = '5000';
		// const query_string = `category=spot&startTime=${startTime}&endTime=${endTime}`;
		const query_string = `category=spot&limit=50`;
		const paramStr = `${endTime}${apiKeys.publicKey}${recv_window}`;
		const signature = getSignature_BT(
			paramStr + query_string,
			apiKeys.secretKey
		);
		objParams.prefix = 'BT_API';
		objParams.config = {
			withCredentials: true,
			method: constants.GET_HISTORY_SPOT_ORDERS_BY_API.method,
			url: `${constants.GET_HISTORY_SPOT_ORDERS_BY_API.url}?${query_string}`,
			data: null,
			headers: {
				'X-BAPI-SIGN': `${signature}`,
				'X-BAPI-API-KEY': `${apiKeys.publicKey}`,
				'X-BAPI-TIMESTAMP': `${endTime}`,
				'X-BAPI-RECV-WINDOW': `${recv_window}`,
				// clientType: 'web',
			},
		};
	} else if (prefix === 'p2p_BT') {
	} else if (prefix === 'spot_tickers_BT_API') {
		const recv_window = '5000';
		const query_string = `category=spot`;
		const paramStr = `${endTime}${apiKeys.publicKey}${recv_window}`;
		const signature = getSignature_BT(
			paramStr + query_string,
			apiKeys.secretKey
		);
		objParams.typeMarket = additionals.typeMarket;
		objParams.prefix = 'BT_API';
		objParams.config = {
			withCredentials: true,
			method: constants.GET_ALL_TICKERS_SPOT_BY_API.method,
			url: `${constants.GET_ALL_TICKERS_SPOT_BY_API.url}?${query_string}`,
			data: null,
			headers: {
				'X-BAPI-SIGN': `${signature}`,
				'X-BAPI-API-KEY': `${apiKeys.publicKey}`,
				'X-BAPI-TIMESTAMP': `${endTime}`,
				'X-BAPI-RECV-WINDOW': `${recv_window}`,
				// clientType: 'web',
			},
		};
	} else if (prefix === 'fut_tickers_BT_API') {
		const recv_window = '5000';
		const query_string = `category=linear`;
		const paramStr = `${endTime}${apiKeys.publicKey}${recv_window}`;
		const signature = getSignature_BT(
			paramStr + query_string,
			apiKeys.secretKey
		);
		objParams.typeMarket = additionals.typeMarket;
		objParams.prefix = 'BT_API';
		objParams.config = {
			withCredentials: true,
			method: constants.GET_ALL_TICKERS_FUT_BY_API.method,
			url: `${constants.GET_ALL_TICKERS_FUT_BY_API.url}?${query_string}`,
			data: null,
			headers: {
				'X-BAPI-SIGN': `${signature}`,
				'X-BAPI-API-KEY': `${apiKeys.publicKey}`,
				'X-BAPI-TIMESTAMP': `${endTime}`,
				'X-BAPI-RECV-WINDOW': `${recv_window}`,
				// clientType: 'web',
			},
		};
	} else if (prefix === 'advs_BT') {
	} else if (prefix === 'otc_BP') {
		objParams.prefix = 'BP';
		objParams.config = {
			withCredentials: true,
			method: constants.GET_MERCHANT_ORDERS_BY_API.method,
			url: constants.GET_MERCHANT_ORDERS_BY_API.url,
			data: null,
			// data: { page: 1 },
			headers: {
				'access-control-allow-credentials': true,
				'Access-Control-Allow-Origin': '*',
				'content-type': 'application/json;charset=UTF-8',
				'X-Access-Token': apiKeys.publicKey,
			},
		};
	} else if (prefix === 'otcDetails_BP') {
		const { order } = additionals;
		objParams.prefix = 'BP';
		objParams.config = {
			method: constants.GET_MERCHANT_ORDER_DETAILS_BY_API.method,
			url: `${constants.GET_MERCHANT_ORDER_DETAILS_BY_API.url}/${order}/`,
			data: null,
			headers: {
				'access-control-allow-credentials': true,
				'Access-Control-Allow-Origin': '*',
				'content-type': 'application/json;charset=UTF-8',
				'X-Access-Token': apiKeys.publicKey,
			},
		};
	} else if (prefix === 'balance_BP') {
		objParams.prefix = 'BP';
		objParams.config = {
			withCredentials: true,
			method: constants.GET_P2P_BALANCE_BY_API.method,
			url: constants.GET_P2P_BALANCE_BY_API.url,
			data: null,
			headers: {
				'access-control-allow-credentials': true,
				'Access-Control-Allow-Origin': '*',
				'content-type': 'application/json;charset=UTF-8',
				'X-Access-Token': apiKeys.publicKey,
			},
		};
	} else if (prefix === 'active_BP') {
		objParams.prefix = 'BP';
		objParams.config = {
			withCredentials: true,
			method: constants.GET_ACTIVE_SPOT_ORDERS.method,
			url: constants.GET_ACTIVE_SPOT_ORDERS.url,
			data: {},
			headers: {
				'access-control-allow-credentials': true,
				'Access-Control-Allow-Origin': '*',
				'content-type': 'application/json;charset=UTF-8',
				// c2ctype: 'c2c_merchant',
				clienttype: 'web',
				cookie: requestHeader.cookie,
				csrftoken: requestHeader.csrftoken,
				'device-info': requestHeader.deviceInfo,
				'user-agent': requestHeader.userAgent,
			},
		};
	} else if (prefix === 'history_BP') {
		objParams.prefix = 'BP';
		objParams.config = {
			withCredentials: true,
			method: constants.GET_HISTORY_SPOT_ORDERS.method,
			url: constants.GET_HISTORY_SPOT_ORDERS.url,
			data: {
				endTime,
				page: 1,
				rows: 10,
				startTime,
			},
			headers: {
				'access-control-allow-credentials': true,
				'Access-Control-Allow-Origin': '*',
				'content-type': 'application/json;charset=UTF-8',
				// c2ctype: 'c2c_merchant',
				clienttype: 'web',
				cookie: requestHeader.cookie,
				csrftoken: requestHeader.csrftoken,
				'device-info': requestHeader.deviceInfo,
				'user-agent': requestHeader.userAgent,
			},
		};
	} else if (prefix === 'p2p_BP') {
		const { amount, asset, fiat, tradeType, payMethod } = additionals;
		const urlStr = `?amount=${amount}&crypto_currency_code=${asset}&currency_code=${fiat}&type=${tradeType}&country_code=RU&page=1&limit=40`;
		let variableStr = '';
		if (payMethod !== '') {
			if (
				payMethod === 'QIWI' ||
				payMethod === 'USDT' ||
				payMethod === 'BTC' ||
				payMethod === 'ETH'
			)
				variableStr = `&payment_method_code=${payMethod}`;
			else variableStr = `&payment_method_bank_code=${payMethod}`;
		}
		objParams.prefix = 'BP_API';
		objParams.config = {
			withCredentials: true,
			method: constants.GET_P2P_ORDERS.method,
			url: constants.GET_P2P_ORDERS.url + urlStr + variableStr,
			data: null,
			headers: {
				Accept: 'application/json',
				'X-Access-Token': apiKeys.secretKey,
			},
		};
	} else if (prefix === 'advs_BP') {
	} else if (prefix === 'otc_PX') {
		objParams.prefix = 'PX';
		objParams.config = {
			withCredentials: true,
			method: constants.GET_MERCHANT_ORDERS.method,
			url: constants.GET_MERCHANT_ORDERS.url,
			data: {
				page: 1,
				rows: 20,
				endDate: endTime,
				startDate: startTime, // 60 days
			},
			headers: {
				'access-control-allow-credentials': true,
				'Access-Control-Allow-Origin': '*',
				'content-type': 'application/json;charset=UTF-8',
				c2ctype: 'c2c_merchant',
				clienttype: 'web',
				cookie: requestHeader.cookie,
				csrftoken: requestHeader.csrftoken,
				'device-info': requestHeader.deviceInfo,
				'user-agent': requestHeader.userAgent,
			},
		};
	} else if (prefix === 'otcDetails_PX') {
		objParams.prefix = 'PX';
		objParams.config = {
			method: constants.GET_MERCHANT_ORDER_DETAILS.method,
			url: constants.GET_MERCHANT_ORDER_DETAILS.url,
			data: { orderNo: additionals.order },
			headers: {
				'access-control-allow-credentials': true,
				'Access-Control-Allow-Origin': '*',
				'content-type': 'application/json;charset=UTF-8',
				clienttype: 'web',
				cookie: requestHeader.cookie,
				csrftoken: requestHeader.csrftoken,
				'device-info': requestHeader.deviceInfo,
				'user-agent': requestHeader.userAgent,
			},
		};
	} else if (prefix === 'balance_PX') {
		objParams.prefix = 'PX';
		objParams.config = {
			withCredentials: true,
			method:
				additionals.typeBalance === 'SPOT'
					? constants.GET_SPOT_BALANCE.method
					: constants.GET_P2P_BALANCE.method,
			url:
				additionals.typeBalance === 'SPOT'
					? constants.GET_SPOT_BALANCE.url
					: constants.GET_P2P_BALANCE.url,
			data: { needBtcValuation: true },
			headers: {
				'access-control-allow-credentials': true,
				'Access-Control-Allow-Origin': '*',
				'content-type': 'application/json;charset=UTF-8',
				c2ctype: 'c2c_merchant',
				clienttype: 'web',
				cookie: requestHeader.cookie,
				csrftoken: requestHeader.csrftoken,
				'device-info': requestHeader.deviceInfo,
				'user-agent': requestHeader.userAgent,
			},
		};
	} else if (prefix === 'active_PX') {
		objParams.prefix = 'PX';
		objParams.config = {
			withCredentials: true,
			method: constants.GET_ACTIVE_SPOT_ORDERS.method,
			url: constants.GET_ACTIVE_SPOT_ORDERS.url,
			data: {
				endTime,
				page: 1,
				rows: 10,
				startTime,
			},
			headers: {
				'access-control-allow-credentials': true,
				'Access-Control-Allow-Origin': '*',
				'content-type': 'application/json;charset=UTF-8',
				c2ctype: 'c2c_merchant',
				clienttype: 'web',
				cookie: requestHeader.cookie,
				csrftoken: requestHeader.csrftoken,
				'device-info': requestHeader.deviceInfo,
				'user-agent': requestHeader.userAgent,
			},
		};
	} else if (prefix === 'history_PX') {
		objParams.prefix = 'PX';
		objParams.config = {
			withCredentials: true,
			method: constants.GET_HISTORY_SPOT_ORDERS.method,
			url: constants.GET_HISTORY_SPOT_ORDERS.url,
			data: {
				endTime,
				page: 1,
				rows: 10,
				startTime,
			},
			headers: {
				'access-control-allow-credentials': true,
				'Access-Control-Allow-Origin': '*',
				'content-type': 'application/json;charset=UTF-8',
				c2ctype: 'c2c_merchant',
				clienttype: 'web',
				cookie: requestHeader.cookie,
				csrftoken: requestHeader.csrftoken,
				'device-info': requestHeader.deviceInfo,
				'user-agent': requestHeader.userAgent,
			},
		};
	} else if (prefix === 'p2p_PX') {
	} else if (prefix === 'advs_PX') {
	} else if (prefix === 'otc_MG') {
		const query_string = `endTime=${endTime}&orderDealStates=&page=1&startTime=${startTime}`;
		objParams.prefix = 'MG';
		objParams.config = {
			withCredentials: true,
			method: constants.GET_MERCHANT_ORDERS.method,
			url: `${constants.GET_MERCHANT_ORDERS.url}?${query_string}`,
			data: null,
			headers: {
				'access-control-allow-credentials': true,
				'Access-Control-Allow-Origin': '*',
				'content-type': 'application/json;charset=UTF-8',
				cookie: requestHeader.cookie,
				'user-agent': requestHeader.userAgent,
			},
		};
	} else if (prefix === 'otcDetails_MG') {
		const query_string = `${additionals.order}`;
		objParams.prefix = 'MG';
		objParams.config = {
			method: constants.GET_MERCHANT_ORDER_DETAILS.method,
			url: `${constants.GET_MERCHANT_ORDER_DETAILS.url}${query_string}`,
			data: null,
			headers: {
				'access-control-allow-credentials': true,
				'Access-Control-Allow-Origin': '*',
				'content-type': 'application/json;charset=UTF-8',
				cookie: requestHeader.cookie,
				'user-agent': requestHeader.userAgent,
			},
		};
	} else if (prefix === 'balance_MG') {
		objParams.prefix = 'MG';
		objParams.config = {
			withCredentials: true,
			method:
				additionals.typeBalance === 'SPOT'
					? constants.GET_SPOT_BALANCE.method
					: constants.GET_P2P_BALANCE.method,
			url:
				additionals.typeBalance === 'SPOT'
					? constants.GET_SPOT_BALANCE.url
					: constants.GET_P2P_BALANCE.url,
			data: additionals.typeBalance === 'SPOT' ? {} : null,
			headers: {
				'access-control-allow-credentials': true,
				'Access-Control-Allow-Origin': '*',
				'content-type': 'application/json;charset=UTF-8',
				// accept: '*/*',
				// 'accept-encoding': 'gzip, deflate, br',
				cookie: requestHeader.cookie,
				'user-agent': requestHeader.userAgent,
			},
		};
	} else if (prefix === 'balance_MG_API') {
		const query_string = `timestamp=${endTime}&recv_window=5000`;
		const signature = getSignature_MG(query_string, apiKeys.secretKey);
		const url_string = `${query_string}&signature=${signature}`;
		objParams.prefix = 'MG_API';
		objParams.config = {
			withCredentials: true,
			method: constants.GET_SPOT_BALANCE_BY_API.method,
			url: `${constants.GET_SPOT_BALANCE_BY_API.url}?${url_string}`,
			data: null,
			headers: {
				'Content-Type': 'application/json',
				'X-MEXC-APIKEY': `${apiKeys.publicKey}`,
			},
		};
	} else if (prefix === 'active_MG') {
		const query_string = `pageNum=1&pageSize=10&orderTypes=1`;
		objParams.prefix = 'MG';
		objParams.config = {
			withCredentials: true,
			method: constants.GET_ACTIVE_SPOT_ORDERS.method,
			url: `${constants.GET_ACTIVE_SPOT_ORDERS.url}?${query_string}`,
			data: null,
			headers: {
				'access-control-allow-credentials': true,
				'Access-Control-Allow-Origin': '*',
				'content-type': 'application/json;charset=UTF-8',
				// Accept: '*/*',
				// 'Accept-Encoding': 'gzip, deflate, br',
				cookie: requestHeader.cookie,
				'user-agent': requestHeader.userAgent,
			},
		};
	} else if (prefix === 'history_MG') {
		const query_string = `endTime=${endTime}&pageNum=1&pageSize=20&startTime=${startTime}`;
		objParams.prefix = 'MG';
		objParams.config = {
			withCredentials: true,
			method: constants.GET_HISTORY_SPOT_ORDERS.method,
			url: `${constants.GET_HISTORY_SPOT_ORDERS.url}?${query_string}`,
			data: null,
			headers: {
				'access-control-allow-credentials': true,
				'Access-Control-Allow-Origin': '*',
				'content-type': 'application/json;charset=UTF-8',
				// Accept: '*/*',
				// 'Accept-Encoding': 'gzip, deflate, br',
				cookie: requestHeader.cookie,
				'user-agent': requestHeader.userAgent,
			},
		};
	} else if (prefix === 'active_MG_API') {
		const symbol = additionals.symbol;
		const query_string = `symbol=${symbol}&timestamp=${endTime}&recv_window=5000`;
		const signature = getSignature_MG(query_string, apiKeys.secretKey);
		const url_string = `${query_string}&signature=${signature}`;
		objParams.prefix = 'MG_API';
		objParams.config = {
			withCredentials: true,
			method: constants.GET_ACTIVE_SPOT_ORDERS_BY_API.method,
			url: `${constants.GET_ACTIVE_SPOT_ORDERS_BY_API.url}?${query_string}&signature=${signature}`,
			data: null,
			headers: {
				'Content-Type': 'application/json',
				'X-MEXC-APIKEY': `${apiKeys.publicKey}`,
			},
		};
	} else if (prefix === 'history_MG_API') {
		const { symbol } = additionals;
		const query_string = `symbol=${symbol}&timestamp=${endTime}&recv_window=5000`;
		const signature = getSignature_MG(query_string, apiKeys.secretKey);
		const url_string = `${query_string}&signature=${signature}`;
		objParams.prefix = 'MG_API';
		objParams.config = {
			withCredentials: true,
			method: constants.GET_HISTORY_SPOT_ORDERS_BY_API.method,
			url: `${constants.GET_HISTORY_SPOT_ORDERS_BY_API.url}?${query_string}&signature=${signature}`,
			data: null,
			headers: {
				'Content-Type': 'application/json',
				'X-MEXC-APIKEY': `${apiKeys.publicKey}`,
			},
		};
	} else if (prefix === 'p2p_MG') {
	} else if (prefix === 'spot_tickers_MG_API') {
		const query_string = `timestamp=${endTime}&recv_window=5000`;
		const signature = getSignature_MG(query_string, apiKeys.secretKey);
		const url_string = `${query_string}&signature=${signature}`;
		objParams.typeMarket = additionals.typeMarket;
		objParams.prefix = 'MG_API';
		objParams.config = {
			withCredentials: true,
			method: constants.GET_ALL_TICKERS_SPOT_BY_API.method,
			url: `${constants.GET_ALL_TICKERS_SPOT_BY_API.url}?${url_string}`,
			data: null,
			headers: {
				'Content-Type': 'application/json',
				'X-MEXC-APIKEY': `${apiKeys.publicKey}`,
			},
		};
	} else if (prefix === 'fut_tickers_MG_API') {
		const query_string = `timestamp=${endTime}&recv_window=5000`;
		const signature = getSignature_MG(query_string, apiKeys.secretKey);
		const url_string = `${query_string}&signature=${signature}`;
		objParams.typeMarket = additionals.typeMarket;
		objParams.prefix = 'MG_API';
		objParams.config = {
			withCredentials: true,
			method: constants.GET_ALL_TICKERS_FUT_BY_API.method,
			url: `${constants.GET_ALL_TICKERS_FUT_BY_API.url}?${url_string}`,
			data: null,
			headers: {
				'Content-Type': 'application/json',
				'X-MEXC-APIKEY': `${apiKeys.publicKey}`,
			},
		};
	} else if (prefix === 'advs_MG') {
	} else if (prefix === 'otc_KC') {
		const query_string = `page=1&pageSize=20&lang=en_US`;
		objParams.prefix = 'KC';
		objParams.config = {
			withCredentials: true,
			method: constants.GET_MERCHANT_ORDERS.method,
			url: `${constants.GET_MERCHANT_ORDERS.url}?${query_string}`,
			data: null,
			headers: {
				'access-control-allow-credentials': true,
				'Access-Control-Allow-Origin': '*',
				'content-type': 'application/json;charset=UTF-8',
				cookie: requestHeader.cookie,
				'user-agent': requestHeader.userAgent,
			},
		};
	} else if (prefix === 'otcDetails_KC') {
		const query_string = `${additionals.order}`;
		objParams.prefix = 'KC';
		objParams.config = {
			method: constants.GET_MERCHANT_ORDER_DETAILS.method,
			url: `${constants.GET_MERCHANT_ORDER_DETAILS.url}${query_string}`,
			data: null,
			headers: {
				'access-control-allow-credentials': true,
				'Access-Control-Allow-Origin': '*',
				'content-type': 'application/json;charset=UTF-8',
				cookie: requestHeader.cookie,
				'user-agent': requestHeader.userAgent,
			},
		};
	} else if (prefix === 'balance_KC') {
		objParams.prefix = 'KC';
		objParams.config = {
			method: constants.GET_SPOT_BALANCE.method,
			url: `${constants.GET_SPOT_BALANCE.url}?type=DEPOSIT&lang=en_US`,
			data: null,
			headers: {
				'access-control-allow-credentials': true,
				'Access-Control-Allow-Origin': '*',
				'content-type': 'application/json;charset=UTF-8',
				cookie: requestHeader.cookie,
				'user-agent': requestHeader.userAgent,
			},
		};
	} else if (prefix === 'active_KC') {
		const query_string = `currentPage=1&pageSize=20&tradeType=TRADE&lang=en_US`;
		objParams.prefix = 'KC';
		objParams.config = {
			withCredentials: true,
			method: constants.GET_ACTIVE_SPOT_ORDERS.method,
			url: `${constants.GET_ACTIVE_SPOT_ORDERS.url}?${query_string}`,
			data: null,
			headers: {
				'access-control-allow-credentials': true,
				'Access-Control-Allow-Origin': '*',
				'content-type': 'application/json;charset=UTF-8',
				cookie: requestHeader.cookie,
				'user-agent': requestHeader.userAgent,
			},
		};
	} else if (prefix === 'history_KC') {
		const query_string = `currentPage=1&pageSize=20&start=${startTime}&end=${endTime}&tradeType=TRADE&lang=en_US`;
		objParams.prefix = 'KC';
		objParams.config = {
			withCredentials: true,
			method: constants.GET_HISTORY_SPOT_ORDERS.method,
			url: `${constants.GET_HISTORY_SPOT_ORDERS.url}?${query_string}`,
			data: null,
			headers: {
				'access-control-allow-credentials': true,
				'Access-Control-Allow-Origin': '*',
				'content-type': 'application/json;charset=UTF-8',
				cookie: requestHeader.cookie,
				'user-agent': requestHeader.userAgent,
			},
		};
	} else if (prefix === 'p2p_KC') {
	} else if (prefix === 'spot_tickers_KC_API') {
		const url = '/api/v1/market/allTickers';
		const method = constants.GET_ALL_TICKERS_SPOT_BY_API.method;
		const query_string = `${endTime}${method}${url}`;
		const signature = getSignature_KC(query_string, apiKeys.secretKey);
		const passPhrase = getSignature_KC('TCAe2e9Fyy', apiKeys.secretKey);
		objParams.typeMarket = additionals.typeMarket;
		objParams.prefix = 'KC_API';
		objParams.config = {
			withCredentials: true,
			method,
			url: constants.GET_ALL_TICKERS_SPOT_BY_API.url,
			data: null,
			headers: {
				'Content-Type': 'application/json',
				'KC-API-SIGN': signature,
				'KC-API-TIMESTAMP': endTime,
				'KC-API-KEY': apiKeys.publicKey,
				'KC-API-PASSPHRASE': passPhrase,
				'KC-API-KEY-VERSION': '2',
			},
		};
	} else if (prefix === 'fut_tickers_KC_API') {
		const url = '/api/v1/allTickers';
		const method = constants.GET_ALL_TICKERS_FUT_BY_API.method;
		const query_string = `${endTime}${method}${url}`;
		const signature = getSignature_KC(query_string, apiKeys.secretKey);
		const passPhrase = getSignature_KC('TCAe2e9Fyy', apiKeys.secretKey);
		objParams.typeMarket = additionals.typeMarket;
		objParams.prefix = 'KC_API';
		objParams.config = {
			withCredentials: true,
			method,
			url: constants.GET_ALL_TICKERS_FUT_BY_API.url,
			data: null,
			headers: {
				'Content-Type': 'application/json',
				'KC-API-SIGN': signature,
				'KC-API-TIMESTAMP': endTime,
				'KC-API-KEY': apiKeys.publicKey,
				'KC-API-PASSPHRASE': passPhrase,
				'KC-API-KEY-VERSION': '2',
			},
		};
	} else if (prefix === 'advs_KC') {
		const query_string = `status=PUTUP&page=1&pageSize=12&lang=en_US`;
		objParams.prefix = 'KC';
		objParams.config = {
			withCredentials: true,
			method: constants.GET_MERCHANT_ADVS.method,
			url: `${constants.GET_MERCHANT_ADVS.url}?${query_string}`,
			data: null,
			headers: {
				'access-control-allow-credentials': true,
				'Access-Control-Allow-Origin': '*',
				'content-type': 'application/json;charset=UTF-8',
				cookie: requestHeader.cookie,
				'user-agent': requestHeader.userAgent,
			},
		};
	} else if (prefix === 'otc_GT') {
		const tomorrow = new Date().getTime() + 60000 * 60 * 24 * 1;
		const monthAgo = tomorrow - 60000 * 60 * 24 * 60;
		const timeStart = new Date(monthAgo).toISOString().split('T')[0];
		const timeEnd = new Date(tomorrow).toISOString().split('T')[0];
		const formData = new FormData();
		formData.append('type', 'my_push_hisotry_list');
		formData.append('for_query', 1);
		formData.append('startTime', `${timeStart}`);
		formData.append('endTime', `${timeEnd}`);
		formData.append('curr_a', '');
		formData.append('curr_b', '');
		formData.append('action_type', '');
		formData.append('status_type', '');

		const formHeader = formData.getHeaders();
		objParams.prefix = 'GT';
		objParams.config = {
			// withCredentials: true,
			'content-type': 'application/x-www-form-urlencoded; charset=UTF-8',
			method: constants.GET_MERCHANT_ORDERS.method,
			url: constants.GET_MERCHANT_ORDERS.url,
			data: formData,
			headers: {
				...formHeader,
				cookie: requestHeader.cookie,
				csrftoken: requestHeader.csrftoken,
				'user-agent': requestHeader.userAgent,
			},
		};
	} else if (prefix === 'balance_GT') {
		objParams.prefix = 'GT';
		objParams.config = {
			// withCredentials: true,
			method: constants.GET_SPOT_BALANCE.method,
			url: constants.GET_SPOT_BALANCE.url,
			data: null,
			headers: {
				cookie: requestHeader.cookie,
				csrftoken: requestHeader.csrftoken,
				'user-agent': requestHeader.userAgent,
			},
		};
	} else if (prefix === 'active_GT') {
		const formData = new FormData();
		formData.append('order_status', 1);
		formData.append('order_type', 'normal');
		formData.append('startTime', '');
		formData.append('endTime', '');
		formData.append('curr_a', '');
		formData.append('curr_b', '');
		formData.append('limit', 1000);
		formData.append('offset', 0);

		const formHeader = formData.getHeaders();
		objParams.prefix = 'GT';
		objParams.config = {
			withCredentials: true,
			method: constants.GET_ACTIVE_SPOT_ORDERS.method,
			url: constants.GET_ACTIVE_SPOT_ORDERS.url,
			data: formData,
			headers: {
				...formHeader,
				// 'access-control-allow-credentials': true,
				// 'Access-Control-Allow-Origin': '*',
				// 'content-type': 'application/json;charset=UTF-8',
				cookie: requestHeader.cookie,
				csrftoken: requestHeader.csrftoken,
				'user-agent': requestHeader.userAgent,
			},
		};
	} else if (prefix === 'history_GT') {
		const { startTime, endTime } = params;
		// const reqStartTime = new Date(startTime).toISOString().split('T')[0];
		// const reqEndTime = new Date(endTime).toISOString().split('T')[0];
		const reqStartTime = '2023-12-11';
		const reqEndTime = '2024-03-17';

		const formData = new FormData();
		formData.append('order_status', 2);
		formData.append('order_type', 'normal');
		formData.append('startTime', `${reqStartTime}`);
		formData.append('endTime', `${reqEndTime}`);
		formData.append('curr_a', '');
		formData.append('curr_b', '');
		formData.append('limit', 1000);
		formData.append('offset', 0);

		const formHeader = formData.getHeaders();
		// const query_string = `page=1&type=history_order&all_orders=1&order_type=1`;
		objParams.prefix = 'GT';
		objParams.config = {
			withCredentials: true,
			method: constants.GET_HISTORY_SPOT_ORDERS.method,
			// url: `${constants.GET_HISTORY_SPOT_ORDERS.url}?${query_string}`,
			url: constants.GET_HISTORY_SPOT_ORDERS.url,
			// data: null,
			data: formData,
			headers: {
				...formHeader,
				// 'access-control-allow-credentials': true,
				// 'Access-Control-Allow-Origin': '*',
				// 'content-type': 'application/json;charset=UTF-8',
				cookie: requestHeader.cookie,
				csrftoken: requestHeader.csrftoken,
				'user-agent': requestHeader.userAgent,
			},
		};
	} else if (prefix === 'active_GT_API') {
		const baseURL = constants.GET_ACTIVE_SPOT_ORDERS_BY_API.url;
		const query_string = apiKeys.publicKey + baseURL + endTime;
		const signature = getSignature_GT(query_string, apiKeys.secretKey);
		objParams.prefix = 'GT_API';
		objParams.config = {
			withCredentials: true,
			method: constants.GET_ACTIVE_SPOT_ORDERS_BY_API.method,
			url: baseURL,
			data: null,
			headers: {
				// 'access-control-allow-credentials': true,
				// 'Access-Control-Allow-Origin': '*',
				// 'content-type': 'application/json;charset=UTF-8',
				Accept: 'application/json',
				'Content-Type': 'application/json',
				KEY: apiKeys.publicKey,
				Timestamp: endTime,
				SIGN: signature,
			},
		};
	} else if (prefix === 'history_GT_API') {
	} else if (prefix === 'p2p_GT') {
	} else if (prefix === 'spot_tickers_GT_API') {
		const baseURL = constants.GET_ALL_TICKERS_SPOT_BY_API.url;
		const query_string = apiKeys.publicKey + baseURL + endTime;
		const signature = getSignature_GT(query_string, apiKeys.secretKey);
		objParams.prefix = 'GT_API';
		objParams.config = {
			withCredentials: true,
			method: constants.GET_ALL_TICKERS_SPOT_BY_API.method,
			url: baseURL,
			data: null,
			headers: {
				Accept: 'application/json',
				'Content-Type': 'application/json',
				KEY: apiKeys.publicKey,
				Timestamp: endTime,
				SIGN: signature,
			},
		};
	} else if (prefix === 'fut_tickers_GT_API') {
		const baseURL = constants.GET_ALL_TICKERS_FUT_BY_API.url;
		const query_string = apiKeys.publicKey + baseURL + endTime;
		const signature = getSignature_GT(query_string, apiKeys.secretKey);
		objParams.typeMarket = additionals.typeMarket;
		objParams.typeMarket = additionals.typeMarket;
		objParams.prefix = 'GT_API';
		objParams.config = {
			withCredentials: true,
			method: constants.GET_ALL_TICKERS_FUT_BY_API.method,
			url: baseURL,
			data: null,
			headers: {
				Accept: 'application/json',
				'Content-Type': 'application/json',
				KEY: apiKeys.publicKey,
				Timestamp: endTime,
				SIGN: signature,
			},
		};
	} else if (prefix === 'advs_GT') {
		const formData = new FormData();
		formData.append('type', 'my_push_order_list');
		formData.append('currencyType', 'USDT');
		formData.append('curr_a', '');
		formData.append('action_type', '');

		const formHeader = formData.getHeaders();
		objParams.prefix = 'GT';
		objParams.config = {
			// withCredentials: true,
			method: constants.GET_MERCHANT_ADVS.method,
			url: constants.GET_MERCHANT_ADVS.url,
			data: formData,
			headers: {
				...formHeader,
				cookie: requestHeader.cookie,
				csrftoken: requestHeader.csrftoken,
				'user-agent': requestHeader.userAgent,
			},
		};
	} else if (prefix === 'otc_BG_API') {
		const method = constants.GET_MERCHANT_ORDERS_BY_API.method;
		const requestPath = constants.GET_MERCHANT_ORDERS_BY_API.url;
		const query_string = `?startTimestartTime=${startTime}&endTime=${endTime}&limit=1`;
		// const query_string = `?startTime=${startTime}&endTime=${endTime}&pageSize=20`;
		const final_string = `${endTime}${method}${requestPath}${query_string}`;
		const signParams = getSignature_BG(final_string, apiKeys);
		objParams.prefix = 'BG_API';
		objParams.config = {
			withCredentials: true,
			method,
			url: `${constants.BASE_URL}${requestPath}${query_string}`,
			// data: null, // data: {} - only POST requests
			headers: {
				'ACCESS-KEY': `${signParams.publicKey}`,
				'ACCESS-SIGN': `${signParams.signature}`,
				'ACCESS-TIMESTAMP': `${endTime}`,
				'ACCESS-PASSPHRASE': `${signParams.passPhrase}`,
				locale: 'en-US',
				'Content-Type': 'application/json',
			},
		};
	} else if (prefix === 'balance_BG_API') {
		const { typeBalance } = additionals;
		const cnst =
			typeBalance === 'SPOT'
				? constants.GET_SPOT_BALANCE_BY_API
				: constants.GET_P2P_BALANCE_BY_API;
		const method = cnst.method;
		const url = cnst.url;

		const query_string = `${endTime}${method}${url}`;
		const signParams = getSignature_BG(query_string, apiKeys);

		objParams.prefix = 'BG_API';
		objParams.config = {
			withCredentials: true,
			method,
			url: `${constants.BASE_URL}${url}`,
			// data: null, // data: {} - only POST requests
			headers: {
				'ACCESS-KEY': `${signParams.publicKey}`,
				'ACCESS-SIGN': `${signParams.signature}`,
				'ACCESS-TIMESTAMP': `${endTime}`,
				'ACCESS-PASSPHRASE': `${signParams.passPhrase}`,
				locale: 'en-US',
				'Content-Type': 'application/json',
			},
		};
	} else if (prefix === 'active_BG_API') {
		const method = constants.GET_ACTIVE_SPOT_ORDERS_BY_API.method;
		const requestPath = constants.GET_ACTIVE_SPOT_ORDERS_BY_API.url;
		const body = { symbol: '' };
		const bodyStr = JSON.stringify(body);
		const final_string = `${endTime}${method}${requestPath}${bodyStr}`;
		const signParams = getSignature_BG(final_string, apiKeys);
		// console.log('using signature: ' + final_string);

		objParams.prefix = 'BG_API';
		objParams.config = {
			withCredentials: true,
			method,
			url: `${constants.BASE_URL}${requestPath}`,
			data: body, // data: {} - only POST requests
			headers: {
				'ACCESS-KEY': `${signParams.publicKey}`,
				'ACCESS-SIGN': `${signParams.signature}`,
				'ACCESS-TIMESTAMP': `${endTime}`,
				'ACCESS-PASSPHRASE': `${signParams.passPhrase}`,
				locale: 'en-US',
				'Content-Type': 'application/json',
			},
		};
	} else if (prefix === 'history_BG_API') {
		// https://bitgetlimited.github.io/apidoc/en/spot/#get-order-history
		const method = constants.GET_HISTORY_SPOT_ORDERS_BY_API.method;
		const requestPath = constants.GET_HISTORY_SPOT_ORDERS_BY_API.url;
		const body = {
			symbol: `${additionals.symbol}`,
			// before: timestamp.toString(),
			// after: timeStart.toString(),
			// limit: '100',
		};
		const bodyStr = JSON.stringify(body);
		const final_string = `${endTime}${method}${requestPath}${bodyStr}`;
		const signParams = getSignature_BG(final_string, apiKeys);
		// console.log('using signature: ' + final_string);

		objParams.prefix = 'BG_API';
		objParams.config = {
			withCredentials: true,
			method,
			url: `${constants.BASE_URL}${requestPath}`,
			// data: {} - only POST requests
			data: body,
			headers: {
				'ACCESS-KEY': `${signParams.publicKey}`,
				'ACCESS-SIGN': `${signParams.signature}`,
				'ACCESS-TIMESTAMP': `${endTime}`,
				'ACCESS-PASSPHRASE': `${signParams.passPhrase}`,
				locale: 'en-US',
				'Content-Type': 'application/json',
			},
		};
	} else if (prefix === 'p2p_BG_API') {
		// https://www.bitget.com/api-doc/common/p2p/Get-P2P-Merchant-List
	} else if (prefix === 'spot_tickers_BG_API') {
		const method = constants.GET_ALL_TICKERS_SPOT_BY_API.method;
		const requestPath = constants.GET_ALL_TICKERS_SPOT_BY_API.url;
		const final_string = `${endTime}${method}${requestPath}`;
		const signParams = getSignature_BG(final_string, apiKeys);
		objParams.typeMarket = additionals.typeMarket;
		objParams.prefix = 'BG_API';
		objParams.config = {
			withCredentials: true,
			method,
			url: `${constants.BASE_URL}${requestPath}`,
			// data: {} - only POST requests
			data: null,
			headers: {
				locale: 'en-US',
				'Content-Type': 'application/json',
				'ACCESS-KEY': `${signParams.publicKey}`,
				'ACCESS-SIGN': `${signParams.signature}`,
				'ACCESS-TIMESTAMP': `${endTime}`,
				'ACCESS-PASSPHRASE': `${signParams.passPhrase}`,
			},
		};
	} else if (prefix === 'fut_tickers_BG_API') {
		const method = constants.GET_ALL_TICKERS_FUT_BY_API.method;
		const requestPath = constants.GET_ALL_TICKERS_FUT_BY_API.url;
		const query_string = 'productType=usdt-FUTURES';
		const final_string = `${endTime}${method}${requestPath}?${query_string}`;
		const signParams = getSignature_BG(final_string, apiKeys);
		objParams.typeMarket = additionals.typeMarket;
		objParams.prefix = 'BG_API';
		objParams.config = {
			withCredentials: true,
			method,
			url: `${constants.BASE_URL}${requestPath}?${query_string}`,
			data: null,
			headers: {
				locale: 'en-US',
				'Content-Type': 'application/json',
				'ACCESS-KEY': `${signParams.publicKey}`,
				'ACCESS-SIGN': `${signParams.signature}`,
				'ACCESS-TIMESTAMP': `${endTime}`,
				'ACCESS-PASSPHRASE': `${signParams.passPhrase}`,
			},
		};
	} else if (prefix === 'advs_BG_API') {
		const method = constants.GET_MERCHANT_ADVS_BY_API.method;
		const requestPath = constants.GET_MERCHANT_ADVS_BY_API.url;
		const query_string = `?startTime=${startTime -
			60000 * 60 * 24 * 90}&endTime=${endTime}`;
		const final_string = `${endTime}${method}${requestPath}${query_string}`;
		const signParams = getSignature_BG(final_string, apiKeys);
		objParams.prefix = 'BG_API';
		objParams.config = {
			withCredentials: true,
			method,
			url: `${constants.BASE_URL}${requestPath}${query_string}`,
			// data: null, // data: {} - only POST requests
			headers: {
				'ACCESS-KEY': `${signParams.publicKey}`,
				'ACCESS-SIGN': `${signParams.signature}`,
				'ACCESS-TIMESTAMP': `${endTime}`,
				'ACCESS-PASSPHRASE': `${signParams.passPhrase}`,
				locale: 'en-US',
				'Content-Type': 'application/json',
			},
		};
	} else if (prefix === 'otc_BX') {
		const rh = getFilteredRequestHeaderBX(
			additionals.typeRequest,
			requestHeader
		);
		const typeOrder = additionals.typeRequest === 'running' ? 1 : 4;
		const data =
			additionals.typeRequest === 'running'
				? {
						facilitator: 2,
						messageStatus: 0,
						pageId: 0,
						pageSize: 10,
						type: 1,
				  }
				: {
						facilitator: 2,
						pageId: 0,
						pageSize: 10,
						type: 4,
				  };
		objParams.prefix = 'BX';
		objParams.config = {
			withCredentials: true,
			method: constants.GET_MERCHANT_ORDERS.method,
			// url: `${constants.GET_MERCHANT_ORDERS.url}?type=${typeOrder}&facilitator=2&pageId=0&pageSize=10`,
			url: constants.GET_MERCHANT_ORDERS.url,
			// data: null,
			data,
			headers: {
				'access-control-allow-credentials': true,
				'Access-Control-Allow-Origin': '*',
				'content-type': 'application/json;charset=UTF-8',
				app_version: rh.appVersion,
				authorization: rh.authorization,
				device_id: rh.deviceId,
				lang: 'en',
				platformid: 30,
				sign: rh.sign,
				timestamp: rh.timestamp,
				timezone: 5,
				traceid: rh.traceId,
				'user-agent': rh.userAgent,
			},
		};
	} else if (prefix === 'otcDetails_BX') {
		objParams.prefix = 'BX';
		objParams.config = {
			method: constants.GET_MERCHANT_ORDER_DETAILS.method,
			url: constants.GET_MERCHANT_ORDER_DETAILS.url,
			data: null,
			headers: {},
		};
	} else if (prefix === 'balance_BX') {
		const rh = getFilteredRequestHeaderBX('balances', requestHeader);
		objParams.prefix = 'BX';
		objParams.config = {
			withCredentials: true,
			method: constants.GET_SPOT_BALANCE.method,
			url: constants.GET_SPOT_BALANCE.url,
			data: null,
			headers: {
				'access-control-allow-credentials': true,
				'Access-Control-Allow-Origin': '*',
				'content-type': 'application/json;charset=UTF-8',
				app_version: rh.appVersion,
				authorization: rh.authorization,
				device_id: rh.deviceId,
				lang: 'en',
				platformid: 30,
				sign: rh.sign,
				timestamp: rh.timestamp,
				timezone: 5,
				traceid: rh.traceId,
				'user-agent': rh.userAgent,
			},
		};
	} else if (prefix === 'balance_BX_API') {
		const query_string = `timestamp=${endTime}`;
		const signature = getSignature_BX(query_string, apiKeys.secretKey);
		objParams.prefix = 'BX_API';
		objParams.config = {
			withCredentials: true,
			method: constants.GET_SPOT_BALANCE_BY_API.method,
			url: `${constants.GET_SPOT_BALANCE_BY_API.url}?${query_string}&signature=${signature}`,
			data: null,
			headers: {
				'X-BX-APIKEY': apiKeys.publicKey,
			},
		};
	} else if (prefix === 'active_BX_API') {
		const query_string = `symbol=BTC-USDT&recvWindow=0&timestamp=${endTime}`;
		const signature = getSignature_BX(query_string, apiKeys.secretKey);
		objParams.prefix = 'BX_API';
		objParams.config = {
			withCredentials: true,
			method: constants.GET_ACTIVE_SPOT_ORDERS_BY_API.method,
			url: `${constants.GET_ACTIVE_SPOT_ORDERS_BY_API.url}?${query_string}&signature=${signature}`,
			data: null,
			headers: {
				'X-BX-APIKEY': apiKeys.publicKey,
			},
		};
	} else if (prefix === 'history_BX_API') {
		const query_string = `symbol=BTC-USDT&recvWindow=0&timestamp=${endTime}&pageIndex=0&pageSize=100`;
		const signature = getSignature_BX(query_string, apiKeys.secretKey);
		objParams.prefix = 'BX_API';
		objParams.config = {
			withCredentials: true,
			method: constants.GET_HISTORY_SPOT_ORDERS_BY_API.method,
			url: `${constants.GET_HISTORY_SPOT_ORDERS_BY_API.url}?${query_string}&signature=${signature}`,
			data: null,
			headers: {
				'X-BX-APIKEY': apiKeys.publicKey,
			},
		};
	} else if (prefix === 'p2p_BX') {
	} else if (prefix === 'spot_tickers_BX_API') {
		const query_string = `timestamp=${endTime}`;
		const signature = getSignature_BX(query_string, apiKeys.secretKey);
		objParams.typeMarket = additionals.typeMarket;
		objParams.prefix = 'BX_API';
		objParams.config = {
			withCredentials: true,
			method: constants.GET_ALL_TICKERS_SPOT_BY_API.method,
			url: `${constants.GET_ALL_TICKERS_SPOT_BY_API.url}?${query_string}&signature=${signature}`,
			data: null,
			headers: {
				'X-BX-APIKEY': apiKeys.publicKey,
			},
		};
	} else if (prefix === 'fut_tickers_BX_API') {
		const query_string = `timestamp=${endTime}`;
		const signature = getSignature_BX(query_string, apiKeys.secretKey);
		objParams.typeMarket = additionals.typeMarket;
		objParams.prefix = 'BX_API';
		objParams.config = {
			withCredentials: true,
			method: constants.GET_ALL_TICKERS_FUT_BY_API.method,
			url: `${constants.GET_ALL_TICKERS_FUT_BY_API.url}?${query_string}&signature=${signature}`,
			data: null,
			headers: {
				'X-BX-APIKEY': apiKeys.publicKey,
			},
		};
	} else if (prefix === 'advs_BX') {
	} else if (prefix === 'otc_CX_API') {
		const query_string = `offset=0&limit=20&timestamp=${endTime}`;
		// const query_string = `offset=0&limit=100&timestamp=${endTime}`;
		const signature = getSignature_CX(query_string, apiKeys.secretKey);
		objParams.prefix = 'CX_API';
		objParams.config = {
			withCredentials: true,
			method: constants.GET_MERCHANT_ORDERS_BY_API.method,
			url: `${constants.GET_MERCHANT_ORDERS_BY_API.url}?${query_string}&signature=${signature}`,
			// url: `https://api.commex.com/api/v1/c2c/order-match/list-order-history?offset=0&limit=0`,
			data: null,
			headers: {
				Accept: 'application/json',
				'X-MBX-APIKEY': apiKeys.publicKey,
			},
		};
	} else if (prefix === 'otc_CX') {
		objParams.prefix = 'CX';
		objParams.config = {
			withCredentials: true,
			method: constants.GET_MERCHANT_ORDERS.method,
			url: constants.GET_MERCHANT_ORDERS.url,
			data: {
				page: 1,
				rows: 20,
				endDate: endTime,
				startDate: startTime, // 60 days
			},
			headers: {
				'access-control-allow-credentials': true,
				'Access-Control-Allow-Origin': '*',
				'content-type': 'application/json;charset=UTF-8',
				c2ctype: 'c2c_merchant',
				clienttype: 'web',
				cookie: requestHeader.cookie,
				csrftoken: requestHeader.csrftoken,
				'device-info': requestHeader.deviceInfo,
				'user-agent': requestHeader.userAgent,
			},
		};
	} else if (prefix === 'otcDetails_CX') {
		objParams.prefix = 'CX';
		objParams.config = {
			method: constants.GET_MERCHANT_ORDER_DETAILS.method,
			url: constants.GET_MERCHANT_ORDER_DETAILS.url,
			data: { orderNo: additionals.order },
			headers: {
				'access-control-allow-credentials': true,
				'Access-Control-Allow-Origin': '*',
				'content-type': 'application/json;charset=UTF-8',
				clienttype: 'web',
				cookie: requestHeader.cookie,
				csrftoken: requestHeader.csrftoken,
				'device-info': requestHeader.deviceInfo,
				'user-agent': requestHeader.userAgent,
			},
		};
	} else if (prefix === 'balance_CX') {
		objParams.prefix = 'CX';
		objParams.config = {
			withCredentials: true,
			method:
				additionals.typeBalance === 'SPOT'
					? constants.GET_SPOT_BALANCE.method
					: constants.GET_P2P_BALANCE.method,
			url:
				additionals.typeBalance === 'SPOT'
					? constants.GET_SPOT_BALANCE.url
					: constants.GET_P2P_BALANCE.url,
			data: { needBtcValuation: true },
			headers: {
				'access-control-allow-credentials': true,
				'Access-Control-Allow-Origin': '*',
				'content-type': 'application/json;charset=UTF-8',
				c2ctype: 'c2c_merchant',
				clienttype: 'web',
				cookie: requestHeader.cookie,
				csrftoken: requestHeader.csrftoken,
				'device-info': requestHeader.deviceInfo,
				'user-agent': requestHeader.userAgent,
			},
		};
	} else if (prefix === 'active_CX') {
		objParams.prefix = 'CX';
		objParams.config = {
			withCredentials: true,
			method: constants.GET_ACTIVE_SPOT_ORDERS.method,
			url: constants.GET_ACTIVE_SPOT_ORDERS.url,
			data: {},
			headers: {
				'access-control-allow-credentials': true,
				'Access-Control-Allow-Origin': '*',
				'content-type': 'application/json;charset=UTF-8',
				// c2ctype: 'c2c_merchant',
				clienttype: 'web',
				cookie: requestHeader.cookie,
				csrftoken: requestHeader.csrftoken,
				'device-info': requestHeader.deviceInfo,
				'user-agent': requestHeader.userAgent,
			},
		};
	} else if (prefix === 'history_CX') {
		objParams.prefix = 'CX';
		objParams.config = {
			withCredentials: true,
			method: constants.GET_HISTORY_SPOT_ORDERS.method,
			url: constants.GET_HISTORY_SPOT_ORDERS.url,
			data: {
				endTime,
				page: 1,
				rows: 10,
				startTime,
			},
			headers: {
				'access-control-allow-credentials': true,
				'Access-Control-Allow-Origin': '*',
				'content-type': 'application/json;charset=UTF-8',
				// c2ctype: 'c2c_merchant',
				clienttype: 'web',
				cookie: requestHeader.cookie,
				csrftoken: requestHeader.csrftoken,
				'device-info': requestHeader.deviceInfo,
				'user-agent': requestHeader.userAgent,
			},
		};
	} else if (prefix === 'p2p_CX') {
	} else if (prefix === 'advs_CX') {
	} else if (prefix === 'balance_XG_API') {
		const baseURL = constants.GET_SPOT_BALANCE_BY_API.url;
		const query_string = apiKeys.publicKey + baseURL + endTime;
		const signature = getSignature_MG(query_string, apiKeys.secretKey);
		objParams.prefix = 'XG_API';
		objParams.config = {
			withCredentials: true,
			method: constants.GET_SPOT_BALANCE_BY_API.method,
			url: baseURL,
			data: null,
			headers: {
				'Content-Type': 'application/json',
				'X-API-KEY': apiKeys.publicKey,
				'X-API-NONCE': endTime,
				'X-API-SIGN': signature,
			},
		};
	} else if (prefix === 'active_XG_API') {
		const baseURL = constants.GET_ACTIVE_SPOT_ORDERS_BY_API.url;
		const query_string = apiKeys.publicKey + baseURL + endTime;
		const signature = getSignature_XG(query_string, apiKeys.secretKey);
		objParams.prefix = 'XG_API';
		objParams.config = {
			withCredentials: true,
			method: constants.GET_ACTIVE_SPOT_ORDERS_BY_API.method,
			url: baseURL,
			data: {
				status: 'active',
				limit: 500,
				skip: 0,
			},
			headers: {
				'Content-Type': 'application/json',
				'X-API-KEY': apiKeys.publicKey,
				'X-API-NONCE': endTime,
				'X-API-SIGN': signature,
			},
		};
	} else if (prefix === 'history_XG_API') {
		const baseURL = constants.GET_HISTORY_SPOT_ORDERS_BY_API.url;
		const query_string = apiKeys.publicKey + baseURL + endTime;
		const signature = getSignature_XG(query_string, apiKeys.secretKey);
		objParams.prefix = 'XG_API';
		objParams.config = {
			withCredentials: true,
			method: constants.GET_HISTORY_SPOT_ORDERS_BY_API.method,
			url: baseURL,
			data: {
				limit: 500,
				skip: 0,
			},
			headers: {
				'Content-Type': 'application/json',
				'X-API-KEY': apiKeys.publicKey,
				'X-API-NONCE': endTime,
				'X-API-SIGN': signature,
			},
		};
	} else if (prefix === 'otc_XG') {
		objParams.prefix = 'XG';
		objParams.config = {
			withCredentials: true,
			method: constants.GET_MERCHANT_ORDERS.method,
			url: constants.GET_MERCHANT_ORDERS.url,
			data: null,
			headers: {
				'access-control-allow-credentials': true,
				'Access-Control-Allow-Origin': '*',
				'content-type': 'application/json;charset=UTF-8',
				cookie: requestHeader.cookie,
				'user-agent': requestHeader.userAgent,
			},
		};
	} else if (prefix === 'otc_XG_API') {
		const baseURL = constants.GET_MERCHANT_ORDERS_BY_API.url;
		const query_string = apiKeys.publicKey + `${baseURL}` + endTime;
		const signature = getSignature_XG(query_string, apiKeys.secretKey);
		objParams.prefix = 'XG_API';
		objParams.config = {
			withCredentials: true,
			method: constants.GET_MERCHANT_ORDERS_BY_API.method,
			url: `${baseURL}?&limit=25&skip=0`,
			data: null,
			headers: {
				'Content-Type': 'application/json',
				'X-API-KEY': apiKeys.publicKey,
				'X-API-NONCE': endTime,
				'X-API-SIGN': signature,
			},
		};
	} else if (prefix === 'spot_tickers_XG_API') {
		const baseURL = constants.GET_ALL_TICKERS_SPOT_BY_API.url;
		const query_string = apiKeys.publicKey + baseURL + endTime;
		const signature = getSignature_XG(query_string, apiKeys.secretKey);
		objParams.typeMarket = additionals.typeMarket;
		objParams.prefix = 'XG_API';
		objParams.config = {
			withCredentials: true,
			method: constants.GET_ALL_TICKERS_SPOT_BY_API.method,
			url: baseURL,
			data: null,
			headers: {
				'Content-Type': 'application/json',
				'X-API-KEY': apiKeys.publicKey,
				'X-API-NONCE': endTime,
				'X-API-SIGN': signature,
			},
		};
	} else if (prefix === 'fut_tickers_XG_API') {
	} else if (prefix === 'balance_CN_API') {
		const { method, url } = constants.GET_SPOT_BALANCE_BY_API;
		const query_string = method + '/v2/assets/spot/balance' + endTime;
		const signature = getSignature_CN(query_string, apiKeys.secretKey);
		objParams.prefix = 'CN_API';
		objParams.config = {
			withCredentials: true,
			method,
			url,
			data: null,
			headers: {
				'X-COINEX-KEY': apiKeys.publicKey,
				'X-COINEX-SIGN': signature,
				'X-COINEX-TIMESTAMP': endTime,
			},
		};
	} else if (prefix === 'otc_CN') {
		objParams.prefix = 'CN';
		objParams.config = {
			withCredentials: true,
			// method: 'GET',
			// url: 'https://www.coinex.com/res/p2p/order/active_count',
			// data: null,
			method: constants.GET_MERCHANT_ORDERS.method,
			url: constants.GET_MERCHANT_ORDERS.url,
			data: {
				statuses: [
					'FINISHED',
					'CANCELED',
					'CREATED',
					'CONFIRMED',
					'PAID',
					'TO_FINISH',
				],
				page: 1,
				limit: 10,
			},
			headers: {
				'access-control-allow-credentials': true,
				'Access-Control-Allow-Origin': '*',
				'content-type': 'application/json;charset=UTF-8',
				cookie: requestHeader.cookie,
				authorization: requestHeader.authorization,
				'user-agent': requestHeader.userAgent,
			},
		};
	} else if (prefix === 'spot_tickers_CN_API') {
		const { method, url } = constants.GET_ALL_TICKERS_SPOT_BY_API;
		const query_string = method + '/v2/spot/ticker' + endTime;
		const signature = getSignature_CN(query_string, apiKeys.secretKey);
		objParams.typeMarket = additionals.typeMarket;
		objParams.prefix = 'CN_API';
		objParams.config = {
			withCredentials: true,
			method,
			url,
			data: null,
			headers: {
				'X-COINEX-KEY': apiKeys.publicKey,
				'X-COINEX-SIGN': signature,
				'X-COINEX-TIMESTAMP': endTime,
			},
		};
	} else if (prefix === 'fut_tickers_CN_API') {
		const { method, url } = constants.GET_ALL_TICKERS_FUT_BY_API;
		const query_string = method + '/v2/futures/ticker' + endTime;
		const signature = getSignature_CN(query_string, apiKeys.secretKey);
		objParams.typeMarket = additionals.typeMarket;
		objParams.prefix = 'CN_API';
		objParams.config = {
			withCredentials: true,
			method,
			url,
			data: null,
			headers: {
				'X-COINEX-KEY': apiKeys.publicKey,
				'X-COINEX-SIGN': signature,
				'X-COINEX-TIMESTAMP': endTime,
			},
		};
	} else if (prefix === 'balance_BM_API') {
		const { method, url } = constants.GET_SPOT_BALANCE_BY_API;
		// https://developer-pro.bitmart.com/en/quick/#2-simple-api-example-3
		// const message = `${timestamp}#${API_MEMO}#${body}`;
		const API_MEMO = 'P2P-Trading'; // from field "Memo" when creating api
		const body = '';
		const query_string = `${endTime}#${API_MEMO}#${body}`;
		const signature = getSignature_BM(query_string, apiKeys.secretKey);
		objParams.prefix = 'BM_API';
		objParams.config = {
			withCredentials: true,
			method,
			url,
			data: null,
			headers: {
				// 'Content-Type': 'application/json;charset=UTF-8',
				'X-BM-KEY': apiKeys.publicKey,
				'X-BM-SIGN': signature,
				'X-BM-TIMESTAMP': endTime,
			},
		};
	} else if (prefix === 'otc_BM') {
		objParams.prefix = 'BM';
		objParams.config = {
			withCredentials: true,
			method: constants.GET_MERCHANT_ORDERS.method,
			url: constants.GET_MERCHANT_ORDERS.url,
			data: {
				pageSize: 10,
				pageIndex: 1,
				orderQueryStatus: additionals.typeOrders,
			},
			headers: {
				'access-control-allow-credentials': true,
				'Access-Control-Allow-Origin': '*',
				'content-type': 'application/json;charset=UTF-8',
				cookie: requestHeader.cookie,
				'user-agent': requestHeader.userAgent,
				// "x-bm-client": requestHeader.x_bm_client,
				'x-bm-client': 'WEB',
			},
		};
	} else if (prefix === 'otcDetails_BM') {
		objParams.prefix = 'BM';
		objParams.config = {
			withCredentials: true,
			method: constants.GET_MERCHANT_ORDER_DETAILS.method,
			url: constants.GET_MERCHANT_ORDER_DETAILS.url,
			data: {
				orderId: additionals.order,
			},
			headers: {
				'access-control-allow-credentials': true,
				'Access-Control-Allow-Origin': '*',
				'content-type': 'application/json;charset=UTF-8',
				cookie: requestHeader.cookie,
				'user-agent': requestHeader.userAgent,
				// "x-bm-client": requestHeader.x_bm_client,
				'x-bm-client': 'WEB',
			},
		};
	} else if (prefix === 'spot_tickers_BM_API') {
		const { method, url } = constants.GET_ALL_TICKERS_SPOT_BY_API;
		const API_MEMO = 'P2P-Trading'; // from field "Memo" when creating api
		const body = '';
		const query_string = `${endTime}#${API_MEMO}#${body}`;
		const signature = getSignature_BM(query_string, apiKeys.secretKey);
		objParams.typeMarket = additionals.typeMarket;
		objParams.prefix = 'BM_API';
		objParams.config = {
			withCredentials: true,
			method,
			url,
			data: null,
			headers: {
				// 'Content-Type': 'application/json;charset=UTF-8',
				'X-BM-KEY': apiKeys.publicKey,
				'X-BM-SIGN': signature,
				'X-BM-TIMESTAMP': endTime,
			},
		};
	} else if (prefix === 'fut_tickers_BM_API') {
		const { method, url } = constants.GET_ALL_TICKERS_FUT_BY_API;
		const API_MEMO = 'P2P-Trading'; // from field "Memo" when creating api
		const body = '';
		const query_string = `${endTime}#${API_MEMO}#${body}`;
		const signature = getSignature_BM(query_string, apiKeys.secretKey);
		objParams.typeMarket = additionals.typeMarket;
		objParams.prefix = 'BM_API';
		objParams.config = {
			withCredentials: true,
			method,
			url,
			data: null,
			headers: {
				// 'Content-Type': 'application/json;charset=UTF-8',
				'X-BM-KEY': apiKeys.publicKey,
				'X-BM-SIGN': signature,
				'X-BM-TIMESTAMP': endTime,
			},
		};
	} else if (prefix === 'advs_BM') {
		objParams.prefix = 'BM';
		objParams.config = {
			withCredentials: true,
			method: constants.GET_MERCHANT_ADVS.method,
			url: constants.GET_MERCHANT_ADVS.url,
			data: { side: '', adQueryStatus: '' },
			headers: {
				'access-control-allow-credentials': true,
				'Access-Control-Allow-Origin': '*',
				'content-type': 'application/json;charset=UTF-8',
				cookie: requestHeader.cookie,
				'user-agent': requestHeader.userAgent,
				'x-bm-client': 'WEB',
			},
		};
	} else if (prefix === 'balance_AX_API') {
		objParams.prefix = 'AX_API';
		objParams.config = {
			withCredentials: true,
			method: constants.GET_BALANCES_BY_API.method,
			url: constants.GET_BALANCES_BY_API.url,
			data: null,
			headers: {
				Authorization: `Bearer ${apiKeys.secretKey}`,
			},
		};
	} else if (prefix === 'otc_AX_API') {
		objParams.prefix = 'AX_API';
		objParams.config = {
			withCredentials: true,
			method: constants.GET_MERCHANT_ORDERS_BY_API.method,
			url: constants.GET_MERCHANT_ORDERS_BY_API.url,
			data: null,
			headers: {
				Authorization: `Bearer ${apiKeys.secretKey}`,
			},
		};
	} else if (prefix === 'otcDetails_AX') {
		const { method, url } = constants.GET_MERCHANT_ORDER_DETAILS_BY_API;
		objParams.prefix = 'AX_API';
		objParams.config = {
			withCredentials: true,
			method,
			url: `${url}${additionals.order}`,
			data: null,
			headers: {
				Authorization: `Bearer ${apiKeys.secretKey}`,
			},
		};
	} else if (prefix === 'active_AX_API') {
		objParams.prefix = 'AX_API';
		objParams.config = {
			withCredentials: true,
			method: constants.GET_ACTIVE_SPOT_ORDERS_BY_API.method,
			url: constants.GET_ACTIVE_SPOT_ORDERS_BY_API.url,
			data: null,
			headers: {
				Authorization: `Bearer ${apiKeys.secretKey}`,
			},
		};
	} else if (prefix === 'history_AX_API') {
		objParams.prefix = 'AX_API';
		objParams.config = {
			withCredentials: true,
			method: constants.GET_HISTORY_SPOT_ORDERS_BY_API.method,
			url: constants.GET_HISTORY_SPOT_ORDERS_BY_API.url,
			data: null,
			headers: {
				Authorization: `Bearer ${apiKeys.secretKey}`,
			},
		};
	} else if (prefix === 'balance_CM') {
		objParams.prefix = 'CM';
		objParams.config = {
			withCredentials: true,
			method: constants.GET_P2P_BALANCE.method,
			url: constants.GET_P2P_BALANCE.url,
			data: null,
			headers: {
				'Content-Type': 'application/json',
				authorization: requestHeader.authorization,
				'user-agent': requestHeader.userAgent,
			},
		};
	} else if (prefix === 'balance_CM_API') {
		const query_string = '';
		const secretKey = 'bb4a1a09a8b34d6fc3d70e20b3dc652050034987';
		const user_id = '2131b9ff-f419-4601-9c03-e008f8cf8569';
		// const signature = getSignature_CM(query_string, apiKeys.secretKey);
		const signature = getSignature_CM(query_string, secretKey);
		objParams.prefix = 'CM_API';
		objParams.config = {
			withCredentials: true,
			method: constants.GET_SPOT_BALANCE_BY_API.method,
			url: constants.GET_SPOT_BALANCE_BY_API.url,
			// url: 'https://api.cryptomus.com/v1/exchange/market/trades/BTC_USDT',
			data: null,
			// data: {},
			headers: {
				user_id: apiKeys.publicKey, // user UUID
				sign: signature,
				'Content-Type': 'application/json',
			},
		};
	} else if (prefix === 'otc_CM') {
		objParams.prefix = 'CM';
		objParams.config = {
			withCredentials: true,
			method: constants.GET_MERCHANT_ORDERS.method,
			url: constants.GET_MERCHANT_ORDERS.url,
			data: { page: 1, type: '', currency_code: '', status: '' },
			headers: {
				'access-control-allow-credentials': true,
				'Access-Control-Allow-Origin': '*',
				'content-type': 'application/json;charset=UTF-8',
				authorization: requestHeader.authorization,
				'user-agent': requestHeader.userAgent,
			},
		};
	} else if (prefix === 'balance_XT') {
		objParams.prefix = 'XT';
		objParams.config = {
			withCredentials: true,
			method: constants.GET_SPOT_BALANCE.method,
			url: constants.GET_SPOT_BALANCE.url,
			data: null,
			headers: {
				'Content-Type': 'application/json',
				authorization: `Bearer ${requestHeader.token}`,
				'user-agent': requestHeader.userAgent,
			},
		};
	} else if (prefix === 'otc_XT') {
		const formData = new FormData();
		formData.append('market', '');
		formData.append('status', '100');
		formData.append('pageNo', '1');
		formData.append('pageSize', '10');

		const formHeader = formData.getHeaders();
		objParams.prefix = 'XT';
		objParams.config = {
			withCredentials: true,
			method: constants.GET_MERCHANT_ORDERS.method,
			url: constants.GET_MERCHANT_ORDERS.url,
			data: formData,
			headers: {
				...formHeader,
				'Content-Type': 'application/json',
				authorization: `Bearer ${requestHeader.token}`,
				'user-agent': requestHeader.userAgent,
			},
		};
	} else if (prefix === 'spot_tickers_XT_API') {
		const method = constants.GET_ALL_TICKERS_SPOT_BY_API.method 
		const path = "/v4/public/ticker"
		const query_string = `validate-algorithms=HmacSHA256&validate-appkey=${
			apiKeys.publicKey
		}&validate-recvwindow=60000&validate-timestamp=${endTime}#${method}#${path}#`;
		const signature = getSignature_XT(query_string, apiKeys.secretKey);
		objParams.typeMarket = additionals.typeMarket;
		objParams.prefix = 'XT_API';
		objParams.config = {
			withCredentials: true,
			method,
			url: constants.GET_ALL_TICKERS_SPOT_BY_API.url,
			data: null,
			headers: {
				'accept': '*/*',
    		'Content-Type': 'application/json', 
    		'validate-algorithms': 'HmacSHA256' ,
    		'validate-appkey': apiKeys.publicKey,
    		'validate-recvwindow': '60000',
    		'validate-timestamp': endTime,
    		'validate-signature': signature,
			},
		};
	} else if (prefix === 'fut_tickers_XT_API') {
		const method = constants.GET_ALL_TICKERS_FUT_BY_API.method 
		const path = "/future/market/v1/public/q/agg-tickers"
		const query_string = `validate-algorithms=HmacSHA256&validate-appkey=${
			apiKeys.publicKey
		}&validate-recvwindow=60000&validate-timestamp=${endTime}#${method}#${path}#`;
		const signature = getSignature_XT(query_string, apiKeys.secretKey);
		objParams.typeMarket = additionals.typeMarket;
		objParams.prefix = 'XT_API';
		objParams.config = {
			withCredentials: true,
			method,
			url: constants.GET_ALL_TICKERS_FUT_BY_API.url,
			data: null,
			headers: {
				'accept': '*/*',
    		'Content-Type': 'application/json', 
    		'validate-algorithms': 'HmacSHA256' ,
    		'validate-appkey': apiKeys.publicKey,
    		'validate-recvwindow': '60000',
    		'validate-timestamp': endTime,
    		'validate-signature': signature,
			},
		};
	}
	return objParams;
};

// получение массива merchant-ордеров COMPLETED
export const getOrdersCompleted = (arrOrders) => {
	const result =
		arrOrders.length === 0 || arrOrders[0] === null
			? []
			: arrOrders.filter((item) => {
					return item.statusProps.value === 'Completed';
			  });
	return result.map((item) => {
		// если GT, BG, BX, XG, CN - возвращаем детальный ордер, а не только orderId
		return arrOrders[0].exchange === 'GT' ||
			arrOrders[0].exchange === 'HB' ||
			arrOrders[0].exchange === 'BG' ||
			arrOrders[0].exchange === 'BX' ||
			arrOrders[0].exchange === 'XG' ||
			arrOrders[0].exchange === 'CN' ||
			arrOrders[0].exchange === 'CM' ||
			arrOrders[0].exchange === 'XT'
			? item
			: item.orderId;
	});
};

// групповое получение добавление otc-ордеров в БД
export const getANDinsertAllOtcOrders = async (params) => {
	const {
		userId,
		exchangeId,
		typeOrder,
		shortName,
		objParams,
		orders,
		arrTickers,
		arrPayTypes,
	} = params;
	let countOrder = 0;
	// проверка наличия ордера в БД
	for (let i = 0; i < orders.length; i++) {
		const orderId =
			shortName === 'GT' ||
			shortName === 'HB' ||
			shortName === 'BG' ||
			shortName === 'BX' ||
			shortName === 'XG' ||
			shortName === 'CN' ||
			shortName === 'CM' ||
			shortName === 'XT'
				? orders[i].orderId
				: orders[i];
		const result = await checkOrderInDB(
			userId,
			typeOrder,
			orderId,
			shortName
		);
		// Если ордера нет в БД
		if (result.isUnique) {
			if (
				shortName === 'GT' ||
				shortName === 'HB' ||
				shortName === 'BG' ||
				shortName === 'BX' ||
				shortName === 'XG' ||
				shortName === 'CN' ||
				shortName === 'CM' ||
				shortName === 'XT'
			) {
				objParams.additionals = {};
			} else {
				objParams.additionals.order = orders[i];
			}

			const objReqParams = getObjectRequestParams(objParams);
			// получение данных об ордере с биржи
			const orderDetails =
				shortName === 'GT' ||
				shortName === 'HB' ||
				shortName === 'BG' ||
				shortName === 'BX' ||
				shortName === 'XG' ||
				shortName === 'CN' ||
				shortName === 'CM' ||
				shortName === 'XT'
					? orders[i]
					: await getOrderDetails(
							objReqParams.config,
							shortName,
							typeOrder
					  );
			// если статус ордера "Completed" вставляем в БД
			const paramsNomalized = {
				userId,
				shortName,
				exchangeId,
				arrTickers,
				arrPayTypes,
				orderDetails,
			};
			const newOrder = getOrderDetailsNomalized(paramsNomalized);
			// если newOrder не пустой объект - сохраняем в БД
			if (Object.keys(newOrder).length !== 0) {
				await insertOrderToDB(typeOrder, newOrder);
				// shortName === 'XT' ? console.log(newOrder) : null;
				++countOrder;
			}
		}
	}

	// log print
	consoleProcessed(userId, shortName, orders, countOrder, typeOrder);
};

// start групповоой обработки otc-ордеров
export const startHandlerAllOtcOrders = async (params) => {
	const allOrders = [];
	const { userId, isInsertOrders, typeOrder } = params;
	const user = await User.findOne({ _id: userId });
	if (user) {
		const arrExchanges = await Exchange.find();
		const arrTickers = await Ticker.find();
		const arrPayTypes = await PayType.find();
		const arrOrderStatus = await OrderStatus.find();

		for (let i = 0; i < user.properties.length; i++) {
			if (user.properties[i].updateOrders) {
				let arrData = [];
				const exchangeId = user.properties[i].exchangeId;
				const objExchange = getObjExchangeById(arrExchanges, exchangeId);
				const shortName = objExchange.shortName;
				const objParams = {
					userId,
					prefix: '',
					apiKeys: user.properties[i].apiKeys,
					requestHeader: user.properties[i].requestHeader,
					constants: {},
					additionals: {},
				};
				if (shortName === 'BN') {
					objParams.prefix = `otc_${shortName}_API`;
					objParams.constants = CONSTANTS_BN;
					const arrSides = ['BUY', 'SELL'];
					let result_API = [];
					for (let j = 0; j < arrSides.length; j++) {
						objParams.additionals.side = arrSides[j];
						const objReqParamsAPI = getObjectRequestParams(objParams);
						const orders = await getMerchantOrders(objReqParamsAPI);
						result_API = result_API.concat(orders);
					}
					arrData = result_API;
				} else if (shortName === 'HB') {
					objParams.prefix = `otc_${shortName}`;
					objParams.constants = CONSTANTS_HB;
					const objReqParams = getObjectRequestParams(objParams);
					arrData = await getMerchantOrders(objReqParams);
				} else if (shortName === 'KX') {
					objParams.prefix = `otc_${shortName}`;
					objParams.constants = CONSTANTS_KX;
					const objReqParams = getObjectRequestParams(objParams);
					arrData = await getMerchantOrders(objReqParams);
				} else if (shortName === 'GX') {
					objParams.prefix = `otc_${shortName}`;
					objParams.constants = CONSTANTS_GX;
					const objReqParams = getObjectRequestParams(objParams);
					arrData = await getMerchantOrders(objReqParams);
				} else if (shortName === 'BT') {
					objParams.prefix = `otc_${shortName}`;
					objParams.constants = CONSTANTS_BT;
					const objReqParams = getObjectRequestParams(objParams);
					arrData = await getMerchantOrders(objReqParams);
				} else if (shortName === 'BP') {
					objParams.prefix = `otc_${shortName}`;
					objParams.constants = CONSTANTS_BP;
					const objReqParams = getObjectRequestParams(objParams);
					arrData = await getMerchantOrders(objReqParams);
				} else if (shortName === 'PX') {
					objParams.prefix = `otc_${shortName}`;
					objParams.constants = CONSTANTS_PX;
					const objReqParams = getObjectRequestParams(objParams);
					arrData = await getMerchantOrders(objReqParams);
				} else if (shortName === 'MG') {
					objParams.prefix = `otc_${shortName}`;
					objParams.constants = CONSTANTS_MG;
					const objReqParams = getObjectRequestParams(objParams);
					arrData = await getMerchantOrders(objReqParams);
				} else if (shortName === 'KC') {
					objParams.prefix = `otc_${shortName}`;
					objParams.constants = CONSTANTS_KC;
					const objReqParams = getObjectRequestParams(objParams);
					arrData = await getMerchantOrders(objReqParams);
				} else if (shortName === 'GT') {
					objParams.prefix = `otc_${shortName}`;
					objParams.constants = CONSTANTS_GT;
					const objReqParams = getObjectRequestParams(objParams);
					arrData = await getMerchantOrders(objReqParams);
				} else if (shortName === 'AX') {
					objParams.prefix = `otc_${shortName}_API`;
					objParams.constants = CONSTANTS_AX;
					const objReqParams = getObjectRequestParams(objParams);
					arrData = await getMerchantOrders(objReqParams);
				} else if (shortName === 'BG') {
					objParams.prefix = `otc_${shortName}_API`;
					objParams.constants = CONSTANTS_BG;
					const objReqParams = getObjectRequestParams(objParams);
					arrData = await getMerchantOrders(objReqParams);
				} else if (shortName === 'BX') {
					objParams.prefix = `otc_${shortName}`;
					objParams.constants = CONSTANTS_BX;
					const reqTypes = ['running', 'completed'];
					for (let i = 0; i < reqTypes.length; i++) {
						objParams.additionals.typeRequest = reqTypes[i];
						const objReqParams = getObjectRequestParams(objParams);
						const result = await getMerchantOrders(objReqParams);
						arrData = arrData.concat(result);
					}
				} else if (shortName === 'CX') {
					objParams.prefix = `otc_${shortName}_API`;
					objParams.constants = CONSTANTS_CX;
					const objReqParams = getObjectRequestParams(objParams);
					arrData = await getMerchantOrders(objReqParams);
				} else if (shortName === 'XG') {
					objParams.prefix = `otc_${shortName}`;
					objParams.constants = CONSTANTS_XG;
					const objReqParams = getObjectRequestParams(objParams);
					arrData = await getMerchantOrders(objReqParams);
				} else if (shortName === 'CN') {
					objParams.prefix = `otc_${shortName}`;
					objParams.constants = CONSTANTS_CN;
					const objReqParams = getObjectRequestParams(objParams);
					arrData = await getMerchantOrders(objReqParams);
				} else if (shortName === 'BM') {
					objParams.prefix = `otc_${shortName}`;
					objParams.constants = CONSTANTS_BM;
					const types = ['pendingAll', 'completeAll'];
					for (let i = 0; i < types.length; i++) {
						objParams.additionals.typeOrders = types[i];
						const objReqParams = getObjectRequestParams(objParams);
						const result = await getMerchantOrders(objReqParams);
						arrData = arrData.concat(result);
					}
				} else if (shortName === 'CM') {
					objParams.prefix = `otc_${shortName}`;
					objParams.constants = CONSTANTS_CM;
					const objReqParams = getObjectRequestParams(objParams);
					arrData = await getMerchantOrders(objReqParams);
				} else if (shortName === 'XT') {
					objParams.prefix = `otc_${shortName}`;
					objParams.constants = CONSTANTS_XT;
					const objReqParams = getObjectRequestParams(objParams);
					arrData = await getMerchantOrders(objReqParams);
				}
				// получение массива нормализованных ордеров
				const ordersNomalized =
					arrData.length === 0
						? []
						: getMerchantOrdersNomalized(
								arrData,
								{
									userId,
									exchangeId,
									prefix:
										shortName === 'BN' || shortName === 'CX'
											? `${shortName}_API`
											: shortName,
								},
								arrPayTypes,
								arrOrderStatus
						  );
				// получение массива отсортированных ордеров для BN
				const sortedOrders =
					shortName === 'BN'
						? getArraySortedByProp('ALL', ordersNomalized, 'dateOrder')
						: [];
				// добавление ордеров в общий массив
				allOrders.push({
					exchangeId,
					shortName,
					orders: shortName === 'BN' ? sortedOrders : ordersNomalized,
				});

				if (isInsertOrders) {
					const ordersCompleted = getOrdersCompleted(ordersNomalized);
					const insertParams = {
						userId,
						exchangeId,
						typeOrder,
						shortName,
						objParams: {
							...objParams,
							prefix: `otcDetails_${shortName}`,
						},
						orders: ordersCompleted,
						arrTickers,
						arrPayTypes,
					};
					await getANDinsertAllOtcOrders(insertParams);
				}
			}
		}
	}
	return allOrders;
};

// start групповоой обработки spot-ордеров
export const startHandlerAllSpotOrders = async (params) => {
	const allOrders = [];
	const { userId, isInsertOrders, typeOrder } = params;
	const user = await User.findOne({ _id: userId });
	if (user) {
		const arrExchanges = await Exchange.find();
		const arrTickers = await Ticker.find();
		const arrPayTypes = await PayType.find();
		const arrOrderStatus = await OrderStatus.find();

		for (let i = 0; i < user.properties.length; i++) {
			if (user.properties[i].updateOrders) {
				let arrData = [];
				let countOrder = 0;
				const { exchangeId } = user.properties[i];
				const objExchange = getObjExchangeById(arrExchanges, exchangeId);
				const { shortName } = objExchange;
				const objParams = {
					userId,
					prefix: '',
					apiKeys: user.properties[i].apiKeys,
					requestHeader: user.properties[i].requestHeader,
					constants: {},
					additionals: {},
				};
				if (shortName === 'BN') {
					objParams.prefix = isInsertOrders
						? `history_${shortName}`
						: `active_${shortName}_API`;
					objParams.constants = CONSTANTS_BN;
					const objReqParams = getObjectRequestParams(objParams);
					arrData = await getSpotOrders(objReqParams);
				} else if (shortName === 'HB') {
					objParams.prefix = isInsertOrders
						? `history_${shortName}_API`
						: `active_${shortName}_API`;
					// ? `history_${shortName}`
					// : `active_${shortName}`;
					objParams.constants = CONSTANTS_HB;
					// objParams.additionals.size = 20;
					const objReqParams = getObjectRequestParams(objParams);
					arrData = await getSpotOrders(objReqParams);
				} else if (shortName === 'KX') {
					objParams.prefix = isInsertOrders
						? `history_${shortName}`
						: `active_${shortName}`;
					objParams.constants = CONSTANTS_KX;
					const objReqParams = getObjectRequestParams(objParams);
					arrData = await getSpotOrders(objReqParams);
				} else if (shortName === 'GX') {
					objParams.prefix = isInsertOrders
						? `history_${shortName}`
						: `active_${shortName}`;
					objParams.constants = CONSTANTS_GX;
					const objReqParams = getObjectRequestParams(objParams);
					arrData = await getSpotOrders(objReqParams);
					// arrData =
					// 	objParams.prefix === `active_GX`
					// 		? []
					// 		: await getSpotOrders(objReqParams);
				} else if (shortName === 'BT') {
					// objParams.prefix = isInsertOrders
					// 	? `history_${shortName}`
					// 	: `active_${shortName}`;
					objParams.prefix = isInsertOrders
						? `history_${shortName}_API`
						: `active_${shortName}_API`;
					objParams.constants = CONSTANTS_BT;
					const objReqParams = getObjectRequestParams(objParams);
					arrData = await getSpotOrders(objReqParams);
				} else if (shortName === 'PX') {
					objParams.prefix = isInsertOrders
						? `history_${shortName}`
						: `active_${shortName}`;
					objParams.constants = CONSTANTS_PX;
					const objReqParams = getObjectRequestParams(objParams);
					arrData = await getSpotOrders(objReqParams);
				} else if (shortName === 'MG') {
					objParams.prefix = isInsertOrders
						? `history_${shortName}_API`
						: `active_${shortName}_API`;
					// ? `history_${shortName}`
					// : `active_${shortName}`;
					objParams.constants = CONSTANTS_MG;
					const symbols = [
						'BTCUSDT',
						'ETHUSDT',
						'MNTUSDT',
						'MXUSDT',
						'BGBUSDT',
						'TONUSDT',
						'XMRUSDT',
						'LTCUSDT',
						'KASUSDT',
						'USDCUSDT',
						'USDDUSDT',
						'DAIUSDT',
					];
					for (let i = 0; i < symbols.length; i++) {
						objParams.additionals.symbol = symbols[i];
						const objReqParams = getObjectRequestParams(objParams);
						let result = await getSpotOrders(objReqParams);
						arrData = arrData.concat(result);
					}
				} else if (shortName === 'KC') {
					objParams.prefix = isInsertOrders
						? `history_${shortName}`
						: `active_${shortName}`;
					objParams.constants = CONSTANTS_KC;
					const objReqParams = getObjectRequestParams(objParams);
					arrData = await getSpotOrders(objReqParams);
				} else if (shortName === 'GT') {
					objParams.prefix = isInsertOrders
						? // ? `history_${shortName}_API`
						  // : `active_${shortName}_API`;
						  `history_${shortName}`
						: `active_${shortName}`;
					objParams.constants = CONSTANTS_GT;
					const objReqParams = getObjectRequestParams(objParams);
					arrData = await getSpotOrders(objReqParams);
				} else if (shortName === 'AX') {
					objParams.prefix = isInsertOrders
						? `history_${shortName}_API`
						: `active_${shortName}_API`;
					objParams.constants = CONSTANTS_AX;
					const objReqParams = getObjectRequestParams(objParams);
					arrData = await getSpotOrders(objReqParams);
				} else if (shortName === 'BG') {
					const prefix = isInsertOrders ? 'history' : 'active';
					objParams.prefix = `${prefix}_${shortName}_API`;
					objParams.constants = CONSTANTS_BG;
					if (prefix === 'history') {
						const tickers = ['BTCUSDT', 'ETHUSDT', 'USDCUSDT'];
						for (let j = 0; j < tickers.length; j++) {
							objParams.additionals.symbol = `${tickers[j]}_SPBL`;
							const objReqParams = getObjectRequestParams(objParams);
							const result = await getSpotOrders(objReqParams);
							arrData = arrData.concat(result);
						}
					} else {
						const objReqParams = getObjectRequestParams(objParams);
						arrData = await getSpotOrders(objReqParams);
					}
				} else if (shortName === 'BX') {
					objParams.prefix = isInsertOrders
						? `history_${shortName}_API`
						: `active_${shortName}_API`;
					objParams.constants = CONSTANTS_BX;
					const objReqParams = getObjectRequestParams(objParams);
					arrData = await getSpotOrders(objReqParams);
				} else if (shortName === 'CX') {
					objParams.prefix = isInsertOrders
						? `history_${shortName}`
						: `active_${shortName}`;
					objParams.constants = CONSTANTS_CX;
					const objReqParams = getObjectRequestParams(objParams);
					arrData = await getSpotOrders(objReqParams);
				} else if (shortName === 'XG') {
					objParams.prefix = isInsertOrders
						? `history_${shortName}_API`
						: `active_${shortName}_API`;
					objParams.constants = CONSTANTS_XG;
					const objReqParams = getObjectRequestParams(objParams);
					arrData = await getSpotOrders(objReqParams);
				}
				if (arrData.length !== 0) {
					// получение массива нормализованных ордеров
					const spotOrdersNomalized = getSpotOrdersNomalized(
						arrData,
						{
							flag: objParams.prefix,
							userId,
							shortName,
							exchangeId,
						},
						arrTickers
					);
					// добавление ордеров в общий массив
					allOrders.push({
						exchangeId,
						shortName,
						orders: spotOrdersNomalized,
					});

					if (isInsertOrders) {
						// проверка наличия ордера в БД
						for (let j = 0; j < spotOrdersNomalized.length; j++) {
							// если spotOrdersNomalized[i] не пустой объект
							if (Object.keys(spotOrdersNomalized[j]).length !== 0) {
								// Проверка уникальности ордера
								const result = await checkOrderInDB(
									spotOrdersNomalized[j].userId,
									typeOrder,
									spotOrdersNomalized[j].orderId,
									spotOrdersNomalized[j].exchange
								);
								// Если ордера нет в БД - вставляем
								if (result.isUnique) {
									await insertOrderToDB(typeOrder, spotOrdersNomalized[j]);
									// console.log(spotOrdersNomalized[j]);
									++countOrder;
								}
							}
						}
					}
					//  else console.log(`${shortName}: isInsertOrders is false`);
				}
				// log print
				consoleProcessed(
					userId,
					shortName,
					arrData,
					countOrder,
					typeOrder
				);
			}
		}
	}
	return allOrders;
};

// получение массива spot -Active, -History ордеров пользователя
export const getDataTickers = async (params) => {
	let result = [];
	const { userId, prefix, typeMarket, config } = params;

	// prefix === 'CN_API' ? console.log(config) : null;
	await axios(config)
		.then((response) => {
			// prefix === 'CN_API' ? console.log(response.data) : null;
			if (prefix === 'BN_API') {
				// result = response.data.data ? response.data.data : [];
			} else if (prefix === 'HB_API') {
				if (typeMarket === 'SPOT')
					result = response.data.status === 'ok' ? response.data.data : [];
				else
					result =
						response.data.status === 'ok' ? response.data.ticks : [];
			} else if (prefix === 'KX_API') {
				result = response.data.code === '0' ? response.data.data : [];
			} else if (prefix === 'BT_API') {
				if (response.data.retMsg === 'Your api key has expired.') {
					console.log(`${prefix}: ${response.data.retMsg}`);
				}
				result =
					response.data.retMsg === 'OK' ? response.data.result.list : [];
			} else if (prefix === 'MG_API') {
				if (typeMarket === 'SPOT') result = response.data;
				else result = response.data.success ? response.data.data : [];
			} else if (prefix === 'KC_API') {
				if (typeMarket === 'SPOT')
					result =
						response.data.code === '200000'
							? response.data.data.ticker
							: [];
				else
					result =
						response.data.code === '200000' ? response.data.data : [];
			} else if (prefix === 'GT_API') {
				result = response.data;
			} else if (prefix === 'BG_API') {
				result = response.data.msg === 'success' ? response.data.data : [];
			} else if (prefix === 'BX_API') {
				result = response.data.code === 0 ? response.data.data : [];
			} else if (prefix === 'XG_API') {
				result = response.data;
			} else if (prefix === 'XT_API') {
				if (typeMarket === 'SPOT')
					result = response.data.mc === "SUCCESS" ? response.data.result : [];
				else
					result =
						response.data.msgInfo=== 'success' ? response.data.result : [];
			} else if (prefix === 'CN_API') {
				result = response.data.code === 0?response.data.data: []
			} else if (prefix === 'BM_API') {
				if (typeMarket === 'SPOT')
					result = response.data.message === "success"?response.data.data: []
				else
					result =
						response.data.message === 'Ok' ? response.data.data.symbols : [];
			} else if (prefix === 'CR_API') {
			} else if (prefix === 'DX_API') {
			}
		})
		.catch((error) => {
			console.log(
				`=======// ${getTimestamps()} //=======\n${userId.slice(
					-4
				)} | ${prefix}: ${TEXT_CONSTANTS.GET_TICKERS_ER}\n${error}`
			);
		});
	return result;
};

// нормализация массива spot- и otc-балансов пользователя
export const getTickersNormalized = (params) => {
	const { tickers, typeMarket, userId, shortName, exchangeId } = params;
	const result = [];

	// print anormal ticker
	const printMsg = (params) => {
		const { ticker, tickerName } = params;
		const msg =
			'incorrectData: ' +
			typeMarket +
			' | ' +
			shortName +
			' | ' +
			tickerName;
		// console.log(msg);
		// console.log(ticker);
	};

	// handler huobi items
	const getFixed = (price) => {
		const str = price.toString();
		const result =
			str.indexOf('-') === -1 ? str : price.toFixed(10).toString();
		return result;
	};

	// handler huobi items
	const fromArray = (value) => {
		const result = { price: '0', size: '0' };
		if (value !== null) {
			result.price = getFixed(value[0]);
			result.size = getFixed(value[1]);
		}
		return result;
	};

	for (let i = 0; i < tickers.length; i++) {
		const fundRate = '';
		const itemTicker = {};

		if (shortName === '_BN') {
		} else if (shortName === 'HB') {
			if (typeMarket === 'SPOT') {
				const ticker = getBaseQuoteAssets(tickers[i].symbol.toUpperCase());
				if (ticker.quoteAsset === '' || tickers[i].ask === null) {
					printMsg({
						ticker: tickers[i],
						tickerName: tickers[i].symbol.toUpperCase(),
					});
				} else {
					itemTicker.askPrice = getFixed(tickers[i].ask);
					itemTicker.askSize = tickers[i].askSize.toString();
					itemTicker.bidPrice = getFixed(tickers[i].bid);
					itemTicker.bidSize = tickers[i].bidSize.toString();
					itemTicker.baseAsset = ticker.baseAsset;
					itemTicker.quoteAsset = ticker.quoteAsset;
					itemTicker.fundRate = fundRate;
				}
			} else {
				const ticker = tickers[i].contract_code.split('-');
				if (tickers[i].ask === null) {
					printMsg({
						ticker: tickers[i],
						tickerName: tickers[i].contract_code,
					});
				} else {
					itemTicker.askPrice = fromArray(tickers[i].ask).price;
					itemTicker.askSize = fromArray(tickers[i].ask).size;
					itemTicker.bidPrice = fromArray(tickers[i].bid).price;
					itemTicker.bidSize = fromArray(tickers[i].bid).size;
					itemTicker.baseAsset = ticker[0];
					itemTicker.quoteAsset = ticker[1];
					itemTicker.fundRate = '0';
				}
			}
		} else if (shortName === 'KX') {
			const ticker = tickers[i].instId.split('-');
			if (tickers[i].askPx === null) {
				printMsg({ ticker: tickers[i], tickerName: tickers[i].instId });
			} else {
				itemTicker.askPrice = tickers[i].askPx;
				itemTicker.askSize = tickers[i].askSz;
				itemTicker.bidPrice = tickers[i].bidPx;
				itemTicker.bidSize = tickers[i].bidSz;
				itemTicker.baseAsset = ticker[0];
				itemTicker.quoteAsset = ticker[1];
				itemTicker.fundRate = typeMarket === 'SPOT' ? fundRate : '0';
			}
		} else if (shortName === 'BT') {
			const ticker = getBaseQuoteAssets(tickers[i].symbol);
			if (ticker.quoteAsset === '' || tickers[i].ask1Price === null) {
				printMsg({ ticker: tickers[i], tickerName: tickers[i].symbol });
			} else {
				itemTicker.askPrice = tickers[i].ask1Price;
				itemTicker.askSize = tickers[i].ask1Size;
				itemTicker.bidPrice = tickers[i].bid1Price;
				itemTicker.bidSize = tickers[i].bid1Size;
				itemTicker.baseAsset = ticker.baseAsset;
				itemTicker.quoteAsset = ticker.quoteAsset;
				itemTicker.fundRate =
					typeMarket === 'SPOT' ? fundRate : tickers[i].fundingRate;
			}
		} else if (shortName === 'MG') {
			if (typeMarket === 'SPOT') {
				const ticker = getBaseQuoteAssets(tickers[i].symbol);
				if (ticker.quoteAsset === '' || tickers[i].askPrice === null) {
					printMsg({ ticker: tickers[i], tickerName: tickers[i].symbol });
				} else {
					itemTicker.askPrice = tickers[i].askPrice;
					itemTicker.askSize = tickers[i].askQty;
					itemTicker.bidPrice = tickers[i].bidPrice;
					itemTicker.bidSize = tickers[i].bidQty;
					itemTicker.baseAsset = ticker.baseAsset;
					itemTicker.quoteAsset = ticker.quoteAsset;
					itemTicker.fundRate = fundRate;
				}
			} else {
				const ticker = tickers[i].symbol.split('_');
				if (ticker[1] === '' || tickers[i].lastPrice == 0) {
					printMsg({ ticker: tickers[i], tickerName: tickers[i].symbol });
				} else {
					itemTicker.askPrice = getFixed(tickers[i].ask1);
					// itemTicker.askPrice = tickers[i].ask1;
					itemTicker.askSize = '0';
					itemTicker.bidPrice = getFixed(tickers[i].bid1);
					// itemTicker.bidPrice = tickers[i].bid1;
					itemTicker.bidSize = '0';
					itemTicker.baseAsset = ticker[0];
					itemTicker.quoteAsset = ticker[1];
					itemTicker.fundRate = tickers[i].fundingRate;
				}
			}
		} else if (shortName === 'KC') {
			if (typeMarket === 'SPOT') {
				const ticker = tickers[i].symbol.split('-');
				if (tickers[i].sell === null) {
					printMsg({ ticker: tickers[i], tickerName: tickers[i].symbol });
				} else {
					itemTicker.askPrice = tickers[i].sell;
					itemTicker.askSize = tickers[i].bestAskSize;
					itemTicker.bidPrice = tickers[i].buy;
					itemTicker.bidSize = tickers[i].bestBidSize;
					itemTicker.baseAsset = ticker[0];
					itemTicker.quoteAsset = ticker[1];
					itemTicker.fundRate = fundRate;
				}
			} else {
				const ticker = getBaseQuoteAssets(tickers[i].symbol.slice(0, -1));
				if (ticker.quoteAsset === '' || tickers[i].bestAskPrice === null) {
					printMsg({ ticker: tickers[i], tickerName: tickers[i].symbol });
				} else {
					itemTicker.askPrice = tickers[i].bestAskPrice;
					itemTicker.askSize = tickers[i].bestAskSize;
					itemTicker.bidPrice = tickers[i].bestBidPrice;
					itemTicker.bidSize = tickers[i].bestBidSize;
					itemTicker.baseAsset = ticker.baseAsset;
					itemTicker.quoteAsset = ticker.quoteAsset;
					itemTicker.fundRate = '0';
				}
			}
		} else if (shortName === 'GT') {
			if (typeMarket === 'SPOT') {
				const ticker = tickers[i].currency_pair.split('_');
				if (
					tickers[i].lowest_ask === '' ||
					tickers[i].lowest_ask === null
				) {
					printMsg({
						ticker: tickers[i],
						tickerName: tickers[i].currency_pair,
					});
				} else {
					itemTicker.askPrice = tickers[i].lowest_ask;
					itemTicker.askSize = '0';
					itemTicker.bidPrice = tickers[i].highest_bid;
					itemTicker.bidSize = '0';
					itemTicker.baseAsset = ticker[0];
					itemTicker.quoteAsset = ticker[1];
					itemTicker.fundRate = fundRate;
				}
			} else {
				const ticker = tickers[i].contract.split('_');
				if (
					tickers[i].lowest_ask === '' ||
					tickers[i].lowest_ask === null
				) {
					printMsg({
						ticker: tickers[i],
						tickerName: tickers[i].contract,
					});
				} else {
					itemTicker.askPrice = tickers[i].lowest_ask;
					itemTicker.askSize = tickers[i].lowest_size;
					itemTicker.bidPrice = tickers[i].highest_bid;
					itemTicker.bidSize = tickers[i].highest_size;
					itemTicker.baseAsset = ticker[0];
					itemTicker.quoteAsset = ticker[1];
					itemTicker.fundRate = tickers[i].funding_rate;
				}
			}
		} else if (shortName === 'BG') {
			const ticker = getBaseQuoteAssets(tickers[i].symbol);
			if (
				ticker.quoteAsset === '' ||
				tickers[i].askPr === '0' ||
				tickers[i].askPr === null
			) {
				printMsg({
					ticker: tickers[i],
					tickerName: tickers[i].symbol,
				});
			} else {
				itemTicker.askPrice = tickers[i].askPr;
				itemTicker.askSize = tickers[i].askSz;
				itemTicker.bidPrice = tickers[i].bidPr;
				itemTicker.bidSize = tickers[i].bidSz;
				itemTicker.baseAsset = ticker.baseAsset;
				itemTicker.quoteAsset = ticker.quoteAsset;
				itemTicker.fundRate =
					typeMarket === 'SPOT' ? fundRate : tickers[i].fundingRate;
			}
		} else if (shortName === 'BX') {
			const ticker = tickers[i].symbol.split('-');
			if (tickers[i].askPrice === null) {
				printMsg({ ticker: tickers[i], tickerName: tickers[i].symbol });
			} else {
				itemTicker.askPrice = tickers[i].askPrice;
				itemTicker.askSize =
					typeMarket === 'SPOT' ? tickers[i].askVolume : tickers[i].askQty;
				itemTicker.bidPrice = tickers[i].bidPrice;
				itemTicker.bidSize =
					typeMarket === 'SPOT' ? tickers[i].bidVolume : tickers[i].bidQty;
				itemTicker.baseAsset = ticker[0];
				itemTicker.quoteAsset = ticker[1];
				itemTicker.fundRate = typeMarket === 'SPOT' ? fundRate : '0';
			}
		} else if (shortName === 'XT') {
			const ticker = tickers[i].s.toUpperCase().split('_');
			if (tickers[i].ap === null || tickers[i].bp === null) {
				printMsg({ ticker: tickers[i], tickerName: tickers[i].s.toUpperCase() });
			} else {
				itemTicker.askPrice = tickers[i].ap;
				itemTicker.askSize =
					typeMarket === 'SPOT' ? tickers[i].aq : "0";
				itemTicker.bidPrice = tickers[i].bp;
				itemTicker.bidSize =
					typeMarket === 'SPOT' ? tickers[i].bq : "0";
				itemTicker.baseAsset = ticker[0];
				itemTicker.quoteAsset = ticker[1];
				itemTicker.fundRate = typeMarket === 'SPOT' ? fundRate : '0';
			}
		} else if (shortName === 'XG') {
			const ticker = tickers[i].ticker_id.split('_');
			if (tickers[i].ask === null || tickers[i].bid === null ||
				tickers[i].ask === "0" || tickers[i].bid === "0") {
				printMsg({ ticker: tickers[i], tickerName: tickers[i].ticker_id });
			} else {
				itemTicker.askPrice = tickers[i].ask;
				itemTicker.askSize = "0";
				itemTicker.bidPrice = tickers[i].bid;
				itemTicker.bidSize = "0";
				itemTicker.baseAsset = ticker[0];
				itemTicker.quoteAsset = ticker[1];
				itemTicker.fundRate = typeMarket === 'SPOT' ? fundRate : '0';
			}
		} else if (shortName === 'BM') {
			if (typeMarket === 'SPOT') {
				const ticker = tickers[i][0].split('_');
				if (tickers[i][8] === null || tickers[i][10] === null) {
					printMsg({
						ticker: tickers[i],
						tickerName: tickers[i][0],
					});
				} else {
					itemTicker.askPrice = tickers[i][10];
					itemTicker.askSize = tickers[i][11];
					itemTicker.bidPrice = tickers[i][8];
					itemTicker.bidSize = tickers[i][9];
					itemTicker.baseAsset = ticker[0];
					itemTicker.quoteAsset = ticker[1];
					itemTicker.fundRate = fundRate;
				}
			} else {
				if (tickers[i].last_price === null) {
					printMsg({
						ticker: tickers[i],
						tickerName: tickers[i].symbol,
					});
				} else {
					itemTicker.askPrice = tickers[i].last_price;
					itemTicker.askSize = "0";
					itemTicker.bidPrice = tickers[i].last_price;
					itemTicker.bidSize = "0";
					itemTicker.baseAsset = tickers[i].base_currency;
					itemTicker.quoteAsset = tickers[i].quote_currency;
					itemTicker.fundRate = tickers[i].funding_rate;
				}
			}
		} else if (shortName === 'CN') {
			const ticker = getBaseQuoteAssets(tickers[i].market);
			if (ticker.quoteAsset === '' || tickers[i].last === null) {
				printMsg({
					ticker: tickers[i],
					tickerName: tickers[i].market,
				});
			} else {
				itemTicker.askPrice = tickers[i].last;
				itemTicker.askSize = "0";
				itemTicker.bidPrice = tickers[i].last;
				itemTicker.bidSize = "0";
				itemTicker.baseAsset = ticker.baseAsset;
				itemTicker.quoteAsset = ticker.quoteAsset;
				itemTicker.fundRate = typeMarket === 'SPOT' ? fundRate : '0';
			}}
		// проверяем не пустой ли объект
		if (Object.keys(itemTicker).length) {
			itemTicker.typeMarket = typeMarket;
			itemTicker.userId = userId;
			itemTicker.shortName = shortName;
			itemTicker.exchangeId = exchangeId;
			result.push(itemTicker);
			// if (shortName === 'BM') {
			// 	// console.log(tickers[i]);
			// 	console.log(
			// 		itemTicker.typeMarket +
			// 			' | ' +
			// 			itemTicker.askPrice +
			// 			' | baseAsset: ' +
			// 			itemTicker.baseAsset +
			// 			' | quoteAsset: ' +
			// 			itemTicker.quoteAsset
			// 	);
			// }
		}
	}
	return result;
};

// получение списка всех тикеров
export const startHandlerAllTickers = async (params) => {
	const { typeMarket } = params;
	const isInsertTickers = !true;
	const userId = '6086427c72453019ec72dbb3';
	const user = await User.findOne({ _id: userId });
	const arrExchanges = await Exchange.find();

	// created, updated spot/fut-тикера в БД
	const upsertTickersInDB = async (params) => {
		const { model, objTicker } = params;
		const queryDB = {
			where: {
				exchangeId: objTicker.exchangeId,
				typeMarket: objTicker.typeMarket,
				baseAsset: objTicker.baseAsset,
				quoteAsset: objTicker.quoteAsset,
			},
		};
		// First try to find the record
		const foundTicker = await model.findOne(queryDB);
		if (!foundTicker) {
			// Item not found, create a new one
			await model.create(objTicker);
			const msg = `${objTicker.shortName} | ${objTicker.typeMarket} | ${objTicker.baseAsset}_${objTicker.quoteAsset} is Created`;
			console.log(msg);
			return { isCreated: true };
		}
		// Found an item, update it
		await model.update(objTicker, queryDB);
		return { isCreated: false };
	};

	if (user) {
		let totalCreated = 0;
		let totalUpdated = 0;
		let totalProcessed = 0;
		for (let i = 0; i < user.properties.length; i++) {
			if (user.properties[i].updateOrders) {
				let arrData = [];
				let countCreatedTicker = 0;
				let countUpdatedTicker = 0;
				const { exchangeId } = user.properties[i];
				const objExchange = getObjExchangeById(arrExchanges, exchangeId);
				const { shortName } = objExchange;
				const objParams = {
					userId,
					prefix: '',
					apiKeys: user.properties[i].apiKeys,
					requestHeader: user.properties[i].requestHeader,
					constants: {},
					additionals: { typeMarket },
				};
				if (shortName === '_BN') {
					objParams.prefix =
						typeMarket === 'SPOT'
							? `spot_tickers_${shortName}_API`
							: `fut_tickers_${shortName}_API`;
					objParams.constants = CONSTANTS_BN;
					const objReqParams = getObjectRequestParams(objParams);
					arrData = await getDataTickers(objReqParams);
				} else if (shortName === 'HB') {
					objParams.prefix =
						typeMarket === 'SPOT'
							? `spot_tickers_${shortName}_API`
							: `fut_tickers_${shortName}_API`;
					objParams.constants = CONSTANTS_HB;
					const objReqParams = getObjectRequestParams(objParams);
					arrData = await getDataTickers(objReqParams);
				} else if (shortName === 'KX') {
					objParams.prefix =
						typeMarket === 'SPOT'
							? `spot_tickers_${shortName}_API`
							: `fut_tickers_${shortName}_API`;
					objParams.constants = CONSTANTS_KX;
					const objReqParams = getObjectRequestParams(objParams);
					arrData = await getDataTickers(objReqParams);
				} else if (shortName === 'BT') {
					objParams.prefix =
						typeMarket === 'SPOT'
							? `spot_tickers_${shortName}_API`
							: `fut_tickers_${shortName}_API`;
					objParams.constants = CONSTANTS_BT;
					const objReqParams = getObjectRequestParams(objParams);
					arrData = await getDataTickers(objReqParams);
				} else if (shortName === 'MG') {
					objParams.prefix =
						typeMarket === 'SPOT'
							? `spot_tickers_${shortName}_API`
							: `fut_tickers_${shortName}_API`;
					objParams.constants = CONSTANTS_MG;
					const objReqParams = getObjectRequestParams(objParams);
					arrData = await getDataTickers(objReqParams);
				} else if (shortName === 'KC') {
					objParams.prefix =
						typeMarket === 'SPOT'
							? `spot_tickers_${shortName}_API`
							: `fut_tickers_${shortName}_API`;
					objParams.constants = CONSTANTS_KC;
					const objReqParams = getObjectRequestParams(objParams);
					arrData = await getDataTickers(objReqParams);
				} else if (shortName === 'GT') {
					objParams.prefix =
						typeMarket === 'SPOT'
							? `spot_tickers_${shortName}_API`
							: `fut_tickers_${shortName}_API`;
					objParams.constants = CONSTANTS_GT;
					const objReqParams = getObjectRequestParams(objParams);
					arrData = await getDataTickers(objReqParams);
				} else if (shortName === 'BG') {
					objParams.prefix =
						typeMarket === 'SPOT'
							? `spot_tickers_${shortName}_API`
							: `fut_tickers_${shortName}_API`;
					objParams.constants = CONSTANTS_BG;
					const objReqParams = getObjectRequestParams(objParams);
					arrData = await getDataTickers(objReqParams);
				} else if (shortName === 'BX') {
					objParams.prefix =
						typeMarket === 'SPOT'
							? `spot_tickers_${shortName}_API`
							: `fut_tickers_${shortName}_API`;
					objParams.constants = CONSTANTS_BX;
					const objReqParams = getObjectRequestParams(objParams);
					arrData = await getDataTickers(objReqParams);
				} else if (shortName === 'XG') {
					objParams.prefix = `spot_tickers_${shortName}_API`;
					objParams.constants = CONSTANTS_XG;
					const objReqParams = getObjectRequestParams(objParams);
					arrData = 
						typeMarket === 'SPOT'
							? await getDataTickers(objReqParams)
							: []
				} else if (shortName === 'XT') {
					objParams.prefix =
						typeMarket === 'SPOT'
							? `spot_tickers_${shortName}_API`
							: `fut_tickers_${shortName}_API`;
					objParams.constants = CONSTANTS_XT;
					const objReqParams = getObjectRequestParams(objParams);
					arrData = await getDataTickers(objReqParams);
				} else if (shortName === 'CN') {
					objParams.prefix =
						typeMarket === 'SPOT'
							? `spot_tickers_${shortName}_API`
							: `fut_tickers_${shortName}_API`;
					objParams.constants = CONSTANTS_CN;
					const objReqParams = getObjectRequestParams(objParams);
					arrData = await getDataTickers(objReqParams);
				} else if (shortName === 'BM') {
					objParams.prefix =
						typeMarket === 'SPOT'
							? `spot_tickers_${shortName}_API`
							: `fut_tickers_${shortName}_API`;
					objParams.constants = CONSTANTS_BM;
					const objReqParams = getObjectRequestParams(objParams);
					arrData = await getDataTickers(objReqParams);
				} else if (shortName === '_CR') {
					objParams.prefix =
						typeMarket === 'SPOT'
							? `spot_tickers_${shortName}_API`
							: `fut_tickers_${shortName}_API`;
					objParams.constants = CONSTANTS_CR;
					const objReqParams = getObjectRequestParams(objParams);
					arrData = await getDataTickers(objReqParams);
				} else if (shortName === '_DX') {
					objParams.prefix =
						typeMarket === 'SPOT'
							? `spot_tickers_${shortName}_API`
							: `fut_tickers_${shortName}_API`;
					objParams.constants = CONSTANTS_DX;
					const objReqParams = getObjectRequestParams(objParams);
					arrData = await getDataTickers(objReqParams);
				}

				if (arrData.length !== 0) {
					console.log(shortName + ' .....');
					// console.log(arrData[0]);
					const params = {
						tickers: arrData,
						typeMarket,
						userId,
						shortName,
						exchangeId,
					};
					const tickersNomalized = getTickersNormalized(params);
					// console.log(tickersNomalized[0]);

					totalProcessed += arrData.length;
					if (isInsertTickers) {
						for (let j = 0; j < tickersNomalized.length; j++) {
							if (tickersNomalized[j].baseAsset !== '') {
								// console.log(tickersNomalized[j]);
								const params = {
									model: Ticker_SQL,
									objTicker: tickersNomalized[j],
								};
								const result = await upsertTickersInDB(params);
								result.isCreated
									? ++countCreatedTicker
									: ++countUpdatedTicker;
							}
						}
						totalCreated += countCreatedTicker;
						totalUpdated += countUpdatedTicker;
					} else console.log('upsert: ' + isInsertTickers);
					// log print
					const msg = `${shortName} | created: ${countCreatedTicker} | updated: ${countUpdatedTicker} | processed: ${arrData.length} | ${typeMarket}`;
					console.log('****' + userId.slice(-4) + ' | ' + msg);
				}
			}
		}
		const ttl = `==================================
		TOTAL | created: ${totalCreated} | updated: ${totalUpdated} | processed: ${totalProcessed} | ${typeMarket}`;
		console.log(ttl);
	}
};

// Обработчик получения общего баланса
export const handlerTotalBalance = async (params) => {
	const { shortName } = params;
	const totalBalance = {
		spotBalance: [],
		p2pBalance: [],
		futBalance: [],
		earnBalance: [],
		lockedData: null,
	};

	if (shortName === 'BN') {
		const spotBalance = await getBalance(
			getObjectRequestParams({
				...params,
				additionals: { typeBalance: 'SPOT' },
			})
		);
		const p2pBalance = await getBalance(
			getObjectRequestParams({
				...params,
				additionals: { typeBalance: 'P2P' },
			})
		);
		const futBalance = await getBalance(
			getObjectRequestParams({
				...params,
				additionals: { typeBalance: 'FUT' },
			})
		);
		const earnBalance = await getBalance(
			getObjectRequestParams({
				...params,
				additionals: { typeBalance: 'EARN' },
			})
		);
		const lockedData = await getBalance(
			getObjectRequestParams({
				...params,
				additionals: { typeBalance: 'LOCK' },
			})
		);
		const spotBalanceFiltered = spotBalance.filter((item) => {
			return +item.free + +item.freeze + +item.locked !== 0;
		});
		const p2pBalanceFiltered = p2pBalance.filter((item) => {
			return +item.free + +item.freeze !== 0;
		});
		const futBalanceFiltered = futBalance.filter((item) => {
			return +item.walletBalance + +item.unrealizedProfit !== 0;
		});
		totalBalance.spotBalance = getBalancesNormalized(
			spotBalanceFiltered,
			`${shortName}_spot`
		);
		totalBalance.p2pBalance = getBalancesNormalized(
			p2pBalanceFiltered,
			`${shortName}_otc`
		);
		totalBalance.futBalance = getBalancesNormalized(
			futBalanceFiltered,
			`${shortName}_fut`
		);
		totalBalance.earnBalance = [
			{
				currency: 'USDT',
				available: earnBalance.totalInterestInUsdt,
				frozen: earnBalance.todayInterestInUsdt,
			},
		];
		totalBalance.lockedData = lockedData.total;
	} else if (shortName === 'HB') {
		// Нормализация элеменов spot-balance для HUOBI
		const getItemBalanceNormalizedHB = (params) => {
			const { arrItems, arrCurrencies } = params;
			const result = [];
			for (let i = 0; i < arrCurrencies.length; i++) {
				let tradeTypeBalance = 0;
				let frozenTypeBalance = 0;
				let nameCoin = '';
				// проверка на массив
				if (Array.isArray(arrItems)) {
					for (let j = 0; j < arrItems.length; j++) {
						if (
							arrCurrencies[i].currency ===
							arrItems[j].currency.toUpperCase()
						) {
							nameCoin = arrItems[j].currency.toUpperCase();
							if (arrItems[j].type === 'trade')
								tradeTypeBalance = arrItems[j].balance;
							if (arrItems[j].type === 'frozen')
								frozenTypeBalance = arrItems[j].balance;
						}
					}
				}
				const item = {
					currency: nameCoin,
					available: tradeTypeBalance.toString(),
					frozen: frozenTypeBalance.toString(),
				};
				if (item.currency !== '') result.push(item);
			}
			return result;
		};

		const allAccounts = await getBalance(
			getObjectRequestParams({
				...params,
				additionals: { typeBalance: 'ALL' },
			})
		);
		// console.log(allAccounts);

		if (allAccounts.length !== 0) {
			const arrCurrencies = await Currency.find();

			const spotBalance = await getBalance(
				getObjectRequestParams({
					...params,
					additionals: {
						typeBalance: 'SPOT',
						accountId: allAccounts.filter((item) => {
							return item.type === 'spot';
						})[0].id,
					},
				})
			);
			const p2pBalance = await getBalance(
				getObjectRequestParams({
					...params,
					additionals: {
						typeBalance: 'P2P',
						accountId: allAccounts.filter((item) => {
							return item.type === 'otc';
						})[0].id,
					},
				})
			);
			// const futBalance = await getBalance(
			// 	getObjectRequestParams({
			// 		...params,
			// 		additionals: { typeBalance: 'FUT' },
			// 	})
			// );

			const spotBalanceFiltered =
				spotBalance === null
					? []
					: getItemBalanceNormalizedHB({
							arrItems: spotBalance.list,
							arrCurrencies,
					  });
			const p2pBalanceFiltered =
				p2pBalance === null
					? []
					: getItemBalanceNormalizedHB({
							arrItems: p2pBalance.list,
							arrCurrencies,
					  });
			totalBalance.spotBalance = spotBalanceFiltered;
			totalBalance.p2pBalance = p2pBalanceFiltered;
		}
	} else if (shortName === '_HB') {
		const spotBalance = await getBalance(
			getObjectRequestParams({
				...params,
				additionals: { typeBalance: 'SPOT' },
			})
		);
		const p2pBalance = await getBalance(
			getObjectRequestParams({
				...params,
				additionals: { typeBalance: 'P2P' },
			})
		);
		const futBalance = await getBalance(
			getObjectRequestParams({
				...params,
				additionals: { typeBalance: 'FUT' },
			})
		);
		console.log(futBalance);
		// Нормализация элеменов spot-balance для HUOBI
		const getItemBalanceNormalizedHB = (params) => {
			const { spotArrItems, arrCurrencies } = params;
			const result = [];
			for (let i = 0; i < arrCurrencies.length; i++) {
				let tradeTypeBalance = 0;
				let frozenTypeBalance = 0;
				let nameCoin = '';
				// проверка на массив
				if (Array.isArray(spotArrItems)) {
					for (let j = 0; j < spotArrItems.length; j++) {
						if (
							arrCurrencies[i].currency ===
							spotArrItems[j].currency.toUpperCase()
						) {
							nameCoin = spotArrItems[j].currency.toUpperCase();
							if (spotArrItems[j].type === 'trade')
								tradeTypeBalance = spotArrItems[j].balance;
							if (spotArrItems[j].type === 'frozen')
								frozenTypeBalance = spotArrItems[j].balance;
						}
					}
				}
				const item = {
					currency: nameCoin,
					available: tradeTypeBalance.toString(),
					frozen: frozenTypeBalance.toString(),
				};
				if (item.currency !== '') result.push(item);
			}
			return result;
		};

		const arrCurrencies = await Currency.find();
		const spotBalanceFiltered =
			spotBalance === null
				? []
				: getItemBalanceNormalizedHB({
						spotArrItems: spotBalance.list,
						arrCurrencies,
				  });
		const p2pBalanceFiltered =
			p2pBalance === null
				? []
				: p2pBalance.filter((item) => {
						return +item.total !== 0;
				  });
		totalBalance.spotBalance = spotBalanceFiltered;
		totalBalance.p2pBalance = getBalancesNormalized(
			p2pBalanceFiltered,
			`${shortName}_otc`
		);
	} else if (shortName === 'KX') {
		const spotBalance = await getBalance(
			getObjectRequestParams({
				...params,
				additionals: { typeBalance: 'SPOT' },
			})
		);
		const p2pBalance = await getBalance(
			getObjectRequestParams({
				...params,
				additionals: { typeBalance: 'P2P' },
			})
		);
		totalBalance.spotBalance =
			spotBalance.length !== 0
				? getBalancesNormalized(
						spotBalance.filter((item) => {
							return +item.balance !== 0;
						}),
						`${shortName}_spot`
				  )
				: [];
		totalBalance.p2pBalance =
			p2pBalance.length !== 0
				? getBalancesNormalized(
						p2pBalance.filter((item) => {
							return +item.balance !== 0;
						}),
						`${shortName}_otc`
				  )
				: [];
	} else if (shortName === 'BZ') {
	} else if (shortName === 'GX') {
		const p2pBalance = await getBalance(getObjectRequestParams(params));
		const p2pBalanceFiltered = p2pBalance.filter((item) => {
			return +item.balance > 0 || +item.locked > 0;
		});
		totalBalance.p2pBalance = getBalancesNormalized(
			p2pBalanceFiltered,
			`${shortName}_otc`
		);
	} else if (shortName === 'BT') {
		const spotBalance = await getBalance(
			getObjectRequestParams({
				...params,
				// additionals: { typeBalance: 'SPOT' },
				additionals: { typeBalance: 'SPOT_API' },
			})
		);
		const p2pBalance = await getBalance(
			getObjectRequestParams({
				...params,
				additionals: { typeBalance: 'P2P' },
			})
		);
		const futBalance = await getBalance(
			getObjectRequestParams({
				...params,
				additionals: { typeBalance: 'FUT' },
			})
		);
		// const spotBalanceFiltered = spotBalance.coinList
		// 	? spotBalance.coinList.filter((item) => {
		// 			return +item.equity !== 0;
		// 	  })
		// 	: [];
		const p2pBalanceFiltered = p2pBalance.filter((item) => {
			return +item.totalBalance !== 0;
		});
		const futBalanceFiltered = futBalance.totalBalanceItems.filter(
			(item) => {
				return item.accountType === 'ACCOUNT_TYPE_CONTRACT';
			}
		);
		totalBalance.spotBalance = getBalancesNormalized(
			// spotBalanceFiltered,
			// `${shortName}_spot`
			spotBalance,
			`${shortName}_spot_API`
		);
		totalBalance.p2pBalance = getBalancesNormalized(
			p2pBalanceFiltered,
			`${shortName}_otc`
		);
		totalBalance.futBalance = getBalancesNormalized(
			futBalanceFiltered,
			`${shortName}_fut`
		);
	} else if (shortName === 'BP') {
		const p2pBalance = await getBalance(getObjectRequestParams(params));
		const p2pBalanceFiltered = p2pBalance.filter((item) => {
			return +item.value > 0;
		});
		totalBalance.p2pBalance = getBalancesNormalized(
			p2pBalanceFiltered,
			`${shortName}_otc`
		);
	} else if (shortName === 'PX') {
		const spotBalance = await getBalance(
			getObjectRequestParams({
				...params,
				additionals: { typeBalance: 'SPOT' },
			})
		);
		const p2pBalance = await getBalance(
			getObjectRequestParams({
				...params,
				additionals: { typeBalance: 'P2P' },
			})
		);
		const spotBalanceFiltered = spotBalance.filter((item) => {
			return +item.free + +item.freeze + +item.locked !== 0;
		});
		const p2pBalanceFiltered = p2pBalance.filter((item) => {
			return +item.free + +item.freeze !== 0;
		});
		totalBalance.spotBalance = getBalancesNormalized(
			spotBalanceFiltered,
			`${shortName}_spot`
		);
		totalBalance.p2pBalance = getBalancesNormalized(
			p2pBalanceFiltered,
			`${shortName}_otc`
		);
	} else if (shortName === 'MG') {
		// const spotBalance = await getBalance(
		// 	getObjectRequestParams({
		// 		...params,
		// 		additionals: { typeBalance: 'SPOT' },
		// 	})
		// );
		const spotBalance_API = await getBalance(
			getObjectRequestParams({
				...params,
				prefix: `balance_${shortName}_API`,
			})
		);
		const p2pBalance = await getBalance(
			getObjectRequestParams({
				...params,
				additionals: { typeBalance: 'P2P' },
			})
		);
		// const spotBalanceFiltered = spotBalance.filter((item) => {
		// 	return +item.total !== 0;
		// });
		const p2pBalanceFiltered = p2pBalance.filter((item) => {
			return +item.totalBalance !== 0;
		});
		// totalBalance.spotBalance = getBalancesNormalized(
		// 	spotBalanceFiltered,
		// 	`${shortName}_spot`
		// );
		totalBalance.spotBalance = getBalancesNormalized(
			spotBalance_API,
			`${shortName}_spot_API`
		);
		totalBalance.p2pBalance = getBalancesNormalized(
			p2pBalanceFiltered,
			`${shortName}_otc`
		);
	} else if (shortName === 'KC') {
		const spotBalance = await getBalance(getObjectRequestParams(params));
		const spotBalanceFiltered = spotBalance.filter((item) => {
			return +item.totalBalance !== 0;
		});
		totalBalance.spotBalance = getBalancesNormalized(
			spotBalanceFiltered,
			`${shortName}_spot`
		);
	} else if (shortName === 'GT') {
		const spotBalance = await getBalance(getObjectRequestParams(params));
		// console.log(spotBalance);
		// const spotBalance = [];
		totalBalance.spotBalance = getBalancesNormalized(
			spotBalance,
			`${shortName}_spot`
		);

		params.prefix = `advs_${shortName}`;
		const objReqParamsAPI = getObjectRequestParams(params);
		const arrData = await getMerchantAdvs(objReqParamsAPI);
		const arrPayTypes = await PayType.find();
		const merchantAdvs =
			arrData.length !== 0
				? getMerchantAdvsNomalized(
						arrData,
						{
							userId: params.userId,
							exchangeId: params.additionals.exchangeId,
							prefix: shortName,
						},
						arrPayTypes
				  )
						.filter((item) => {
							return item.tradeType === 'SELL';
						})
						.map((item) => {
							return {
								currency: item.asset,
								available: '0',
								frozen: item.volume,
							};
						})
				: [];

		totalBalance.p2pBalance = getBalancesNormalized(
			merchantAdvs,
			`${shortName}_otc`
		);
	} else if (shortName === 'AX') {
		const allBalances = await getBalance(getObjectRequestParams(params));
		const spotBalanceFiltered = allBalances.filter((item) => {
			return (
				item.type === 'user' &&
				item.serviceBalance + item.heldBalance !== 0
			);
		});
		const p2pBalanceFiltered = allBalances.filter((item) => {
			return (
				item.type === 'p2p' && item.serviceBalance + item.heldBalance !== 0
			);
		});
		totalBalance.spotBalance = getBalancesNormalized(
			spotBalanceFiltered,
			`${shortName}_spot_API`
		);
		totalBalance.p2pBalance = getBalancesNormalized(
			p2pBalanceFiltered,
			`${shortName}_otc_API`
		);
	} else if (shortName === 'BG') {
		params.additionals.typeBalance = 'SPOT';
		const spotBalance = await getBalance(getObjectRequestParams(params));
		const spotBalanceFiltered = spotBalance.filter((item) => {
			return +item.available + +item.frozen !== 0;
		});
		totalBalance.spotBalance = getBalancesNormalized(
			spotBalanceFiltered,
			`${shortName}_spot`
		);

		params.additionals.typeBalance = 'P2P';
		const p2pBalance = await getBalance(getObjectRequestParams(params));
		const p2pBalanceFiltered = p2pBalance.filter((item) => {
			return +item.available + +item.frozen !== 0;
		});
		totalBalance.p2pBalance = getBalancesNormalized(
			p2pBalanceFiltered,
			`${shortName}_otc`
		);
	} else if (shortName === 'BX') {
		const allBalances = await getBalance(getObjectRequestParams(params));
		if (params.prefix === `balance_${shortName}_API`) {
			// console.log(allBalances);
			totalBalance.spotBalance =
				allBalances.length === 0
					? []
					: getBalancesNormalized(allBalances, `${shortName}_spot_API`);
		} else {
			const spotBalanceFiltered = allBalances
				.filter((item) => {
					return item.accountName === 'Fund Account';
				})
				.map((item) => {
					return {
						assetName: item.total.sign,
						assetAmount: item.total.currencyAmount,
					};
				});
			const p2pBalanceFiltered = allBalances
				.filter((item) => {
					return item.accountName === 'P2P Ad';
				})
				.map((item) => {
					return {
						assetName: item.total.sign,
						assetAmount: item.total.currencyAmount,
					};
				});
			totalBalance.spotBalance =
				spotBalanceFiltered.length === 0
					? []
					: getBalancesNormalized(
							spotBalanceFiltered,
							`${shortName}_spot`
					  );
			totalBalance.p2pBalance =
				p2pBalanceFiltered.length === 0
					? []
					: getBalancesNormalized(p2pBalanceFiltered, `${shortName}_otc`);
		}
	} else if (shortName === 'CX') {
		const spotBalance = await getBalance(
			getObjectRequestParams({
				...params,
				additionals: { typeBalance: 'SPOT' },
			})
		);
		const p2pBalance = await getBalance(
			getObjectRequestParams({
				...params,
				additionals: { typeBalance: 'P2P' },
			})
		);
		const spotBalanceFiltered = spotBalance.filter((item) => {
			return +item.free + +item.freeze + +item.locked !== 0;
		});
		const p2pBalanceFiltered = p2pBalance.filter((item) => {
			return +item.free + +item.freeze !== 0;
		});
		totalBalance.spotBalance = getBalancesNormalized(
			spotBalanceFiltered,
			`${shortName}_spot`
		);
		totalBalance.p2pBalance = getBalancesNormalized(
			p2pBalanceFiltered,
			`${shortName}_otc`
		);
	} else if (shortName === 'XG') {
		const spotBalance = await getBalance(getObjectRequestParams(params));
		const spotBalanceFiltered = spotBalance.filter((item) => {
			return +item.available + +item.held !== 0;
		});
		totalBalance.spotBalance = getBalancesNormalized(
			spotBalanceFiltered,
			`${shortName}_spot_API`
		);
	} else if (shortName === 'CN') {
		const spotBalance = await getBalance(getObjectRequestParams(params));
		const spotBalanceFiltered = spotBalance.filter((item) => {
			return +item.available + +item.frozen !== 0;
		});
		totalBalance.spotBalance = getBalancesNormalized(
			spotBalanceFiltered,
			`${shortName}_spot_API`
		);
	} else if (shortName === 'BM') {
		const spotBalance = await getBalance(getObjectRequestParams(params));

		params.prefix = `advs_${shortName}`;
		const objReqParams = getObjectRequestParams(params);
		const arrData = await getMerchantAdvs(objReqParams);
		const arrPayTypes = await PayType.find();
		const merchantAdvs =
			arrData.length !== 0
				? getMerchantAdvsNomalized(
						arrData,
						{
							userId: params.userId,
							exchangeId: params.additionals.exchangeId,
							prefix: shortName,
						},
						arrPayTypes
				  )
				: [];

		const p2pBalanceFiltered = merchantAdvs.filter((item) => {
			return item.advStatus && item.tradeType === 'SELL';
		});
		totalBalance.spotBalance = getBalancesNormalized(
			spotBalance,
			`${shortName}_spot_API`
		);
		totalBalance.p2pBalance = getBalancesNormalized(
			p2pBalanceFiltered,
			`${shortName}_otc`
		);
	} else if (shortName === 'CM') {
		const p2pBalance = await getBalance(getObjectRequestParams(params));
		const p2pBalanceFiltered = p2pBalance.filter((item) => {
			return +item.balance !== 0;
		});
		totalBalance.p2pBalance = getBalancesNormalized(
			p2pBalanceFiltered,
			`${shortName}_otc`
		);
	} else if (shortName === 'XT') {
		const spotBalance = await getBalance(getObjectRequestParams(params));
		totalBalance.spotBalance = getBalancesNormalized(
			spotBalance,
			`${shortName}_spot`
		);
	}
	// console.log(totalBalance);
	return totalBalance;
};

// групповое получение Balances
export const getAllBalances = async (params) => {
	const allBalances = [];
	const { user } = params;
	const arrCurrencies = await Currency.find();
	const arrExchanges = await Exchange.find();
	const userId = user._id.toString();

	const objParams = {
		userId,
		prefix: '',
		apiKeys: {},
		requestHeader: {},
		constants: {},
		additionals: {},
	};

	for (let i = 0; i < user.properties.length; i++) {
		if (user.properties[i].updateOrders) {
			const exchangeId = user.properties[i].exchangeId;
			const objExchange = getObjExchangeById(arrExchanges, exchangeId);
			const shortName = objExchange.shortName;
			objParams.prefix = `balance_${shortName}`;
			objParams.shortName = shortName;
			objParams.apiKeys = user.properties[i].apiKeys;
			objParams.requestHeader = user.properties[i].requestHeader;
			const dataBalances = {
				exchangeId,
				shortName,
				balances: {
					spotBalance: [],
					p2pBalance: [],
					futBalance: [],
					earnBalance: [],
					lockedData: null,
				},
			};

			if (shortName === 'BN') {
				objParams.constants = CONSTANTS_BN;
			} else if (shortName === 'HB') {
				objParams.constants = CONSTANTS_HB;
				objParams.prefix = `balance_${shortName}_API`;
			} else if (shortName === 'KX') {
				objParams.constants = CONSTANTS_KX;
			} else if (shortName === 'GX') {
				objParams.constants = CONSTANTS_GX;
			} else if (shortName === 'BT') {
				objParams.constants = CONSTANTS_BT;
			} else if (shortName === 'BP') {
				objParams.constants = CONSTANTS_BP;
			} else if (shortName === 'PX') {
				objParams.constants = CONSTANTS_PX;
			} else if (shortName === 'MG') {
				objParams.constants = CONSTANTS_MG;
			} else if (shortName === 'KC') {
				objParams.constants = CONSTANTS_KC;
			} else if (shortName === 'GT') {
				objParams.constants = CONSTANTS_GT;
			} else if (shortName === 'BG') {
				objParams.constants = CONSTANTS_BG;
				objParams.prefix = `balance_${shortName}_API`;
			} else if (shortName === 'BX') {
				objParams.constants = CONSTANTS_BX;
				// objParams.prefix = `balance_${shortName}_API`;
				objParams.prefix = `balance_${shortName}`;
			} else if (shortName === 'CX') {
				objParams.constants = CONSTANTS_CX;
			} else if (shortName === 'XG') {
				objParams.constants = CONSTANTS_XG;
				objParams.prefix = `balance_${shortName}_API`;
			} else if (shortName === 'CN') {
				objParams.constants = CONSTANTS_CN;
				objParams.prefix = `balance_${shortName}_API`;
			} else if (shortName === 'BM') {
				objParams.constants = CONSTANTS_BM;
				objParams.prefix = `balance_${shortName}_API`;
				objParams.additionals.exchangeId = exchangeId;
			} else if (shortName === 'AX') {
				objParams.constants = CONSTANTS_AX;
				objParams.prefix = `balance_${shortName}_API`;
			} else if (shortName === 'CM') {
				objParams.constants = CONSTANTS_CM;
				// objParams.prefix = `balance_${shortName}_API`;
				objParams.prefix = `balance_${shortName}`;
			} else if (shortName === 'XT') {
				objParams.constants = CONSTANTS_XT;
				objParams.prefix = `balance_${shortName}`;
			}

			const totalBalance = await handlerTotalBalance(objParams);
			dataBalances.balances = totalBalance;

			console.log(`${shortName}: ${TEXT_CONSTANTS.BALANCE_OK}`);
			// добавление балансов в общий массив
			allBalances.push(dataBalances);
		}
	}

	return allBalances;
};

// получение текущего курса тикерa
const getCurrentCourseAssetUSDT = async (arrTickers) => {
	let result;
	const priceUSDTRUB = await getPriceTicker('Garantex', 'USDTRUB');
	for (let i = 0; i < arrTickers.length; i++) {
		// Синтетический расчет цены тикера
		if (
			arrTickers[i].ticker === 'SLPRUB' ||
			arrTickers[i].ticker === 'EOSRUB' ||
			arrTickers[i].ticker === 'GMTRUB' ||
			arrTickers[i].ticker === 'DASHRUB' ||
			arrTickers[i].ticker === 'DOGERUB' ||
			arrTickers[i].ticker === 'BCHRUB' ||
			arrTickers[i].ticker === 'SHIBRUB' ||
			arrTickers[i].ticker === 'TRXRUB' ||
			arrTickers[i].ticker === 'HTXRUB' ||
			// arrTickers[i].ticker === 'BTCRUB' ||
			// arrTickers[i].ticker === 'ETHRUB' ||
			arrTickers[i].ticker === 'BNBRUB' ||
			arrTickers[i].ticker === 'TONRUB' ||
			arrTickers[i].ticker === 'XMRRUB'
		) {
			const tickerAssetUSDT = arrTickers[i].ticker.replace('RUB', 'USDT');
			const priceAssetUSDT = await getPriceTicker(
				arrTickers[i].exchange,
				tickerAssetUSDT
			);
			arrTickers[i].course =
				priceUSDTRUB.priceTicker * priceAssetUSDT.priceTicker;
		} else if (
			arrTickers[i].ticker === 'USDCRUB' ||
			arrTickers[i].ticker === 'TUSDRUB' ||
			arrTickers[i].ticker === 'USDDRUB' ||
			arrTickers[i].ticker === 'BUSDRUB'
		) {
			arrTickers[i].course = priceUSDTRUB.priceTicker;
		} else if (
			arrTickers[i].ticker === 'RUBRUB' ||
			arrTickers[i].ticker === 'USDTUSDT'
		) {
			arrTickers[i].course = '1.00000000';
		}
		// Стандартное получение цены тикера
		else {
			result = await getPriceTicker(
				arrTickers[i].exchange,
				arrTickers[i].ticker
			);
			if (result.priceTicker !== null) {
				arrTickers[i].course = result.priceTicker;
			}
		}
		// console.log(
		// 	arrTickers[i].exchange +
		// 		': ' +
		// 		arrTickers[i].ticker +
		// 		': ' +
		// 		arrTickers[i].course
		// );
		const item = await Ticker.findOne({ ticker: arrTickers[i].ticker });
		// если ticker не нашёлся, вставляем в БД
		if (!item) {
			const newTicker = {
				ticker: arrTickers[i].ticker, // "BTCUSDT"
				asset: arrTickers[i].asset, // "BTC"
				course: arrTickers[i].course, // "51026.42000000"
				exchange: arrTickers[i].exchange, // "Binance"
			};
			// сохраняем в БД
			const ticker = new Ticker(newTicker);
			await ticker
				.save()
				.then(() => {
					console.log(`Ticker ${newTicker.ticker} is inserted`);
				})
				.catch((error) => console.log(error));
		}
		// если тикер есть в БД - обновляем цену
		else {
			item.course = arrTickers[i].course;
			await item
				.save()
				.then(() => {
					// console.log(`Course ${item.ticker} is updated`);
				})
				.catch((error) =>
					console.log(`Course ${item.ticker} isnot updated \n${error}`)
				);
		}
	}
	console.log('Courses updated => date: ' + new Date().toLocaleString());
};

TG_BOT
	? console.log('=== setInterval() orders|tickers is false ===')
	: setInterval(async () => {
			console.log(
				'+++++++|tickers|+++++++ ' +
					getTimestamps() +
					' +++++++|timer|+++++++'
			);
			// обновление курсов тикеров
			getCurrentCourseAssetUSDT(tickers);
			// Проверка новых завершенных otc-orders
			await startHandlerAllOtcOrders({
				userId: '6086427c72453019ec72dbb3',
				isInsertOrders: true,
				typeOrder: 'MERCHANT',
			});
			// Проверка новых завершенных spot-orders
			await startHandlerAllSpotOrders({
				userId: '6086427c72453019ec72dbb3',
				isInsertOrders: true,
				typeOrder: 'SPOT',
			});
	  }, 60000 * 29);
