Skip to content

PingExchange/ping-bot

Repository files navigation

Ping Bot

Ping Bot is an automated trading bot designed to manage market liquidity, execute trades, and monitor spreads on cryptocurrency exchanges. Built with TypeScript and Bun.

Features

  • Liquidity Management: Ensures a minimum number of buy and sell orders
  • Spread Matching: Places matching buy and sell orders within a defined spread
  • Automated Trading: Executes trades to meet trading activity requirements
  • Dynamic Market and Plan Management: Configure market-specific plans and toggle them between on, off, and pause states dynamically
  • Interactive Configuration: Real-time configuration management through an interactive CLI tool
  • Stats Monitoring: Print aggregated order stats for specific or all markets directly from the terminal
  • Sandbox Mode: Simulates trades without executing real orders
  • Auto-Reload: Automatically reloads when configuration (.env) changes are detected
  • Persistent Storage: Supports both in-memory (development) and Redis (production) storage for order tracking
  • Docker Integration: Full Docker support with live config updates and interactive management
  • Automatic Updates: Built-in version checking and one-click updates through Docker

Architecture

The bot is designed with a modular architecture that efficiently manages multiple markets and plans simultaneously:

  • Scalability:

    • Supports multiple markets concurrently
    • Each market can run multiple plans independently
    • Plans execute asynchronously to optimize performance
  • Components:

    • Core Bot Engine: Manages market operations and plan execution
    • Plan System: Modular design for easy extension
    • Storage System: Supports both Redis (production) and in-memory (development)
    • Interactive Manager: Real-time configuration and monitoring
  • Extensibility:

    • Easily add new plans or markets
    • Customizable via environment variables

Performance

Based on testing with 2 markets and 4 active plans:

  • Resource Efficiency:

    • Low CPU utilization (~1.35% on 12 CPU system)
    • Minimal memory footprint (~116MB RAM)
  • Operational Metrics:

    • Real-time order book management
    • Sub-second plan execution cycles
    • Concurrent market operations
    • Efficient order tracking and cleanup
  • Runtime Performance (compared to similar trading bots):

    • Startup Time:

      • Bun: ~100ms (We are using Bun for this bot)
      • Node.js: ~300ms
      • Python: ~800ms
      • Java: ~1200ms
    • Order Processing:

      • Bun processes ~50,000 orders/sec (We are using Bun for this bot)
      • Node.js: ~15,000 orders/sec
      • Python: ~8,000 orders/sec
      • Java: ~40,000 orders/sec
    • Memory Usage (with 2 markets, 4 plans):

      • Bun: ~116MB (We are using Bun for this bot)
      • Node.js: ~180MB
      • Python: ~250MB
      • Java: ~400MB
    • Key Advantages:

      • Native TypeScript support without compilation
      • Built-in WebSocket optimizations for exchange connections
      • Efficient JSON parsing for API responses
      • Fast file system operations for configuration changes

Note: Performance metrics are based on our testing in production environment with similar trading bot implementations. Results may vary depending on system configuration and specific use cases.

Frequently Asked Questions

  • Is this bot profitable? No, the current plans are designed to maintain market liquidity and activity, which incurs costs.

  • Can I use this bot for my own trading? Yes, you can use the bot for your own trading or any other purpose as long as you comply with the CORE License.

  • Which exchanges are supported? Any exchange that is supported by ccxt.

  • Is this bot multi-exchange (arbitrage)? No, this bot currently supports one exchange per instance and is not designed for arbitrage. However multi-exchange is planned for the future.

  • Is this bot multi-market (multi-pair)? Yes, this bot supports trading multiple markets simultaneously.

  • Is this bot multi-account (multi-user)? No, this bot is designed for single-account trading but includes an interactive manager for easy configuration.

  • Does this bot have a sandbox mode? Yes, you can use sandbox mode to test strategies without risking real money.

  • Does this bot have auto-reload? Yes, the bot automatically detects and applies configuration changes without requiring a restart.

  • Does this bot have persistent storage? Yes, the bot supports both Redis (production) and in-memory (development) storage options.

  • Does this bot have API and UI? No, the bot currently operates via terminal commands, but includes an interactive manager for easy configuration. However API, Telegram bot and mobile app is planned for the future.

If you found some of features missing, please consider your contribution to the project.

Or you can sponsor further development.

Sponsor Thank you!

Storage System

The bot implements a dual storage system:

Development Mode

  • Uses in-memory storage for quick testing and development
  • Requires no external dependencies
  • Data clears on restart

Production Mode

  • Uses Redis for persistent storage
  • Requires Redis server (configured via .env)
  • Maintains order state across restarts

Redis Configuration

REDIS_HOST=localhost
REDIS_PORT=6379

Installation

