Skip to content

lakal96/Crypto.inteligence.ai.agent

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

1 Commit
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

Crypto AI Trading Assistant

A comprehensive AI-powered cryptocurrency trading assistant that analyzes multiple data sources and provides advisory trading signals with high confidence. This system is designed to assist you in making informed trading decisions — you maintain full control and make the final trading decision.

⚠️ Important: Advisory Mode

This system is an ADVISOR, not an automatic trader.

  • All signals are recommendations only
  • You must review and approve all trades manually
  • No trades are executed automatically
  • Use paper trading first to validate signals
  • See INTEGRATIONS.md for integration with auto-trading platforms (Freqtrade, OctoBot, etc.)

📚 Documentation Quick Links

New to this system? Start here:

Architecture Overview

This system is built as a microservices architecture with containerized components:

┌─────────────────────────────────────────────────────────────────┐
│                    Crypto AI Trading Assistant                  │
└─────────────────────────────────────────────────────────────────┘
        │                    │              │           │
        ↓                    ↓              ↓           ↓
┌──────────────────┐ ┌──────────────────┐ ┌──────────────┐ ┌──────────────┐
│ Market Collector │ │ Technical Analysis│ │ OrderBook    │ │ Sentiment    │
│   (Binance API)  │ │   (RSI, MACD...)   │ │   Analyzer   │ │   Agent      │
└──────────────────┘ └──────────────────┘ └──────────────┘ └──────────────┘
        │                    │              │           │
        └────────────────────┴──────────────┴───────────┘
                            │
                            ↓
                       ┌──────────────┐
                       │   Redis      │
                       │   (Data Bus) │
                       └──────────────┘
                            │
        ┌───────────────────┴───────────────────┐
        ↓                                       ↓
┌───────────────────────┐           ┌──────────────────┐
│  AI Predictor         │           │ On-Chain         │
│  (ML Models)          │           │ Analytics        │
└───────────────────────┘           └──────────────────┘
        │                                       │
        └───────────────────┬───────────────────┘
                            │
                            ↓
                    ┌────────────────────┐
                    │   Signal Engine    │
                    │  (BUY/SELL/HOLD)   │
                    └────────────────────┘
                            │
                    ┌───────┴────────┐
                    ↓                ↓
            ┌──────────────┐  ┌─────────────┐
            │   Logs       │  │   Telegram  │
            │ (Docker)     │  │   Alerts    │
            └──────────────┘  └─────────────┘

Services

1. Market Data Collector (services/market_collector/)

  • Fetches live market data from Binance API
  • Collects candlestick data (OHLCV) for multiple timeframes
  • Streams recent trades and order book snapshots
  • Stores data in Redis for real-time access
  • Supported Pairs: BTCUSDT, ETHUSDT, SOLUSDT (expandable)
  • Timeframes: 5m, 1h, 4h (configurable)
  • Features:
    • REST API integration with retry logic
    • Rate limiting compliance
    • Real-time data pipeline

2. Technical Analysis Engine (services/technical_analysis/)

  • Calculates key technical indicators:
    • RSI (Relative Strength Index): Identifies overbought/oversold conditions
    • MACD (Moving Average Convergence Divergence): Trend and momentum analysis
    • EMA (Exponential Moving Averages): 50/200 period crossover signals
    • Bollinger Bands: Volatility and price level analysis
  • Generates bullish/bearish/neutral signals
  • Stores signals with confidence scores
  • Real-time calculation on incoming candle data

3. Order Book Analyzer (services/orderbook_analyzer/)

  • Analyzes microstructure of order book
  • Detects:
    • Buy/sell pressure ratios
    • Liquidity walls
    • Liquidity imbalance scores
    • Spread analysis
  • Signals accumulation/distribution pressure
  • Updates on each order book snapshot

4. Sentiment Agent (services/sentiment_agent/)

  • Aggregates sentiment from multiple sources:
    • News (CoinTelegraph, crypto news feeds)
    • Reddit (r/cryptocurrency, r/Bitcoin, etc.)
    • Twitter/X (real-time crypto discussions)
  • NLP-based sentiment scoring
  • Weighted aggregation across sources
  • Tracks mention volume and trends

