An intelligent cryptocurrency trading bot that uses AI analysis to make data-driven trading decisions on Coinbase Advanced Trade.
This bot prioritizes AI-driven market analysis over rigid portfolio rebalancing, allowing for:
- Market-responsive trading based on technical indicators and trends
- Dynamic position sizing that adapts to confidence levels and market conditions
- Smart safety limits that protect your portfolio without blocking profitable trades
- Momentum-based strategies that can ride winners and cut losers
- Advanced LLM Analysis: Uses Google's Gemini 2.5 Pro for market analysis
- Technical Indicators: RSI, MACD, Bollinger Bands, Moving Averages
- Market Sentiment: Analyzes price trends, volume, and volatility
- Confidence Scoring: 0-100% confidence levels for each trading decision
- AI Priority: Market analysis drives all trading decisions
- Dynamic Position Sizing: Trade sizes adapt to confidence (10-25% of balance)
- Intelligent Rebalancing: Automatic portfolio rebalancing every 3 hours based on market conditions
- Safety Limits: Minimum β¬50 EUR balance, 3% minimum crypto allocation
- Real-time Trade Alerts: Instant notifications for BUY/SELL executions
- Error Notifications: Critical error alerts with context
- Portfolio Summaries: Daily portfolio performance updates
- Bot Status Updates: Startup, shutdown, and status notifications
- Dual-Layer System: Static risk configuration + dynamic market assessment
- Confidence Thresholds: 70% minimum confidence for BUY/SELL decisions
- Position Sizing: Risk-adjusted trade sizes (HIGH=50% reduction, MEDIUM=25%, LOW=0%)
- Market Volatility: Real-time assessment (high/medium/low) affects trading decisions
- Balance Protection: Maintains minimum balances for continued trading
- Diversification: Prevents over-concentration in any single asset
π Complete Risk Management Guide β
- Real-time Portfolio Tracking: Live EUR values and allocations
- Comprehensive AI Analysis: Detailed reasoning for each trade decision with 4 analysis sections
- Performance Metrics: P&L tracking, win rates, portfolio growth
- Market Overview: Current prices, trends, and technical indicators
Phase 1 (Critical Components): ββββββββββββββββββββ 100% (5/5)
Phase 2 (Core Functionality): ββββββββββββββββββββ 20% (1/5)
Phase 3 (Integration & E2E): ββββββββββββββββββββ 0% (0/5)
Phase 4 (Specialized Testing): ββββββββββββββββββββ 0% (0/7)
Overall Test Suite Progress: ββββββββββββββββββββ 31.8% (7/22)
-
β Configuration Management (
test_config.py
) - 100% coverage - 37 tests- Environment variable parsing and validation
- Trading pairs and allocation calculations
- Risk management settings
- Backward compatibility
-
β Coinbase Client (
test_coinbase_client.py
) - 53% coverage - 38 tests- Client initialization and credential validation
- Rate limiting and error handling
- Account operations and balance retrieval
- Market data operations and price fetching
- Trading operations and order placement
- Precision handling for different trading pairs
- Notification integration and error recovery
-
β Trading Strategy (
test_trading_strategy.py
) - Core functionality - 14 tests- Strategy initialization and configuration
- Trading decision logic with technical indicators
- Risk management and confidence thresholds
- Position sizing calculations
- Portfolio management operations
- Error handling and edge cases
-
β Risk Management (
test_risk_management.py
) - Comprehensive coverage - 32 tests- Risk level configuration and multipliers
- Confidence threshold enforcement
- Balance and safety checks
- Smart trading limits and portfolio protection
- Position sizing with risk management
- Confidence adjustments based on technical indicators
- Integrated risk scenarios and error handling
-
β Portfolio Management (
test_portfolio.py
) - Complete coverage - 41 tests- Portfolio initialization and loading from multiple sources
- Portfolio validation and data structure integrity
- Portfolio saving and persistence across instances
- Portfolio value calculations and price updates
- Asset allocation calculations and performance metrics
- Trade execution and portfolio updates
- Exchange data synchronization and integration
- Portfolio rebalancing calculations and actions
- Error handling and edge case management
- Large number precision and concurrent access safety
- Rate limiting and error handling
- Account operations and balance retrieval
- Market data operations and price fetching
- Trading operations and order placement
- Precision handling for different trading pairs
- Notification integration and error recovery
-
β LLM Analyzer (
test_llm_analyzer.py
) - 100% coverage - 26 tests- Initialization and Google Cloud authentication
- Vertex AI provider integration and API calls
- Market data analysis and decision generation
- Technical indicator processing and prompt creation
- Response parsing and JSON handling
- Trading decision making (BUY/SELL/HOLD signals)
- Error handling and edge cases
- Configuration validation and parameter handling
All critical components now have comprehensive test coverage.
First Phase 2 component with 100% test coverage and 26 comprehensive tests.
- π Data Collector (
test_data_collector.py
) - π Dashboard Updater (
test_dashboard_updater.py
) - π Notification Service (
test_notification_service.py
) - π Trade Logger (
test_trade_logger.py
)
- Code Coverage Target: 90%+ for unit tests
- Current Coverage: 100% (config), 53% (coinbase_client), 100% (llm_analyzer), Comprehensive (core modules)
- Test Execution Time: <1 second per module
- Test Categories: Unit, Integration, E2E, Performance, Security
π Complete Test Documentation β
- Python 3.8+
- Coinbase Advanced Trade account
- Google Cloud account (for AI analysis)
-
Clone the repository
git clone <repository-url> cd AI-crypto-bot
-
Create virtual environment
python3 -m venv venv source venv/bin/activate # Linux/Mac # or venv\Scripts\activate # Windows
-
Install dependencies
pip install -r requirements.txt
-
Configure environment
cp .env.example .env # Edit .env with your API keys and settings
-
Deploy dashboard (optional)
python3 deploy_dashboard.py
-
Run the bot
python3 main.py
For production deployment on cloud platforms, use the automated setup scripts:
- AWS EC2: See
aws_setup/README.md
for complete AWS deployment guide - Google Cloud: See
gcp_setup/README.md
for complete GCP deployment guide
Both include automated scripts for dependencies, web server setup, and service configuration.
# Trading Configuration
BASE_CURRENCY=EUR # Base currency for trading
TRADING_PAIRS=BTC-EUR,ETH-EUR,SOL-EUR # Trading pairs
RISK_LEVEL=HIGH # LOW, MEDIUM, HIGH
SIMULATION_MODE=False # Set to True for paper trading
# AI Decision Thresholds
CONFIDENCE_THRESHOLD_BUY=70 # Minimum confidence for BUY orders
CONFIDENCE_THRESHOLD_SELL=70 # Minimum confidence for SELL orders
# Trade Size Limits
MIN_TRADE_AMOUNT=30.0 # Minimum trade size (EUR)
MAX_POSITION_SIZE=1000.0 # Maximum single trade size (EUR)
# Portfolio Strategy
TARGET_CRYPTO_ALLOCATION=90 # Target crypto allocation %
TARGET_BASE_ALLOCATION=10 # Target EUR allocation %
# Coinbase Advanced Trade
COINBASE_API_KEY=your_api_key
COINBASE_API_SECRET=your_private_key
# Google Cloud (for AI analysis)
GOOGLE_CLOUD_PROJECT=your_project_id
GOOGLE_APPLICATION_CREDENTIALS=path/to/service-account.json
LLM_MODEL=gemini-2.5-pro-preview-05-06
# Push Notifications (Pushover)
NOTIFICATIONS_ENABLED=true
PUSHOVER_TOKEN=your_pushover_app_token
PUSHOVER_USER=your_pushover_user_key
-
Download Pushover App
- iOS: App Store
- Android: Google Play
-
Create Pushover Account
- Sign up at pushover.net
- Note your User Key from the dashboard
-
Create Application
- Go to Create Application
- Name: "AI Crypto Bot" (or your preference)
- Copy the API Token/Key
-
Configure Environment
NOTIFICATIONS_ENABLED=true PUSHOVER_TOKEN=your_app_api_token_here PUSHOVER_USER=your_user_key_here
-
Test Notifications
python3 test_notifications.py
Unlike traditional rebalancing bots that force rigid allocation percentages, this bot:
- Analyzes Market Conditions using AI and technical indicators
- Makes Trading Decisions based on market opportunities
- Applies Smart Safety Limits to protect your portfolio
- Sizes Positions Dynamically based on confidence and allocation
- Minimum EUR Balance: β¬50 (ensures ability to make BUY orders)
- Maximum EUR Allocation: 35% (prevents holding too much cash)
- Minimum Crypto Allocation: 3% per asset (maintains diversification)
- Trade Size Scaling: Higher confidence = larger positions (up to 1.5x)
Market Data β AI Analysis β Confidence Score β Safety Check β Position Sizing β Execute Trade
- Total Value: Real-time EUR portfolio value
- Asset Allocation: Current vs target percentages
- AI-First Strategy Status: Smart safety limits and trading capability
- Performance Metrics: P&L, returns, win rates
- Comprehensive Trade Details: 4-section analysis for each trade
- AI Reasoning: Detailed bullet-point market analysis
- Technical Analysis: RSI, MACD, Bollinger Bands with color coding
- Bot Decision Process: Confidence checks and risk management
- Market Context: Price trends, conditions, and analysis quality
- Recent Decisions: Latest BUY/SELL/HOLD recommendations
- Confidence Levels: AI confidence scores (0-100%)
- Real-time Log Monitoring: Last 30 lines of bot activity
- Auto-refresh: Updates every 5 seconds automatically
- Color-coded Log Levels: ERROR (red), WARNING (yellow), INFO (blue), DEBUG (gray)
- Live Status Indicators: Bot operational status and last update time
- Interactive Controls: Manual refresh, auto-scroll toggle, clear logs
- Live Prices: Real-time cryptocurrency prices
- Price Changes: 1h, 4h, 24h, 5d percentage changes
- Trading Status: Current bot status and next decision time
AI-crypto-bot/
βββ main.py # Main bot entry point
βββ config.py # Configuration management
βββ coinbase_client.py # Coinbase API client
βββ llm_analyzer.py # AI analysis engine
βββ trading_strategy.py # Trading strategy implementation
βββ data_collector.py # Market data collection
βββ utils/ # Utility modules
β βββ dashboard_updater.py
β βββ webserver_sync.py
β βββ logger.py
β βββ portfolio.py
β βββ ...
βββ dashboard/ # Web dashboard
β βββ static/
β βββ images/
βββ aws_setup/ # AWS deployment scripts
β βββ setup_ec2.sh
β βββ iam_policy.json
β βββ cloudwatch_setup.sh
β βββ create_secrets.sh
βββ gcp_setup/ # Google Cloud deployment scripts
β βββ setup_gce.sh
β βββ README.md
βββ data/ # Runtime data
βββ logs/ # Application logs
βββ .env # Environment variables
βββ requirements.txt # Dependencies
The bot features intelligent uptime management that distinguishes between restarts and stops:
- Restarts: Configuration changes, updates, or service restarts preserve uptime
- Explicit Stops: Manual stops or
systemctl stop
reset uptime - Crash Recovery: Automatic restarts after crashes preserve uptime
Use the included bot manager for proper uptime handling:
# Start the bot
python3 bot_manager.py start
# Restart (preserves uptime) - for config changes, updates
python3 bot_manager.py restart
# Stop (resets uptime) - for maintenance, shutdown
python3 bot_manager.py stop
# Check status and total uptime
python3 bot_manager.py status
- Total Uptime: Cumulative uptime across all sessions
- Restart Count: Number of restarts since original start
- Professional Metrics: True operational uptime tracking
# Position Sizing Multipliers
RISK_HIGH_POSITION_MULTIPLIER=0.5 # 50% position reduction for high risk
RISK_MEDIUM_POSITION_MULTIPLIER=0.75 # 25% position reduction for medium risk
RISK_LOW_POSITION_MULTIPLIER=1.0 # No reduction for low risk
# Technical Analysis Weights
RSI_SIGNAL_WEIGHT=0.3 # RSI indicator weight
MACD_SIGNAL_WEIGHT=0.4 # MACD indicator weight
BOLLINGER_SIGNAL_WEIGHT=0.3 # Bollinger Bands weight
# Web Interface
WEBSERVER_SYNC_ENABLED=true # Enable web dashboard
WEBSERVER_SYNC_PATH=/var/www/html/crypto-bot # Dashboard path
DASHBOARD_TRADE_HISTORY_LIMIT=10 # Number of recent trades to show
- High Confidence (80%+): Larger position sizes, immediate execution
- Medium Confidence (70-79%): Standard position sizes
- Low Confidence (<70%): No trade execution (HOLD)
- Over-allocated assets: Smaller SELL positions to maintain balance
- Under-allocated assets: Larger BUY positions when EUR is available
- High EUR allocation: Larger BUY positions to deploy cash
- Low EUR allocation: Smaller BUY positions to preserve liquidity
- Main Log:
logs/crypto_bot.log
- General bot activity - Trade Log:
data/trades/trade_history.json
- All executed trades - Decision Log:
data/cache/latest_decisions.json
- Recent AI decisions
- Portfolio:
data/portfolio/portfolio.json
- Current holdings - Market Data:
data/*_EUR_*.json
- Historical price and analysis data - Configuration:
data/config/
- Runtime configuration snapshots
- Dashboard Status: Green badge indicates healthy operation
- EUR Balance: Warning if below β¬50 minimum
- API Connectivity: Automatic retry on connection issues
- AI Analysis: Fallback to HOLD if analysis fails
Test strategies without real money:
SIMULATION_MODE=True
- Insufficient Balance: Stops BUY orders if EUR < β¬50
- API Failures: Graceful degradation with error logging
- Invalid Decisions: Defaults to HOLD on analysis errors
- Minimum Holdings: Prevents selling below 3% allocation
- Maximum Cash: Limits EUR allocation to 35%
- Trade Size Limits: β¬30 minimum, β¬1000 maximum per trade
# Copy service file
sudo cp crypto-bot.service /etc/systemd/system/
sudo systemctl daemon-reload
sudo systemctl enable crypto-bot
sudo systemctl start crypto-bot
# Deploy dashboard to web server
python3 deploy_dashboard.py
1. Launch EC2 Instance
- Choose Amazon Linux 2023 AMI
- Select t2.medium or better for production
- Configure security groups:
- SSH access (port 22)
- HTTP access (port 80) for dashboard
2. Connect and Setup
# Connect to instance
ssh -i your-key.pem ec2-user@your-instance-ip
# Clone repository
git clone https://github.com/schmidb/AI-crypto-bot.git
cd AI-crypto-bot
# Run setup script
bash aws_setup/setup_ec2.sh
3. Configure and Start
# Edit configuration
nano .env
# Start service
sudo systemctl start crypto-bot
sudo systemctl enable crypto-bot
# Check status
sudo systemctl status crypto-bot
sudo journalctl -u crypto-bot -f
4. Access Dashboard
http://your-ec2-ip/crypto-bot/
1. Create VM Instance
- Navigate to Compute Engine > VM instances
- Choose e2-medium or better
- Select Debian/Ubuntu boot disk
- Allow HTTP/HTTPS traffic
- Add firewall rule for port 80
2. Connect and Setup
# Connect via SSH
gcloud compute ssh your-instance-name --zone=your-zone
# Clone repository
git clone https://github.com/schmidb/AI-crypto-bot.git
cd AI-crypto-bot
# Run setup script
bash gcp_setup/setup_gce.sh
3. Configure and Start
# Edit configuration
nano .env
# Check service status
sudo supervisorctl status crypto-bot
# View logs
tail -f /var/log/crypto-bot/crypto-bot.log
# Restart if needed
sudo supervisorctl restart crypto-bot
4. Access Dashboard
http://your-vm-ip/crypto-bot/
AWS IAM Policy (for CloudWatch integration):
{
"Version": "2012-10-17",
"Statement": [
{
"Effect": "Allow",
"Action": [
"cloudwatch:PutMetricData",
"cloudwatch:GetMetricStatistics",
"logs:CreateLogGroup",
"logs:CreateLogStream",
"logs:PutLogEvents"
],
"Resource": "*"
}
]
}
GCP Firewall Rules:
# Allow HTTP traffic for dashboard
gcloud compute firewall-rules create allow-http-crypto-bot \
--allow tcp:80 \
--source-ranges 0.0.0.0/0 \
--description "Allow HTTP access to crypto bot dashboard"
Bot not trading:
- Check EUR balance (minimum β¬50 required)
- Verify AI confidence meets 70% threshold
- Confirm API keys are valid
Dashboard not updating:
- Check webserver sync settings
- Verify file permissions
- Restart bot if needed
Low performance:
- Review confidence thresholds
- Check market conditions
- Analyze recent AI decisions in dashboard
- Check log files for error messages
- Review dashboard for status indicators
- Verify configuration settings
- Test in simulation mode first
This project is licensed under the MIT License - see the LICENSE file for details.
This software is for educational and research purposes. Cryptocurrency trading involves substantial risk of loss. Past performance does not guarantee future results. Use at your own risk and never invest more than you can afford to lose.
Built with β€οΈ for intelligent cryptocurrency trading