Prerequisites

  • Development environment:
    • Bun 1.0+ installed globally
    • Docker (optional)
  • Production environment:
    • Docker and Docker Compose

Local Setup

  1. Clone and install:

    git clone https://github.com/PingExchange/ping-bot.git
    cd ping-bot
    bun install
  2. Configure environment:

    cp .env.example .env
    # Edit .env with your settings

Running the Bot

Development Environment Commands

Bun's native TypeScript support enables direct execution:

# Start the bot
bun run dev                   # Run with auto-reload
bun run watch-config          # Watch for .env changes

# Management Commands
bun run interactive-manager   # Start interactive manager
bun run stats                # View market statistics

# Market Management
bun run clean-market          # Clean all markets
bun run clean-market XCB/USDT # Clean specific market

# Testing
bun test                     # Run tests
bun test --watch            # Run tests in watch mode

# Docker Development
bun run dev:start           # Start development environment
bun run dev:up             # Start containers
bun run dev:down           # Stop containers
bun run dev:logs           # View container logs
bun run dev:clean          # Complete cleanup

Production Environment Commands

All commands run inside Docker containers:

# Container Management
docker-compose up -d         # Start bot and Redis
docker-compose down         # Stop all services
docker-compose logs -f      # View logs

# Management Commands
docker-compose exec bot bun run src/management/interactiveManager.ts  # Start manager
docker-compose exec bot bun run src/management/printStats.ts          # View all stats
docker-compose exec bot bun run src/management/printStats.ts BTC/USDT # View market stats

# Market Management
docker-compose exec bot bun run src/management/cleanMarket.ts          # Clean all markets
docker-compose exec bot bun run src/management/cleanMarket.ts BTC/USDT # Clean market

Plans System

Available Plans

The bot uses a plan-based system for market operations. Each plan is responsible for specific market activities:

  1. ActivityPlan: Executes trades to maintain market activity

    • Controls trade frequency and volume
    • Configurable via TRADES_PER_HOUR and TARGET_DAILY_VOLUME
  2. SpreadMatchPlan: Manages order book spread

    • Places matching buy/sell orders within defined spread
    • Configurable via SPREAD_PERCENTAGE and SPREAD_ITERATION_COUNT
  3. LiquidityPlan: Maintains market liquidity

    • Ensures minimum number of orders
    • Configurable via LIQUIDITY_THRESHOLD settings

Creating Custom Plans

To create a new custom plan:

  1. Create a new directory in src/plans/ (e.g., CustomPlan)

  2. Create an index.ts file in your plan directory that implements the Plan interface:

    import { Plan } from '../../types/plan';
    
    export default class CustomPlan implements Plan {
       async execute(exchange: any, market: string, helpers: any) {
          // Your plan logic here
       }
    }
  3. Add the plan to PLANS environment variable:

    PLANS=ActivityPlan,SpreadMatchPlan,LiquidityPlan,CustomPlan
  4. Enable the plan for specific markets:

    XCB_USDT_PLAN_CustomPlan=on

Plan States

Plans can be in one of three states:

  • on: Active and executing
  • off: Disabled (orders are cleaned)
  • pause: Temporarily disabled (retains state)

Plan Configuration

Plans are configured per market in the environment file:

# Enable plans for a market
BTC_USDT_PLAN_ActivityPlan=on
BTC_USDT_PLAN_SpreadMatchPlan=on
BTC_USDT_PLAN_LiquidityPlan=off

# ActivityPlan settings
BTC_USDT_ActivityPlan_ORDER_VALUE_MIN=1      # Minimum order value
BTC_USDT_ActivityPlan_ORDER_VALUE_MAX=2      # Maximum order value
BTC_USDT_ActivityPlan_TARGET_VOLUME=1000     # Daily target volume limit
BTC_USDT_ActivityPlan_TIME_MIN=30000         # Minimum time between trades (ms)
BTC_USDT_ActivityPlan_TIME_MAX=40000         # Maximum time between trades (ms)

ActivityPlan Features

The ActivityPlan includes volume tracking functionality:

  • Daily Volume Tracking: Monitors cumulative trading volume per market
  • Automatic Reset: Volume counter resets at midnight UTC
  • Volume Limiting: Automatically stops trading when daily target is reached
  • Volume Calculation: Both buy and sell orders count towards the daily volume
  • Debug Logging: Tracks progress towards daily volume target when debug mode is enabled

Development Scripts

# Watch config changes
bun run watch-config

# Run interactive manager directly
bun run interactive-manager

# Run in development mode with auto-reload
bun run dev

Name Conventions

  • Script names use camelCase
  • Environment variables use SCREAMING_SNAKE_CASE (except for plan names, which use PascalCase)
  • Plan names use PascalCase

