BoxExchanger
  • Вернутся на сайт
  • Начало работы
    • Настройка безопасности
      • Создание админа
      • Настройка прав администратора (роли)
      • Установка двухфакторной аутентификация
      • Ограничения доступа админ панели по IP
        • Установка ограничения на CloudFlare
        • Установка ограничений в админ панели
      • Установка ограничение по header host
    • Настройка дизайна
    • Технические работы
    • Уведомление на сайте
      • Создание
      • Редактирование
    • Избраные курсы
      • Создание
      • Редактирование
    • Подключение онлайн чата
      • Подключение чата LiveChat
      • Подключение чата JivoSite
      • Подключение чата HelpCrunch
    • Добавление контактов
    • Настройка почты
      • Отправка копии отправленных писем
      • Подключение GMail почты
      • Подключение Zoho почты
      • Подключение dynadot почты
    • Вопросы и ответы
      • Создать
    • Настройка AntiBot системы
      • Установка reCAPTCHA
    • Правила
      • Создание
      • AML/KYC Политика
    • Партнеры
      • Создание партнера
      • Редактирование
    • Новости
      • Создание
    • Отзывы
      • Создать
      • Список отзывов
    • Статичные страницы
      • Создание
    • Настройки авторизации пользователя
    • Настройка идентификаторов
    • Настройка истории действий
  • Обмен
    • Валюты
      • Список валют
      • Логотип валюты
      • Название валюты
      • Тип валюты
      • Точность суммы
      • XML валюты
      • Курс к USD
      • Резервы
      • Настройка поля валюты
      • Прием платежей
      • Настройка выплаты
      • AML проверка
      • Верификация
    • Сортировка направлений
    • Направление
      • Приоритетные модули
      • Плавающий курс
      • Страховка курса
      • SEO-friendly URL (ЧПУ)
      • Документы
      • Дополнительные услуги
    • Настройка группы направлений
    • Мерчант и АПИ
      • 001k bot
        • Мерчант 001k bot
        • Выплаты 001k bot
      • Биржа whitebit
        • Взаимодействие модулей
        • Мерчант whitebit
        • Выплаты whitebit
      • BetPay
        • Мерчант BetPay
        • Выплаты BetPay.money
      • Heleket
        • Мерчант Heleket
        • Выплаты Heleket
      • Paylink.finance
        • Мерчант Paylink.finance
        • Выплаты Paylink.finance
      • VelPay
        • Выплаты VelPay
      • Мерчант BSC BEP20
      • Мерчант Billline
      • Мерчант Bitconce
      • Мерчант By password
      • Мерчант Dynamic requisites
      • Мерчант EVM Token
      • Мерчант ETH ERC20
      • Мерчант TRON TRC20
      • Мерчант Monerod
      • Мерчант Payeer
      • Мерчант Perfect Money
      • Мерчант WestWallet.io
      • Настройка Inqud
      • Выплаты Agents Telegram
      • Выплаты Auto Success
      • Выплаты Binance
      • Выплаты Kuna.io
      • Выплаты PSPline
      • Выплаты WestWallet.io
    • Парсер курсов
      • BestChange v2
      • BetPay.Money
      • CurrencyLayer
      • Heleket
      • Kurs.Expert
      • PancakeSwap
      • Paylink.finance
      • VelPay
      • whitebit v2
      • XML file
    • Верификации
    • Расчет суммы обмена
  • Заявки
    • Список обменов
    • Заявки
      • Статусы заявки
    • Автоматическое добавление резерва
  • Партнерская программа
    • Партнерские направления
    • Партнёрские обмены
    • Реферальные настройки
  • AML плагины
    • CUBE3
    • CrystalBlockchain
    • AMLBot.com
    • GetBlock.net
  • Дополнительные системы
    • Внутренний кошелек
    • Расписания
    • Approve underpaid orders
    • Heleket модули
      • Heleket auto update fee
      • Heleket control available
      • Heleket auto min amount for TO currency
    • Install plugin
    • KYC модули
      • KYC Модуль Kycaid
      • KYC Модуль AMLBot
      • KYC Модуль SumSub
    • Whitebit модули
      • WhiteBit Exchanger auto update fee
      • WhiteBIT control available
      • WhiteBIT auto min amount for TO currency
    • BestChange ScamAPI
  • Системы авторизации
    • Авторизация Apple
    • Авторизация Google
  • Для разработчиков
    • Установка проекта
      • Сервер для обменника
        • Vultr
        • DigitalOcean
          • Удаление VDS на DigitalOcean
        • Hetzner Cloud
          • Изменения размера VDS на Hetzner
          • Удаление VDS на Hetzner
      • Настройки CloudFlare
      • Установка Nginx
      • Установка ПО
        • Установка NodeJs
        • Установка MongoDB
        • Установка exchanger-api
        • Установка exchanger-web
        • Настройка сборки на CloudFlare Workers
    • Настройка Telegram Bot
    • Доступ к исходному коду
    • Миграция Git BoxExchanger
    • Разработка client-web
      • Локальный запуск
      • Применения изменений
    • Шаблоны писем
      • Локализация шаблонов
    • Загрузка статического файла
    • Структура проекта
    • Настройки API документации
    • Установка Node
      • Bitcoin Node
      • Monero Node
      • Ethereum Node
      • Tron Node
    • Разработка модулей
      • Мерчант системы
      • Модуль выплат
      • Парсер курсов
    • Отправка логов разработчикам
    • Процессинг платежей API
    • Настройка VPN (openvpn)
    • Установка SOCKS5-прокси
    • Настройка бекап на B2
    • Настройка Firewall
      • Настройка доступа порта 22 (ssh)
      • Настройка доступа портов 80,443 (http/s)
      • IP в белый список CloudFlare
    • Webhook уведомления URL
      • Новый обмен
      • Новая верификация (ручная)
      • Обновление статуса заявки
      • Регистрация пользователя
  • Журнал изменений
