Skip to content

nubro999/AutoTrading

Folders and files

NameName
Last commit message
Last commit date

Latest commit

Β 

History

19 Commits
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 

Repository files navigation

AutoTrading - AI-Powered Cryptocurrency Trading System

πŸ€– Overview

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.

πŸ—οΈ Architecture

Core Components

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

πŸš€ Features

AI Trading Modes

1. AI Full Auto Mode (AIFullAutoTrader)

  • 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

2. Single Coin Mode (SingleCoinTrader)

  • 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

Data Sources & Analysis

Market Data (data/market_data.py)

  • 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

News Analysis (data/news_analyzer.py)

  • 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

Fear & Greed Index (data/fear_greed.py)

  • Market sentiment: 0-100 scale emotional indicator
  • Trend analysis: Historical sentiment patterns
  • Trading signals: Contrarian and momentum strategies

AI Master Analysis (analysis/ai_master.py)

  • 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

Trading System

Portfolio Management (trading/portfolio.py)

  • 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

Trade Execution (trading/executor.py)

  • 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

Web Dashboard

Backend API (web/backend/main.py)

  • 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

Frontend Dashboard (web/frontend/src/App.js)

  • 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

πŸ› οΈ Technical Stack

Backend Technologies

  • 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

Frontend Technologies

  • 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

Infrastructure

  • Docker: Containerization and deployment
  • Docker Compose: Multi-service orchestration
  • Nginx: Reverse proxy and static file serving
  • Volume mounting: Persistent log storage

βš™οΈ Configuration

Environment Variables

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

Trading Configuration (config/settings.py)

# 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)

πŸš€ Quick Start

Prerequisites

  • Python 3.8+
  • Upbit account with API access
  • OpenAI API key (required for AI analysis)
  • SerpAPI key (optional, for news analysis)

Installation

  1. Install dependencies

    pip install -r requirements.txt
  2. Environment Setup Create a .env file 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
  3. Run the bot

    # Production mode
    python main.py
    
    # Test mode (analysis only, no trades)
    python main.py --test

🐳 Docker Deployment

Bot Only

docker-compose up -d

Bot + Web Dashboard

docker-compose -f docker-compose.web.yml up -d

Access the web dashboard at http://localhost:3000

πŸ“Š Monitoring & Logging

Log Files

  • logs/trades_YYYYMMDD.json: Trading execution records
  • logs/analysis_YYYYMMDD.json: AI analysis results
  • logs/errors_YYYYMMDD.log: Error logs and debugging information

Web Dashboard Features

  • 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

API Endpoints

  • GET /api/trades: Trading history and statistics
  • GET /api/analysis: AI analysis results and market data
  • GET /api/portfolio: Current portfolio status
  • GET /api/performance: Performance metrics and returns
  • WebSocket /ws: Real-time data updates

πŸ”’ Security & Risk Management

API Security

  • Environment variables: Secure API key storage
  • Minimal permissions: Only required exchange permissions
  • Rate limiting: Respectful API usage patterns

Trading Risk Controls

  • 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)

Error Handling

  • Graceful degradation: Fallback strategies when AI fails
  • Comprehensive logging: Detailed error tracking
  • Automatic retries: Resilient API communication
  • Safe defaults: Conservative settings for unknown situations

πŸ“ˆ AI Decision Process

1. Market Analysis

  • Sentiment evaluation: Fear & Greed Index interpretation
  • News impact assessment: Sentiment scoring and relevance
  • Trend direction: Overall market momentum analysis

2. Multi-Coin Evaluation (Full Auto Mode)

  • 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

3. Optimal Selection

  • 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)

4. Trade Execution

  • 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

πŸ“‹ Core Functions Overview

Main Entry Point (main.py)

  • BaseTrader: Abstract base class for all trading modes
  • AIFullAutoTrader: Fully autonomous AI trading with coin selection
  • SingleCoinTrader: Focused single-coin trading

Data Collection (data/ directory)

  • CoinAnalyzer.get_comprehensive_coin_data(): Parallel analysis of 15 coins
  • MarketDataCollector.get_all_market_data(): OHLCV and market data
  • NewsAnalyzer.analyze_news_sentiment(): Real-time news sentiment
  • FearGreedIndex.get_current_index(): Market psychology indicator

AI Analysis (analysis/ directory)

  • AIMasterAnalyzer.analyze_and_decide(): Comprehensive AI decision making
  • AIAnalyzer.get_recommendation(): Single coin AI analysis
  • TechnicalAnalyzer.get_signals(): Technical indicator calculations

Trading System (trading/ directory)

  • PortfolioManager.get_comprehensive_investment_status(): Multi-coin portfolio tracking
  • TradeExecutor.execute_trade(): Order execution with risk management

Web Interface (web/ directory)

  • Backend: FastAPI server with WebSocket support
  • Frontend: React dashboard with real-time charts

πŸ“ Usage Examples

AI Full Auto Mode

# AI selects coin and makes all decisions
trader = AIFullAutoTrader()
trader.run_continuous()

Single Coin Mode

# Focus on specific cryptocurrency (e.g., Bitcoin)
trader = SingleCoinTrader()  # Uses TARGET_COIN from config
trader.run_continuous()

Test Mode

# Analyze without executing trades
python main.py --test

⚠️ Risk Disclaimer

Important: 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

πŸ”§ Customization

Adding New Indicators

Extend technical analysis in analysis/technical_analyzer.py:

def calculate_custom_indicator(self, df):
    # Add your custom technical indicator
    pass

Custom AI Prompts

Modify 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..."

News Analysis Configuration

Configure news impact in config/settings.py:

NEWS_ANALYSIS_ENABLED = True
NEWS_WEIGHT = 0.3  # 30% influence on decisions

πŸ“ž Support

  • Issues: Report bugs via GitHub Issues
  • Documentation: Check HowToUse.md for 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.

About

GPT + Blockchain + DEX

Resources

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published

Contributors 2

  •  
  •