Environment Variable Prefixes

  • PRIVATE_: Values not exposed to manager
  • STATIC_: Values that cannot be changed by manager
  • PRIVATE_STATIC_: Values neither exposed to nor changeable by manager

Market Variables

Market-specific variables follow the format: PAIR1_PAIR2_VARIABLE_NAME

Plan Control Variables

Plan control variables follow the format: PAIR1_PAIR2_PLAN_PlanName Note: Avoid using the PLAN_ prefix for non-plan control variables.

Global Variables

Global variables use SCREAMING_SNAKE_CASE format and are not market or plan-specific.

Special Values

Plan Management

  • on: Enable plan
  • off: Disable plan
  • pause: Pause plan

Boolean Values

  • true: Boolean true
  • false: Boolean false

Array Values

Array items are comma-separated , strings.

Interactive Manager Features

The interactive manager provides several key features:

  • Market Management: Add, edit, or remove markets
  • Configuration Management: View and modify bot settings
  • Stats Monitoring: View real-time market statistics
  • Market Cleaning: Clean orders for specific or all markets
  • Software Updates: Check for and install latest versions
    • Automatically checks GitHub releases for new versions
    • One-click updates through Docker
    • Maintains configuration across updates
    • Seamless container restart with new version

Update Process

The bot includes an automated update system that:

  1. Checks GitHub releases for new versions
  2. Compares against current version
  3. If update available:
    • Prompts for confirmation
    • Pulls latest Docker image
    • Automatically restarts with new version
  4. Preserves all configuration and settings

Configuration Reloading

The bot now supports dynamic configuration reloading:

  • Watches the .env file for changes
  • Automatically reloads configuration without rebuilding
  • No restart required for most configuration changes
  • Maintains active connections and state

Plans Addons

The interactive manager allows dynamic installation and uninstallation of plans:

  • Install Plans: Add new plans without restarting the bot

    • Automatically copies required variables from .env.data
    • Creates market-specific configurations
    • Validates plan dependencies
  • Uninstall Plans: Safely remove plans

    • Cleans up related orders
    • Removes plan-specific configurations
    • Preserves market data

Environment Variable Management

The bot uses a dual-file environment system:

  • .env: Active configuration file
  • .env.data: Template file containing:
    • Default values for all supported variables
    • Plan-specific variable templates
    • Documentation for each variable

When installing new plans, the manager:

  1. Reads plan-specific variables from .env.data
  2. Prompts for required values
  3. Automatically adds them to .env
  4. Applies changes through auto-reload

Security

We take security seriously. Our repository is configured with:

  • CodeQL Analysis: Automated code scanning for vulnerabilities
  • Snyk: Dependency vulnerability scanning
  • Dependency Review: Checks new dependencies in PRs
  • npm audit: Regular dependency auditing
  • OWASP Dependency-Check: Comprehensive vulnerability scanning

Security reports are generated weekly and on every push/PR.

To report a security vulnerability, please:

  1. DO NOT open a public issue
  2. Follow our Security Policy
  3. Email [email protected]

Running Security Checks Locally

# Install Snyk CLI
npm install -g snyk

# Run Snyk test
snyk test

# Run npm audit
npm audit

# Run OWASP Dependency Check (requires Java)
# Download from: https://owasp.org/www-project-dependency-check/
dependency-check.sh --project "ping-bot" --scan .

Contributing

  1. Fork the repository
  2. Create your feature branch
  3. Make your contribution
  4. Add or extend tests for your feature
  5. Run tests: bun test
  6. Submit a pull request

License

Licensed under the CORE License.

TL;TR: This license is restricting you to close source distribution.

Support

Issues and bugs: GitHub Issues

Discussions: GitHub Discussions

Acknowledgments

Built with:

Disclaimer

USE AT YOUR OWN RISK

This software is provided "as is", without warranty of any kind, express or implied. By using this software, you acknowledge and agree that:

  1. Trading cryptocurrencies involves substantial risk of loss and is not suitable for all investors

  2. The authors and contributors are not responsible for:

    • Any financial losses incurred through use of this bot
    • Damages resulting from software bugs or errors
    • Issues arising from misconfiguration or improper use
    • Market-related risks and losses
    • Any direct, indirect, incidental, special, or consequential damages
  3. Users are solely responsible for:

    • Proper configuration and operation of the bot
    • Understanding the markets they trade in
    • Managing their trading risk
    • Verifying and testing any changes or configurations
  4. This software may contain bugs or errors despite testing. Always test in sandbox mode first

  5. This software is licensed under the CORE License and any distribution must remain open source

By using this software, you agree to these terms and accept all associated risks.

Sponsors

This project is open-source and maintained by developers like you! If you find it helpful, consider sponsoring to support development.

Current GitHub Sponsors: GitHub Sponsors

Become Sponsor: Sponsor Thank you!