Powered by GitBook
On this page
  • Parser Integration Documentation
  • File Structure
  • Configuration (configure.js)
  • Icon (icon.png)
  • Implementation (index.js)
  • Example Implementation
  • Testing
  • Notes

Was this helpful?

  1. Для разработчиков
  2. Разработка модулей

Парсер курсов

Here's the revised documentation with brief explanations of the properties, without the comments:

Parser Integration Documentation

This document outlines the structure and key components required to integrate a parser into the system.

File Structure

Your parser should be organized in the following directory structure:

pluginsExternal/parser/PARSER_NAME/
  • configure.js: Configuration file to set up the parser.

  • icon.png: An icon representing the parser.

  • index.js: The main implementation of the parser.

Configuration (configure.js)

The configure.js file is used to define the parser's setup. It should export an object with the following structure:

module.exports = {
  title: "Parser Name",
  name: "parser_name",
  defaultInterval: 30000,
  isActiveDefault: false,
  extra: {
    // Additional configurations like API keys, currencies, etc.
  },
};

Properties:

  • title: The display name of the parser.

  • name: A unique identifier for the parser, typically in lowercase and snake_case.

  • defaultInterval: The default time interval (in milliseconds) at which the parser fetches data.

  • isActiveDefault: A boolean indicating whether the parser is active by default when initialized.

  • extra: An object for any additional settings such as API keys, currencies, or other specific parameters required by the parser.

Icon (icon.png)

The icon.png file should be a PNG image with a minimum size of 150x150 pixels. This icon will represent your parser in the user interface.

Implementation (index.js)

The index.js file contains the core logic of your parser. Below are the key methods that should be implemented:

Constructor

The constructor is responsible for initializing the parser with the necessary configurations and options.

Parameters:

  • config: An object containing configuration details like the parser's name, title, default interval, and extra settings such as API keys.

  • options: An object that may include an emitter for event-based data processing or a callback for direct function-based processing.

updateRate Method

The updateRate method fetches the latest data from an external API, processes it, and then either emits the data through an event emitter or returns it via a callback function.

Key Responsibilities:

  • Fetch data from the API using the apiRequest method.

  • Process the data, including calculations like exchange rates.

  • Format the data into a consistent structure ({ from, to, buy }) and create data objects rate1

  • Emit or return the processed data rate1 using the emitter or callback provided in the options.

  • Optional: Reverse the exchange rate if the API provides only one-way rates.

  • Return an array of processed data objects.

apiRequest Method

The apiRequest method handles communication with the external API to retrieve the necessary data.

Key Responsibilities:

  • Send an HTTP request to the API endpoint.

  • Handle the response and format the data.

  • Manage errors, ensuring that descriptive messages are provided if the request fails.

Example Implementation

const axios = require("axios");
const BigNumber = require("bignumber.js");

class ParserName {

  constructor(config, options) {
    this.id = __dirname.split("/").slice(-1)[0];
    this.exchangeRateUrl = "https://api.example.com/exchange_rate";

    if (config.extra && config.extra.apiKey) {
      this.apiKey = config.extra.apiKey;
    } else {
      throw new Error("API key is required");
    }

    if (options.emitter) {
      this.emitter = options.emitter;
    } else if (options.callback) {
      this.callback = options.callback;
    }
  }

  async updateRate() {
    const data = await this.apiRequest();
    const rate = new BigNumber(data.rate);

    const rate1 = { from: data.from, to: data.to, buy: rate };

    // Optional: Reverse the exchange rate if the API provides only one-way rates
    const rate2 = { from: data.to, to: data.from, buy: new BigNumber(1).div(rate) };

    if (this.emitter) {
      this.emitter.emit("updateRate", this.id_key, rate1);
      this.emitter.emit("updateRate", this.id_key, rate2);
    } else if (this.callback) {
      this.callback('updateRate', this.id_key, rate1);
      this.callback('updateRate', this.id_key, rate2);
    }

    return [rate1, rate2];
  }

  async apiRequest() {
    try {
      const response = await axios.get(this.exchangeRateUrl, {
        headers: {
          'Content-Type': 'application/json',
          Authorization: `Bearer ${this.apiKey}`,
        },
      });
      return response.data;
    } catch (error) {
      throw new Error(`API Request failed: ${error.message}`);
    }
  }
}

module.exports = ParserName;

Testing

To test the parser, you can instantiate it and call the updateRate method:

const parser = new ParserName(
  { extra: { apiKey: "your-api-key-here" } },
  { emitter: { emit: (event, data) => console.log(event, data) } }
);

parser.updateRate().then(data => console.log("Rates Updated:", data));

Notes

  • Unique Directory Name: Ensure that each parser has a unique directory name.

  • Default States: Always define a default interval and active state (isActiveDefault) in the configuration.

  • Title and Name: Both title and name fields in the configuration are mandatory and must be unique.

  • Icon: Use a distinct icon for each parser to avoid confusion in the UI.

Last updated 1 month ago

Was this helpful?