Skip to content

A comprehensive Discord bot for risk-free cryptocurrency trading simulation with real-time market data, portfolio management, and educational features.

Notifications You must be signed in to change notification settings

Dev-Adnani/trading-bot-discord

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

4 Commits
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

🤖 SimChain - Discord Paper Trading Crypto Bot

A comprehensive Discord bot for risk-free cryptocurrency trading simulation with real-time market data, portfolio management, and educational features.

TypeScript Discord.js MongoDB Node.js

📋 Table of Contents

✨ Features

🔄 Core Trading

  • Virtual Trading Environment - Practice crypto trading with $10,000 starting balance
  • Real-time Market Data - Live cryptocurrency prices from CoinGecko API
  • Portfolio Management - Track holdings, P&L, and performance metrics
  • Advanced Order Types - Buy/sell with amounts, percentages, or dollar values

📊 Analytics & Insights

  • Comprehensive Statistics - Detailed performance analytics and trading metrics
  • Profit/Loss Tracking - Real-time P&L calculations with visual feedback
  • Portfolio Breakdown - Asset allocation and net worth analysis
  • Trading History - Complete transaction log with timestamps

🎓 Educational Features

  • Interactive Tips System - 6 categories of trading education (Beginner, Risk, Strategy, Analysis, Psychology, Mistakes)
  • Performance Insights - Personalized feedback based on trading performance
  • Risk-free Learning - Learn trading psychology without financial risk

🏆 Social Features

  • Leaderboards - Compete with other traders based on portfolio value
  • Community Engagement - Share and compare trading strategies
  • Account Management - Reset functionality for fresh starts

🛡️ Robust Infrastructure

  • Data Persistence - MongoDB integration for reliable data storage
  • Error Handling - Comprehensive validation and error management
  • Caching System - Intelligent API caching to respect rate limits
  • Type Safety - Full TypeScript implementation

🎮 Commands

🔄 Core Trading Commands

Command Description Usage
/start Create your trading account /start
/balance View account summary /balance
/buy Purchase cryptocurrency /buy BTC 0.01 or /buy ETH $500 or /buy ADA 25%
/sell Sell cryptocurrency holdings /sell BTC 50% or /sell ETH 100%

📊 Portfolio & Market Commands

Command Description Usage
/portfolio View your holdings /portfolio
/prices Check market prices /prices BTC ETH or /prices (top 10)
/leaderboard View top traders /leaderboard

📈 Analytics Commands

Command Description Usage
/stats Detailed account statistics /stats
/pnl Profit/loss analysis /pnl
/networth Asset allocation breakdown /networth

🛠️ Utility Commands

Command Description Usage
/history Trading transaction history /history
/reset Reset your account /reset
/tips Educational trading tips /tips beginner or /tips (random)

🚀 Installation

Prerequisites

  • Node.js (v18 or higher)
  • MongoDB (v5.0 or higher)
  • Discord Bot Token
  • CoinGecko API (free tier)

1. Clone the Repository

git clone https://github.com/Dev-Adnani/trading-bot-discord.git
cd trading-bot-discord

2. Install Dependencies

npm install

3. Environment Setup

Create a .env file based on .env.example:

cp .env.example .env

4. Build the Project

npm run build

5. Start the Bot

npm start

For development with auto-reload:

npm run dev

⚙️ Configuration

Create a .env file in the root directory with the following variables:

# Discord Bot Configuration
DISCORD_TOKEN=your_discord_bot_token_here
CLIENT_ID=your_discord_application_id_here
GUILD_ID=your_discord_server_id_here

# MongoDB Configuration
MONGODB_URI=mongodb://localhost:27017/simchain
# OR for MongoDB Atlas:
# MONGODB_URI=mongodb+srv://username:password@cluster.mongodb.net/simchain

# CoinGecko API (Optional - uses free tier by default)
COINGECKO_API_KEY=your_coingecko_api_key_here

# Bot Configuration
STARTING_BALANCE=10000
CACHE_TIMEOUT=60000

Discord Bot Setup

  1. Create Discord Application

  2. Create Bot User

    • Go to "Bot" section in your application
    • Click "Add Bot"
    • Copy the token for DISCORD_TOKEN
    • Enable required intents (Message Content Intent)
  3. Invite Bot to Server

    • Go to "OAuth2" > "URL Generator"
    • Select scopes: bot, applications.commands
    • Select permissions: Send Messages, Use Slash Commands, Embed Links
    • Use generated URL to invite bot to your server

MongoDB Setup

Option 1: Local MongoDB

# Install MongoDB locally
# Ubuntu/Debian
sudo apt install mongodb

# macOS with Homebrew
brew install mongodb/brew/mongodb-community

# Start MongoDB service
sudo systemctl start mongodb  # Linux
brew services start mongodb/brew/mongodb-community  # macOS

Option 2: MongoDB Atlas (Recommended)

  1. Create account at MongoDB Atlas
  2. Create a new cluster
  3. Get connection string and replace in MONGODB_URI

🏗️ Architecture

Project Structure

src/
├── index.ts                 # Application entry point
├── client/
│   └── bot_client.ts       # Discord client configuration
├── commands/               # Slash command implementations
│   ├── trading/           # Trading commands (start, buy, sell, balance)
│   ├── portfolio/         # Portfolio commands (portfolio, prices, leaderboard)
│   ├── analytics/         # Analytics commands (stats, pnl, networth)
│   └── utility/           # Utility commands (history, reset, tips)
├── services/              # Business logic services
│   ├── database.ts        # MongoDB operations
│   ├── coingecko.ts      # CoinGecko API integration
│   └── trading.ts        # Trading logic and calculations
├── models/                # Data models and interfaces
│   ├── User.ts           # User account model
│   ├── Portfolio.ts      # Portfolio holding model
│   └── Trade.ts          # Trade transaction model
├── utils/                 # Utility functions
│   ├── formatters.ts     # Currency and number formatting
│   ├── validators.ts     # Input validation
│   └── constants.ts      # Application constants
└── listeners/            # Event listeners
    └── ready.ts          # Bot ready event handler

