Skip to content

dmitry575/Crypto.Compare

Repository files navigation

Comparison of buy and sell price on crypto exchanges

.NET Core ASP.NET Core Docker License

Description

Crypto.Compare is .NET Core system for collecting and aggregating the best prcie of order book data from cryptocurrency exchanges in real-time. The system provides:

🔄 Real-time connectivity to 7+ crypto exchanges

💾 Dual storage (PostgreSQL + Cache)

🌐 WebSocket and REST API for client connections

🐳 Full Docker support for easy deployment

⚡ High performance thanks to .NET 10 and async/await

🏗️ Architecture system

┌─────────────────────────────────────────────────────────┐
│                    Client Applications                  │
│  ┌──────────┐  ┌──────────┐  ┌──────────┐               │
│  │ Web App  │  │ Mobile   │  │  Desktop │               │
│  └──────────┘  └──────────┘  └──────────┘               │
└─────────────────┬─────────────────┬─────────────────────┘
                  │                 │
           REST API (HTTP)   WebSocket (WS)
                  │                 │
          ┌───────▼─────────────────▼────────┐
          │      Crypto.Compare API Gateway  │
          │  ┌─────────────┐ ┌─────────────┐ │
          │  │ REST Contr. │ │ WS Handler  │ │
          │  └─────────────┘ └─────────────┘ │
          └──────────────┬─────────────────┬─┘
                         │                 │
                ┌────────▼─────┐ ┌─────────▼─────┐
                │   Cache      │ │ PostgreSQL    │
                │              │ │               │
                └──────────────┘ └───────────────┘
                         │
                  ┌──────▼─────────────────────┐
                  │   Exchange Data Collectors │
                  │  ┌────┐ ┌────┐ ┌────┐      │
                  │  │Bing│ │Bitg│ │BitM│  ... │
                  │  │ X  │ │ et │ │ art│      │
                  │  └────┘ └────┘ └────┘      │
                  └────────────────────────────┘

🚀 Quick start

  1. Clone the repository:
git clone https://github.com/dmitry575/Crypto.Compare.git
cd Crypto.Compare
  1. Starting the application in docker
  • Stopping the current image if it is running
docker-compose -f docker-compose.tests.yml down
  • Build main image and database
docker-compose -f docker-compose.tests.yml build api-public sql 
  • Starting dependencies
docker-compose -f docker-compose.tests.yml run --rm start_dependencies
  • Starting the application
docker-compose -f docker-compose.tests.yml up -d api-public 
  1. Open the API documentation:

Swagger UI: http://localhost:18072/swagger

Starting for OS Windows

It is enough to launch the file: docker-start.cmd

Adding data about exchanges

Since all data about access to exchanges is stored in the database, it is necessary to add the necessary records. After running all the images in the docker container, you can connect to Adminer to manage viewing and adding entries to the database. You need to choose:

  • System: Posgresql
  • Server: sql
  • Username: postgres
  • Password: test

Add data to connect to exchanges (Access Key and Private Key)

MEXC

INSERT INTO public."Providers"(
            "Name", "WebSite", "BaseUrl", "AccessKey", "SecretKey", "Status", "CreatedAt", "UpdatedAt")
    VALUES ('mexc', 'https://mexc.com', 'https://api.mexc.com', 'AccessKey', 'SecretKey', 1,NOW(), NOW());

Need to replace in the request: AccessKey and SecretKey - for keys from the exchange's personal account

XT

INSERT INTO public."Providers"(
            "Name", "WebSite", "BaseUrl", "AccessKey", "SecretKey", "Status", "CreatedAt", "UpdatedAt")
    VALUES ('xtcom', 'https://xt.com', 'https://sapi.xt.com', 'AccessKey', 'SecretKey', 1,NOW(), NOW());

Need to replace in the request: AccessKey and SecretKey - for keys from the exchange's personal account

BYBIT

INSERT INTO public."Providers"(
            "Name", "WebSite", "BaseUrl", "AccessKey", "SecretKey", "Status", "CreatedAt", "UpdatedAt")
    VALUES ('bybit', 'https://bybit.com', 'https://api.bybit.com', 'AccessKey', 'SecretKey', 1,NOW(), NOW());