5. AI Predictor Engine (services/ai_predictor/)

  • Machine learning models for price prediction:
    • XGBoost: Fast gradient boosting for classification
    • Random Forest: Ensemble learning for robustness
    • LSTM: Deep learning for time series patterns
  • Feature engineering from all indicators
  • Outputs probability of price increase/decrease
  • Model training and persistence
  • Confidence scoring

6. Signal Engine (services/signal_engine/)

  • Aggregates all signals into final recommendation
  • Weighted scoring system:
    • Technical Analysis: 35%
    • Sentiment: 25%
    • Order Book: 15%
    • On-Chain: 15%
    • ML Prediction: 10%
  • Outputs: BUY, SELL, or HOLD
  • Includes:
    • Entry price
    • Target price
    • Stop loss
    • Risk/reward ratio
    • Confidence score
  • Telegram notifications for high-confidence signals

Project Structure

crypto-ai-assistant/
├── config/
│   └── config.yaml                 # Main configuration file
├── shared/
│   ├── __init__.py
│   ├── config_loader.py           # YAML config management
│   ├── redis_client.py            # Redis wrapper
│   ├── logger_setup.py            # Logging configuration
│   └── models.py                  # Data models (Dataclasses)
├── services/
│   ├── market_collector/
│   │   ├── main.py               # Binance API client
│   │   ├── Dockerfile
│   │   └── __init__.py
│   ├── technical_analysis/
│   │   ├── main.py               # Technical indicator calculations
│   │   ├── Dockerfile
│   │   └── __init__.py
│   ├── orderbook_analyzer/
│   │   ├── main.py               # Order book analysis
│   │   ├── Dockerfile
│   │   └── __init__.py
│   ├── sentiment_agent/
│   │   ├── main.py               # Sentiment analysis
│   │   ├── Dockerfile
│   │   └── __init__.py
│   ├── ai_predictor/
│   │   ├── main.py               # ML model predictions
│   │   ├── Dockerfile
│   │   └── __init__.py
│   └── signal_engine/
│       ├── main.py               # Signal aggregation
│       ├── Dockerfile
│       └── __init__.py
├── docker-compose.yml             # Multi-container orchestration
├── requirements.txt               # Python dependencies
├── README.md                      # This file
└── .env.example                   # Environment variables template

Setup & Installation

Prerequisites

  • Docker & Docker Compose (v1.29+)
  • Python 3.11+ (for local development)
  • Binance API key and secret
  • Optional: Telegram bot token for alerts

Step 1: Clone Repository

git clone https://github.com/yourusername/crypto-ai-assistant.git
cd crypto-ai-assistant

Step 2: Configure Settings

cp config/config.yaml config/config.yaml.local

Edit config/config.yaml.local with:

  • Binance API credentials
  • Trading symbols (e.g., BTCUSDT, ETHUSDT)
  • Timeframes (1m, 5m, 1h, 4h, 1d)
  • Telegram bot token (optional)

Step 3: Build Docker Images

docker-compose build

Step 4: Start Services

docker-compose up -d

Step 5: Monitor Logs

# All services
docker-compose logs -f

# Specific service
docker-compose logs -f signal_engine

Configuration

Main Configuration File (config/config.yaml)

Redis Configuration

redis:
  host: redis
  port: 6379
  db: 0

Binance API

binance:
  api_key: "YOUR_KEY"
  api_secret: "YOUR_SECRET"
  base_url: "https://api.binance.com"

Trading Symbols

trading:
  symbols:
    - "BTCUSDT"
    - "ETHUSDT"
  timeframes:
    - "1h"
    - "4h"
    - "1d"

Technical Indicators

technical:
  rsi:
    period: 14
    overbought: 70
    oversold: 30
  macd:
    fast: 12
    slow: 26
    signal: 9
  ema:
    short: 50
    long: 200
  bollinger_bands:
    period: 20
    std_dev: 2

Signal Weights

signal_engine:
  weights:
    technical: 0.35
    sentiment: 0.25
    onchain: 0.15
    orderbook: 0.15
    ml_prediction: 0.10
  confidence_threshold: 0.60

Telegram Notifications

notifications:
  telegram:
    enabled: true
    bot_token: "YOUR_BOT_TOKEN"
    chat_id: "YOUR_CHAT_ID"

