A comprehensive Discord bot for risk-free cryptocurrency trading simulation with real-time market data, portfolio management, and educational features.
- Features
- Commands
- Installation
- Configuration
- Usage
- Architecture
- API Integration
- Contributing
- License
- 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
- 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
- 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
- Leaderboards - Compete with other traders based on portfolio value
- Community Engagement - Share and compare trading strategies
- Account Management - Reset functionality for fresh starts
- 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
| 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% |
| Command | Description | Usage |
|---|---|---|
/portfolio |
View your holdings | /portfolio |
/prices |
Check market prices | /prices BTC ETH or /prices (top 10) |
/leaderboard |
View top traders | /leaderboard |
| Command | Description | Usage |
|---|---|---|
/stats |
Detailed account statistics | /stats |
/pnl |
Profit/loss analysis | /pnl |
/networth |
Asset allocation breakdown | /networth |
| Command | Description | Usage |
|---|---|---|
/history |
Trading transaction history | /history |
/reset |
Reset your account | /reset |
/tips |
Educational trading tips | /tips beginner or /tips (random) |
- Node.js (v18 or higher)
- MongoDB (v5.0 or higher)
- Discord Bot Token
- CoinGecko API (free tier)
git clone https://github.com/Dev-Adnani/trading-bot-discord.git
cd trading-bot-discordnpm installCreate a .env file based on .env.example:
cp .env.example .envnpm run buildnpm startFor development with auto-reload:
npm run devCreate 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-
Create Discord Application
- Go to Discord Developer Portal
- Click "New Application" and give it a name
- Copy the Application ID for
CLIENT_ID
-
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)
-
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
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 # macOSOption 2: MongoDB Atlas (Recommended)
- Create account at MongoDB Atlas
- Create a new cluster
- Get connection string and replace in
MONGODB_URI
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
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
- 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
- users: User accounts and balances
- portfolios: Individual cryptocurrency holdings
- trades: Transaction history and audit trail
# 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# 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# 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 tradersnpm 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)- Create command file in appropriate
/commandssubdirectory - Extend
Commandclass from Sapphire Framework - Implement
registerApplicationCommandsandchatInputRunmethods - Add validation and error handling
- Use services for business logic
Update the symbol mapping in src/services/coingecko.ts:
private symbolToId: { [key: string]: string } = {
'NEW': 'new-crypto-id',
// Add new mappings here
};- Fork the repository
- Create a feature branch (
git checkout -b feature/amazing-feature) - Commit your changes (
git commit -m 'Add some amazing feature') - Push to the branch (
git push origin feature/amazing-feature) - Open a Pull Request
- Follow TypeScript best practices
- Add comprehensive error handling
- Include JSDoc comments for functions
- Maintain consistent code formatting
- Test thoroughly before submitting
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
- 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
Bot doesn't respond to commands:
- Check bot permissions in Discord server
- Verify
DISCORD_TOKENandCLIENT_IDin.env - Ensure bot has required intents enabled
Database connection errors:
- Verify MongoDB is running (local) or connection string (Atlas)
- Check network connectivity
- Validate
MONGODB_URIformat
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 buildafter code changes - Restart bot process
- Clear Discord cache if needed
This project is licensed under the ISC License - see the LICENSE file for details.
- 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
- GitHub Issues: Report bugs or request features
- Discord: Join our community server for support
- Documentation: Check the Wiki for detailed guides
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