Need to replace in the request: AccessKey and SecretKey - for keys from the exchange's personal account

BINGX

INSERT INTO public."Providers"(
            "Name", "WebSite", "BaseUrl", "AccessKey", "SecretKey", "Status", "CreatedAt", "UpdatedAt")
    VALUES ('bingx', 'https://bingx.com', 'https://open-api.bingx.com', 'AccessKey', 'SecretKey', 1,NOW(), NOW());

Need to replace in the request: AccessKey and SecretKey - for keys from the exchange's personal account

BITGET

INSERT INTO public."Providers"(
            "Name", "WebSite", "BaseUrl", "AccessKey", "SecretKey", "Status", "CreatedAt", "UpdatedAt", "PasswordKey")
    VALUES ( 'bitget', 'https://bitget.com', 'https://api.bitget.com', 'AccessKey', 'SecretKey', 1,NOW(), NOW(), 'PasswordKey');

Need to replace in the request: AccessKey, SecretKey and PasswordKey - for keys from the exchange's personal account

GATEIO

INSERT INTO public."Providers"(
            "Name", "WebSite", "BaseUrl", "AccessKey", "SecretKey", "Status", "CreatedAt", "UpdatedAt", "PasswordKey")
    VALUES ( 'gateio',  'https://gateio.ws', 'https://api.gateio.ws', 'AccessKey', 'SecretKey', 1,NOW(), NOW(), '');

Need to replace in the request: AccessKey and SecretKey - for keys from the exchange's personal account

BITMART

INSERT INTO public."Providers"(
            "Name", "WebSite", "BaseUrl", "AccessKey", "SecretKey", "Status", "CreatedAt", "UpdatedAt", "PasswordKey")
    VALUES ( 'bitmart',  'https://bitmart.com', 'https://api-cloud.bitmart.com', 'AccessKey', 'SecretKey', 1,NOW(), NOW(), '');

Need to replace in the request: AccessKey and SecretKey - for keys from the exchange's personal account

BINANCE

INSERT INTO public."Providers"(
            "Name", "WebSite", "BaseUrl", "AccessKey", "SecretKey", "Status", "CreatedAt", "UpdatedAt")
    VALUES ('binance', 'https://binance.com', 'https://api.binance.com', 'AccessKey', 'SecretKey', 1,NOW(), NOW());

Need to replace in the request: AccessKey and SecretKey - for keys from the exchange's personal account

Getting API keys for exchanges

Database settings

Using PosgreSQL. Script for creating database:

./db/init.sql

API requests examples

  • Get data of crypto markets
GET /v1/providers?skip=0&rows=10
  • Get data full add of crypto market
GET /v1/providers/{id}
  • Get data full add of crypto market
GET /v1/providers/{id}
  • Get prices from all markets by ticker of currency
GET /v1/symbols/ticker/{ticker}
curl -X POST "http://localhost:8081/v1/symbols/ticker/btcusdt" \
  -H "Content-Type: application/json" 

WebSocket examples

First connect

ws://localhost:8081

Response

{
    "id": "a7aef64b-6ee8-47ea-a17d-72d39874001c",
    "type": 0,
    "data": {
        "message": "Connected to Crypto Compare server"
    }
}

Type Welcome = 0

Error message

{
    "id": "1610dd4f-c266-4928-81c1-33819a22e55e",
    "type": -1,
    "data": {
        "error": "Ticker no found",
        "errorCode": 3
    }
}

Type Error = -1

Subscribe to changes in currency buy and sell prices

Request

{
    "type": 1,
    "data": {
        "ticker": "ethusdt"
    }
}

Response

{
    "id": "17428ac3-43f4-4362-9d3a-7e25cf011ae9",
    "type": 1,
    "data": {
        "ticker": "ethusdt"
    }
}

Type Subscribe = 1

Unsubscribe from changes in currency buy and sell prices

Request

{
    "type": 2,
    "data": {
        "ticker": "ethusdt"
    }
}

Response