API Integration Details

Binance Market Data

  • Endpoint: https://api.binance.com/api/v3/
  • Endpoints Used:
    • /klines - Candlestick data
    • /trades - Recent trades
    • /depth - Order book
  • Rate Limits: 1200 requests per minute
  • Authentication: API key + secret for authenticated endpoints

Example: Get BTCUSDT Candles

from services.market_collector.main import BinanceMarketCollector

collector = BinanceMarketCollector()
klines = collector.fetch_klines('BTCUSDT', '1h', limit=100)
candles = collector.process_klines('BTCUSDT', '1h', klines)
collector.store_candles(candles)

Running Locally (Development)

Setup Python Environment

python -m venv venv
source venv/bin/activate  # On Windows: venv\Scripts\activate
pip install -r requirements.txt

Start Redis Locally

# Using Homebrew (macOS)
brew install redis
redis-server

# Or using Docker
docker run -d -p 6379:6379 redis:7-alpine

Run Individual Services

# In separate terminals:

# Terminal 1: Market Collector
CONFIG_PATH=config/config.yaml python services/market_collector/main.py

# Terminal 2: Technical Analysis
CONFIG_PATH=config/config.yaml python services/technical_analysis/main.py

# Terminal 3: Order Book Analyzer
CONFIG_PATH=config/config.yaml python services/orderbook_analyzer/main.py

# Terminal 4: Sentiment Agent
CONFIG_PATH=config/config.yaml python services/sentiment_agent/main.py

# Terminal 5: AI Predictor
CONFIG_PATH=config/config.yaml python services/ai_predictor/main.py

# Terminal 6: Signal Engine
CONFIG_PATH=config/config.yaml python services/signal_engine/main.py

Monitor Signals in Docker Logs

# Watch for trading signals (most important)
docker-compose logs -f signal_engine | grep "TRADING SIGNAL"

# Or locally in terminal 6 output

Redis Data Schema

Candlestick Data

Key: candle:{SYMBOL}:{TIMEFRAME}
Type: List (FIFO)
Value: JSON Candle objects (max 1000 per symbol/timeframe)
TTL: None (historical data)

Technical Signals

Key: technical_signal_latest:{SYMBOL}
Type: Hash
TTL: 1 hour
Fields: rsi, macd, ema50, ema200, bb_upper, bb_lower, overall_signal, confidence

Order Book Snapshot

Key: orderbook:{SYMBOL}
Type: Hash
TTL: 60 seconds
Fields: bids, asks, timestamp, buy_pressure, liquidity_score

Sentiment Data

Key: sentiment_latest:{SYMBOL}
Type: Hash
TTL: 1 hour
Fields: overall_score, overall_label, confidence, individual_sentiments

Trading Signals

Key: trading_signal_latest:{SYMBOL}
Type: Hash
TTL: 1 hour
Fields: signal, confidence, entry_price, target_price, stoploss_price, recommendation

Signal Interpretation

Signal Levels

Signal Meaning Action
BUY (score > 0.3) Strong bullish bias Enter long position
SELL (score < -0.3) Strong bearish bias Exit long or go short
HOLD (-0.3 ≤ score ≤ 0.3) Neutral / indecision Wait for clarity

Confidence Scoring

  • High Confidence (>80%): Signals agree across multiple indicators
  • Medium Confidence (50-80%): Mixed signals with slight bias
  • Low Confidence (<50%): Conflicting signals, high uncertainty

Price Level Recommendations

For a BUY signal at $40,000:

  • Entry: $40,000 (current price)
  • Target: $42,000 (+5%)
  • Stop Loss: $38,800 (-3%)
  • Risk/Reward: 1.67 (favorable)

Extensibility

Adding a New Data Source

  1. Create a new service directory:
mkdir services/my_datasource
touch services/my_datasource/{main.py,Dockerfile,__init__.py}
  1. Implement signal class in shared/models.py:
@dataclass
class MySignal:
    symbol: str
    timestamp: int
    score: float
    signal: str
  1. Add to docker-compose.yml:
my_datasource:
  build:
    context: ./services/my_datasource
  depends_on:
    - redis
  networks:
    - crypto_ai_network
  1. Update signal weights in signal_engine/main.py