Core Services

DatabaseService - Handles all MongoDB operations:

  • User account management
  • Portfolio tracking
  • Trade recording
  • Analytics and leaderboards

CoinGeckoService - Real-time cryptocurrency data:

  • Price fetching with caching
  • Multi-symbol batch requests
  • Rate limit management
  • Symbol mapping and validation

TradingService - Trading logic orchestration:

  • Buy/sell order execution
  • Portfolio calculations
  • P&L tracking
  • Balance management

🔌 API Integration

CoinGecko API

  • Free Tier: 50 calls/minute, 10,000 calls/month
  • Caching: 1-minute cache to optimize API usage
  • Supported Symbols: 25+ major cryptocurrencies
  • Features: Real-time prices, market data, historical data

MongoDB Collections

  • users: User accounts and balances
  • portfolios: Individual cryptocurrency holdings
  • trades: Transaction history and audit trail

🎯 Usage Examples

Basic Trading Flow

# 1. Create account
/start

# 2. Check available balance
/balance

# 3. Buy cryptocurrency
/buy BTC 0.01          # Buy 0.01 BTC
/buy ETH $500          # Buy $500 worth of ETH
/buy ADA 25%           # Invest 25% of balance in ADA

# 4. Check portfolio
/portfolio

# 5. Sell holdings
/sell BTC 50%          # Sell 50% of BTC holdings
/sell ETH 100%         # Sell all ETH

# 6. View performance
/pnl                   # Check profit/loss
/stats                 # Detailed statistics

Educational Features

# Get trading tips by category
/tips beginner         # Basic trading concepts
/tips risk            # Risk management
/tips psychology      # Trading psychology
/tips strategy        # Trading strategies

# Get random tip
/tips

Portfolio Analysis

# View holdings breakdown
/networth             # Asset allocation pie chart

# Check market prices
/prices               # Top 10 cryptocurrencies
/prices BTC ETH ADA   # Specific symbols

# Compare with others
/leaderboard          # Top 10 traders

🛠️ Development

Scripts

npm run build         # Compile TypeScript
npm run start         # Start production bot
npm run dev          # Development with rebuild
npm run watch        # Watch mode compilation
npm test             # Run tests (TODO)

Adding New Commands

  1. Create command file in appropriate /commands subdirectory
  2. Extend Command class from Sapphire Framework
  3. Implement registerApplicationCommands and chatInputRun methods
  4. Add validation and error handling
  5. Use services for business logic

Adding New Cryptocurrencies

Update the symbol mapping in src/services/coingecko.ts:

private symbolToId: { [key: string]: string } = {
  'NEW': 'new-crypto-id',
  // Add new mappings here
};

🤝 Contributing

  1. Fork the repository
  2. Create a feature branch (git checkout -b feature/amazing-feature)
  3. Commit your changes (git commit -m 'Add some amazing feature')
  4. Push to the branch (git push origin feature/amazing-feature)
  5. Open a Pull Request

Contribution Guidelines

  • Follow TypeScript best practices
  • Add comprehensive error handling
  • Include JSDoc comments for functions
  • Maintain consistent code formatting
  • Test thoroughly before submitting

📊 Performance Metrics

The bot is designed to handle:

  • Concurrent Users: 100+ simultaneous traders
  • API Calls: Optimized for CoinGecko free tier limits
  • Database: Efficient queries with proper indexing
  • Response Time: <2 seconds for most commands

🔒 Security Features

  • Input Validation: All user inputs are validated and sanitized
  • Rate Limiting: API calls are cached and rate-limited
  • Error Handling: Graceful error handling prevents crashes
  • Data Integrity: Atomic database operations for consistency

🐛 Troubleshooting

Common Issues

Bot doesn't respond to commands:

  • Check bot permissions in Discord server
  • Verify DISCORD_TOKEN and CLIENT_ID in .env
  • Ensure bot has required intents enabled

Database connection errors:

  • Verify MongoDB is running (local) or connection string (Atlas)
  • Check network connectivity
  • Validate MONGODB_URI format

API rate limit errors:

  • CoinGecko free tier: 50 calls/minute
  • Bot implements caching to minimize API calls
  • Consider upgrading to CoinGecko Pro for higher limits

Commands not updating:

  • Run npm run build after code changes
  • Restart bot process
  • Clear Discord cache if needed

📄 License

This project is licensed under the ISC License - see the LICENSE file for details.

🙏 Acknowledgments

  • CoinGecko - Reliable cryptocurrency market data
  • Discord.js - Powerful Discord bot framework
  • Sapphire Framework - Excellent command handling
  • MongoDB - Robust data persistence
  • TypeScript - Type-safe development experience

📞 Support


Disclaimer: This bot is for educational purposes only. All trading is simulated with virtual money. Past performance does not guarantee future results. Always do your own research before making real financial decisions.

Built with ❤️ by the SimChain Team

About

A comprehensive Discord bot for risk-free cryptocurrency trading simulation with real-time market data, portfolio management, and educational features.

Topics

Resources

Stars

Watchers

Forks