{
    "id": "17428ac3-43f4-4362-9d3a-7e25cf011ae9",
    "type": 2,
    "data": {
        "ticker": "ethusdt"
    }
}

Type UnSubscribe = 2

Price change messages

Messages are sent only if there was a subscription to the ticker.

{
    "id": "1155b20d-017b-494f-b96c-b6d1913d1120",
    "type": 4,
    "data": {
        "ticker": "ethusdt",
        "symbolId": 2,
        "providerId": 5,
        "priceSell": 3329.82,
        "priceBuy": 3329.81
    }
}

Type SymbolPriceChange = 4

Russian version

Real-time Cryptocurrency Exchange Data Aggregator - система для сбора и сравнения данных о лучших ценах в стаканах заявок с ведущих криптовалютных бирж в режиме реального времени.

✨ Особенности

  • 🔌 Поддержка 7+ бирж: Единый интерфейс для работы с BingX, Bitget, BitMart, ByBit, GateIo, Mexc, XT.com
  • ⚡ Режим реального времени: WebSocket подключения для мгновенного получения обновлений стаканов
  • 💾 Двойное хранение: PostgreSQL для исторических данных + Cache для кэширования
  • 🌐 Полноценный API: REST API
  • 🐳 Готовая Docker инфраструктура: Полная контейнеризация с Docker Compose
  • 📊 Агрегация данных: Сбор и нормализация данных с разных бирж в единый формат
  • 🔄 Автоматическое восстановление: Устойчивые подключения с автоматическим переподключением

🏗️ Архитектура

┌─────────────────────────────────────────────────────────┐
│                    Client Applications                  │
│  ┌──────────┐  ┌──────────┐  ┌──────────┐               │
│  │ Web App  │  │ Mobile   │  │  Desktop │               │
│  └──────────┘  └──────────┘  └──────────┘               │
└─────────────────┬─────────────────┬─────────────────────┘
                  │                 │
           REST API (HTTP)   WebSocket (WS)
                  │                 │
          ┌───────▼─────────────────▼────────┐
          │      Crypto.Compare API Gateway  │
          │  ┌─────────────┐ ┌─────────────┐ │
          │  │ REST Contr. │ │ WS Handler  │ │
          │  └─────────────┘ └─────────────┘ │
          └──────────────┬─────────────────┬─┘
                         │                 │
                ┌────────▼─────┐ ┌─────────▼─────┐
                │   Cache      │ │ PostgreSQL    │
                │              │ │               │
                └──────────────┘ └───────────────┘
                         │
                  ┌──────▼─────────────────────┐
                  │   Exchange Data Collectors │
                  │  ┌────┐ ┌────┐ ┌────┐      │
                  │  │Bing│ │Bitg│ │BitM│  ... │
                  │  │ X  │ │ et │ │ art│      │
                  │  └────┘ └────┘ └────┘      │
                  └────────────────────────────┘

🛠️ Технологический стек

  • Платформа: .NET 10, ASP.NET Core Web API
  • Базы данных: PostgreSQL (основное хранилище), in-memory кэш
  • Контейнеризация: Docker, Docker Compose
  • ORM: Entity Framework Core
  • Конфигурация: appsettings.json, переменные окружения
  • Логирование: Log4net с консольным и файловым выводом
  • Кэширование: In-memory кэш
  • Документация API: Swagger/OpenAPI

🚀 Быстрый старт

  1. Клонируйте репозиторий:
git clone https://github.com/dmitry575/Crypto.Compare.git
cd Crypto.Compare
  1. Запуск приложения в докере
docker-compose -f docker-compose.tests.yml down
docker-compose -f docker-compose.tests.yml build api-public sql 
docker-compose -f docker-compose.tests.yml run --rm start_dependencies
docker-compose -f docker-compose.tests.yml up -d api-public 
  1. Откройте документацию API:

Swagger UI: http://localhost:18072/swagger

Для Windows

Достаточно запусть файл: docker-start.cmd

Добавление данных о биржах

Т.к. все данные о доступах к биржам хранятся в базе данных, необходимо добавить нужные записи. После запуска в докер контейнере всех образов, можно подключиться к Adminer для управления просмотра и добавления записей в базе данных. Нужно выбрать:

  • System: Posgresql
  • Server: sql
  • Username: postgres
  • Password: test

