AutoTrading is a sophisticated AI-powered cryptocurrency trading system that combines multiple data sources and advanced analysis techniques to make automated trading decisions. The system features both a core trading bot and a web dashboard for monitoring and analysis.
AutoTrading/
βββ main.py # Main entry point and trading orchestration
βββ config/ # Configuration and settings
β βββ settings.py # Trading configuration and API keys
βββ data/ # Data collection and analysis modules
β βββ coin_analyzer.py # Multi-coin analysis and selection
β βββ market_data.py # Market data collection from Upbit
β βββ news_analyzer.py # News sentiment analysis via SerpAPI
β βββ fear_greed.py # Fear & Greed Index integration
βββ analysis/ # AI analysis modules
β βββ ai_master.py # Master AI decision maker (GPT-4)
β βββ ai_analyzer.py # Single coin AI analysis
β βββ technical_analyzer.py # Technical analysis backup
βββ trading/ # Trading execution
β βββ portfolio.py # Portfolio management
β βββ executor.py # Trade execution engine
βββ utils/ # Utilities
β βββ logger.py # Comprehensive logging system
βββ web/ # Web dashboard
β βββ backend/ # FastAPI backend server
β βββ frontend/ # React.js dashboard
βββ logs/ # Trading and analysis logs
- Autonomous coin selection: Analyzes 15 major cryptocurrencies
- Comprehensive decision making: AI selects both the coin and trading action
- Multi-source analysis: Combines OHLCV data, news sentiment, and Fear & Greed Index
- Risk management: Dynamic position sizing and stop-loss/take-profit levels
- Focused analysis: Deep analysis of a single cryptocurrency
- Configurable target: Fixed coin or AI-assisted selection
- Backup strategies: Technical analysis fallback when AI is unavailable
- Real-time pricing: Current prices and order book data
- Historical OHLCV: 30-day daily and 24-hour hourly candlestick data
- Volume analysis: Trading volume patterns and trends
- Upbit API integration: Direct connection to Korean exchange
- Google News integration: Latest cryptocurrency news via SerpAPI
- Sentiment scoring: Keyword-based sentiment analysis
- Time-weighted analysis: Recent news given higher priority
- Multi-language support: Korean and English news processing
- Market sentiment: 0-100 scale emotional indicator
- Trend analysis: Historical sentiment patterns
- Trading signals: Contrarian and momentum strategies
- GPT-4 powered: Advanced natural language processing
- Multi-coin comparison: Comparative analysis across all supported coins
- Comprehensive reasoning: Combines technical, fundamental, and sentiment analysis
- Risk assessment: Dynamic risk level evaluation
- Real-time balances: KRW and cryptocurrency holdings
- Performance tracking: Profit/loss calculations
- Asset allocation: Percentage-based position sizing
- Multi-coin support: Handles multiple cryptocurrency positions
- Order management: Market buy/sell order execution
- Risk controls: Minimum trade amounts and confidence thresholds
- Error handling: Comprehensive error handling and retry logic
- Trade logging: Detailed transaction records
- FastAPI framework: High-performance REST API
- Real-time updates: WebSocket support for live data
- Log aggregation: Historical trading and analysis data
- Performance metrics: Trading statistics and returns
- React.js interface: Modern, responsive web application
- Interactive charts: Real-time price and portfolio visualizations
- Trading history: Detailed transaction logs
- Performance analytics: Win rates, returns, and trade statistics
- Python 3.8+: Core programming language
- PyUpbit: Korean cryptocurrency exchange API
- OpenAI GPT-4: AI analysis and decision making
- FastAPI: Web API framework
- Pandas/NumPy: Data analysis and manipulation
- HTTPX/Requests: HTTP client libraries
- React 18: User interface framework
- Recharts: Data visualization library
- Tailwind CSS: Utility-first CSS framework
- Lucide React: Icon library
- Axios: HTTP client for API calls
- Docker: Containerization and deployment
- Docker Compose: Multi-service orchestration
- Nginx: Reverse proxy and static file serving
- Volume mounting: Persistent log storage
UPBIT_ACCESS_KEY=your_upbit_access_key
UPBIT_SECRET_KEY=your_upbit_secret_key
OPENAI_API_KEY=your_openai_api_key
SERPAPI_KEY=your_serpapi_key # Optional, for news analysis# AI Mode Selection
AI_FULL_AUTO_MODE = True # Enable AI full automation
AUTO_SELECTION_ENABLED = True # AI coin selection
# Supported Cryptocurrencies
SUPPORTED_COINS = [
"KRW-BTC", "KRW-ETH", "KRW-XRP", "KRW-ADA", "KRW-SOL",
"KRW-DOGE", "KRW-AVAX", "KRW-DOT", "KRW-MATIC", "KRW-LINK",
"KRW-UNI", "KRW-LTC", "KRW-BCH", "KRW-ATOM", "KRW-NEAR"
]
# Risk Management
TRADE_RATIOS = {
"high": 0.1, # High risk: 10% of portfolio
"medium": 0.2, # Medium risk: 20% of portfolio
"low": 0.3 # Low risk: 30% of portfolio
}
# Trading Parameters
MIN_CONFIDENCE = 6 # Minimum AI confidence (1-10)
TRADE_INTERVAL = 30 # Analysis interval (seconds)
MIN_TRADE_AMOUNT = 5000 # Minimum trade amount (KRW)- Python 3.8+
- Upbit account with API access
- OpenAI API key (required for AI analysis)
- SerpAPI key (optional, for news analysis)
-
Install dependencies
pip install -r requirements.txt
-
Environment Setup Create a
.envfile in the project root:UPBIT_ACCESS_KEY=your_upbit_access_key UPBIT_SECRET_KEY=your_upbit_secret_key OPENAI_API_KEY=your_openai_api_key SERPAPI_KEY=your_serpapi_key
-
Run the bot
# Production mode python main.py # Test mode (analysis only, no trades) python main.py --test
docker-compose up -ddocker-compose -f docker-compose.web.yml up -dAccess the web dashboard at http://localhost:3000
logs/trades_YYYYMMDD.json: Trading execution recordslogs/analysis_YYYYMMDD.json: AI analysis resultslogs/errors_YYYYMMDD.log: Error logs and debugging information
- Portfolio tracking: Real-time asset values and allocation
- Performance metrics: Returns, win rates, and trade statistics
- Trading history: Detailed transaction logs with timestamps
- Charts and visualizations: Price trends and portfolio performance
GET /api/trades: Trading history and statisticsGET /api/analysis: AI analysis results and market dataGET /api/portfolio: Current portfolio statusGET /api/performance: Performance metrics and returnsWebSocket /ws: Real-time data updates
- Environment variables: Secure API key storage
- Minimal permissions: Only required exchange permissions
- Rate limiting: Respectful API usage patterns
- Position limits: Maximum 80% portfolio allocation per coin
- Confidence thresholds: Minimum AI confidence requirements (configurable)
- Stop-loss mechanisms: Automatic loss limitation
- Minimum amounts: Prevents micro-transactions (5,000 KRW minimum)
- Graceful degradation: Fallback strategies when AI fails
- Comprehensive logging: Detailed error tracking
- Automatic retries: Resilient API communication
- Safe defaults: Conservative settings for unknown situations
- Sentiment evaluation: Fear & Greed Index interpretation
- News impact assessment: Sentiment scoring and relevance
- Trend direction: Overall market momentum analysis
- Technical analysis: OHLCV patterns and indicators
- Performance metrics: Price changes and volatility
- News relevance: Coin-specific news impact
- Liquidity assessment: Trading volume and market depth
- Risk-reward scoring: Potential return vs. downside risk
- Market timing: Entry and exit point optimization
- Portfolio balance: Diversification and allocation
- Confidence rating: Decision certainty measurement (1-10 scale)
- Order placement: Market orders for immediate execution
- Position sizing: Risk-adjusted investment amounts
- Risk management: Dynamic stop-loss and take-profit levels
- Performance tracking: Real-time monitoring and adjustment
BaseTrader: Abstract base class for all trading modesAIFullAutoTrader: Fully autonomous AI trading with coin selectionSingleCoinTrader: Focused single-coin trading
CoinAnalyzer.get_comprehensive_coin_data(): Parallel analysis of 15 coinsMarketDataCollector.get_all_market_data(): OHLCV and market dataNewsAnalyzer.analyze_news_sentiment(): Real-time news sentimentFearGreedIndex.get_current_index(): Market psychology indicator
AIMasterAnalyzer.analyze_and_decide(): Comprehensive AI decision makingAIAnalyzer.get_recommendation(): Single coin AI analysisTechnicalAnalyzer.get_signals(): Technical indicator calculations
PortfolioManager.get_comprehensive_investment_status(): Multi-coin portfolio trackingTradeExecutor.execute_trade(): Order execution with risk management
- Backend: FastAPI server with WebSocket support
- Frontend: React dashboard with real-time charts
# AI selects coin and makes all decisions
trader = AIFullAutoTrader()
trader.run_continuous()# Focus on specific cryptocurrency (e.g., Bitcoin)
trader = SingleCoinTrader() # Uses TARGET_COIN from config
trader.run_continuous()# Analyze without executing trades
python main.py --testImportant: Cryptocurrency trading involves substantial risk of loss. This system is for educational and research purposes. Key considerations:
- Test thoroughly: Always run in test mode before live trading
- Start small: Use small amounts while learning the system
- Monitor actively: Regularly check logs and performance
- Market volatility: Crypto markets are highly volatile
- No guarantees: Past performance doesn't guarantee future results
- API limits: Respect exchange rate limits and terms of service
Extend technical analysis in analysis/technical_analyzer.py:
def calculate_custom_indicator(self, df):
# Add your custom technical indicator
passModify AI analysis prompts in analysis/ai_master.py:
def _get_master_system_prompt(self):
# Customize the AI's decision-making personality
return "Your custom trading prompt..."Configure news impact in config/settings.py:
NEWS_ANALYSIS_ENABLED = True
NEWS_WEIGHT = 0.3 # 30% influence on decisions- Issues: Report bugs via GitHub Issues
- Documentation: Check
HowToUse.mdfor detailed usage instructions - API Documentation: Refer to Upbit and OpenAI API documentation
This comprehensive system provides a robust foundation for automated cryptocurrency trading with AI-powered decision making, extensive monitoring capabilities, and production-ready deployment options.