Adding a New Technical Indicator

Edit services/technical_analysis/main.py:

def calculate_my_indicator(self, data: np.ndarray) -> float:
    # Your calculation here
    return result

# In analyze_symbol():
my_indicator = self.calculate_my_indicator(closes)
signal.my_field = my_indicator

Performance Optimization

For Production Deployment

  1. Database Persistence: Replace Redis with PostgreSQL for historical data
  2. Caching: Add Redis cluster for high availability
  3. Load Balancing: Use multiple instances of computationally heavy services
  4. Message Queue: Add Kafka/RabbitMQ for asynchronous processing
  5. Monitoring: Integrate Prometheus + Grafana for metrics

Resource Requirements

  • Market Collector: 256MB RAM, 1 CPU
  • Technical Analysis: 512MB RAM, 1 CPU (numpy heavy)
  • Order Book Analyzer: 256MB RAM, 1 CPU
  • Sentiment Agent: 1GB RAM, 2 CPUs (NLP models)
  • AI Predictor: 2GB RAM, 2 CPUs (ML model inference/training)
  • Signal Engine: 256MB RAM, 1 CPU
  • Redis: 512MB RAM, 1 CPU

Total Minimum: 5GB RAM, 8 CPUs

Monitoring & Logging

Docker Logs

# All services
docker-compose logs -f

# Follow specific service
docker-compose logs -f signal_engine

# Show only errors
docker-compose logs --tail 100 | grep ERROR

Log Levels

  • DEBUG: Detailed diagnostic information
  • INFO: Confirmation that things are working
  • WARNING: Something unexpected or degradation
  • ERROR: Serious problems

Configure in config/config.yaml:

logging:
  level: "INFO"  # DEBUG, INFO, WARNING, ERROR
  log_file: "/app/logs/crypto_ai.log"

Advanced Features

Model Training

Train the ML model on historical data:

from services.ai_predictor.main import AIPredictor
import numpy as np

predictor = AIPredictor()

# Prepare historical data
X_train = np.random.randn(1000, 10)  # 1000 samples, 10 features
y_train = np.random.randint(0, 2, 1000)  # Binary labels

predictor.train(X_train, y_train)

Custom Signal Weights

Adjust signal weights based on market conditions:

# Conservative (low risk)
weights = {
    'technical': 0.45,
    'sentiment': 0.15,
    'orderbook': 0.20,
    'ml_prediction': 0.10,
    'onchain': 0.10,
}

# Aggressive (high return potential)
weights = {
    'technical': 0.25,
    'sentiment': 0.35,
    'orderbook': 0.10,
    'ml_prediction': 0.20,
    'onchain': 0.10,
}

Troubleshooting

Issue: Redis Connection Failed

# Check Redis is running
docker-compose ps | grep redis

# Restart Redis
docker-compose restart redis

# Test connection
redis-cli -h localhost ping  # Should return PONG

Issue: Market Data Not Updating

# Check market collector logs
docker-compose logs market_collector

# Verify Binance API credentials
curl "https://api.binance.com/api/v3/klines?symbol=BTCUSDT&interval=1h&limit=1"

Issue: High Memory Usage

  • Reduce candle retention: Lower the ltrim limit in market_collector
  • Reduce TTL on Redis keys: Lower ex parameter in storage calls
  • Scale down ML model size

Disclaimer

This system is for educational and research purposes.

⚠️ NOT FINANCIAL ADVICE

  • Always conduct your own research
  • Never risk more than you can afford to lose
  • Test thoroughly in paper trading before live trading
  • Past performance does not guarantee future results
  • Crypto markets are highly volatile and unpredictable

Contributing

Contributions are welcome! Please:

  1. Fork the repository
  2. Create a feature branch
  3. Add tests for new functionality
  4. Submit a pull request

License

MIT License - See LICENSE file for details

Contact & Support


Last Updated: March 11, 2026 Version: 1.0.0

About

A comprehensive AI-powered cryptocurrency trading assistant that analyzes multiple data sources and provides advisory trading signals with high confidence. This system is designed to assist you in making informed trading decisions

Resources

Stars

0 stars

Watchers

0 watching

Forks

Releases

No releases published

Packages

 
 
 

Contributors