Добавить данные для подключения к биржам

MEXC

INSERT INTO public."Providers"(
            "Name", "WebSite", "BaseUrl", "AccessKey", "SecretKey", "Status", "CreatedAt", "UpdatedAt")
    VALUES ('mexc', 'https://mexc.com', 'https://api.mexc.com', 'AccessKey', 'SecretKey', 1,NOW(), NOW());

Нужно заменить в запросе: AccessKey и SecretKey - на ключи с личного кабинета биржи

XT

INSERT INTO public."Providers"(
            "Name", "WebSite", "BaseUrl", "AccessKey", "SecretKey", "Status", "CreatedAt", "UpdatedAt")
    VALUES ('xtcom', 'https://xt.com', 'https://sapi.xt.com', 'AccessKey', 'SecretKey', 1,NOW(), NOW());

Нужно заменить в запросе: AccessKey и SecretKey - на ключи с личного кабинета биржи

BYBIT

INSERT INTO public."Providers"(
            "Name", "WebSite", "BaseUrl", "AccessKey", "SecretKey", "Status", "CreatedAt", "UpdatedAt")
    VALUES ('bybit', 'https://bybit.com', 'https://api.bybit.com', 'AccessKey', 'SecretKey', 1,NOW(), NOW());

Нужно заменить в запросе: AccessKey и SecretKey - на ключи с личного кабинета биржи

BINGX

INSERT INTO public."Providers"(
            "Name", "WebSite", "BaseUrl", "AccessKey", "SecretKey", "Status", "CreatedAt", "UpdatedAt")
    VALUES ('bingx', 'https://bingx.com', 'https://open-api.bingx.com', 'AccessKey', 'SecretKey', 1,NOW(), NOW());

Нужно заменить в запросе: AccessKey и SecretKey- на ключи с личного кабинета биржи

BITGET

INSERT INTO public."Providers"(
            "Name", "WebSite", "BaseUrl", "AccessKey", "SecretKey", "Status", "CreatedAt", "UpdatedAt", "PasswordKey")
    VALUES ( 'bitget', 'https://bitget.com', 'https://api.bitget.com', 'AccessKey', 'SecretKey', 1,NOW(), NOW(), 'PasswordKey');

Нужно заменить в запросе: AccessKey и SecretKey, PasswordKey - на ключи с личного кабинета биржи

GATEIO

INSERT INTO public."Providers"(
            "Name", "WebSite", "BaseUrl", "AccessKey", "SecretKey", "Status", "CreatedAt", "UpdatedAt", "PasswordKey")
    VALUES ( 'gateio',  'https://gateio.ws', 'https://api.gateio.ws', 'AccessKey', 'SecretKey', 1,NOW(), NOW(), '');

Нужно заменить в запросе: AccessKey и SecretKey - на ключи с личного кабинета биржи

BITMART

INSERT INTO public."Providers"(
            "Name", "WebSite", "BaseUrl", "AccessKey", "SecretKey", "Status", "CreatedAt", "UpdatedAt", "PasswordKey")
    VALUES ( 'bitmart',  'https://bitmart.com', 'https://api-cloud.bitmart.com', 'AccessKey', 'SecretKey', 1,NOW(), NOW(), '');

Нужно заменить в запросе: AccessKey и SecretKey - на ключи с личного кабинета биржи

BINANCE

INSERT INTO public."Providers"(
            "Name", "WebSite", "BaseUrl", "AccessKey", "SecretKey", "Status", "CreatedAt", "UpdatedAt")
    VALUES ('binance', 'https://binance.com', 'https://api.binance.com', 'AccessKey', 'SecretKey', 1,NOW(), NOW());

Нужно заменить в запросе: AccessKey и SecretKey - на ключи с личного кабинета биржи

Получение API ключей для бирж

About

Web socket connection to crypto market and get the best price to sell or buy

Resources

License

Stars

Watchers

Forks

Releases

No releases published

Packages

 
 
 

Contributors

Languages