xoxo3413/Defi_risk_mcp_server
If you are the rightful owner of Defi_risk_mcp_server and would like to certify it and/or have it hosted online, please leave a comment on the right or send an email to henry@mcphub.com.
The DeFi Signal Tracker MVP is a comprehensive system designed to track and verify cryptocurrency trading signal performance from social media influencers and crypto traders.
🚀 DeFi Signal Tracker MVP
A comprehensive system for tracking and verifying cryptocurrency trading signal performance from social media influencers and crypto traders.
✨ Features
- 🤖 AI-Powered Signal Processing: Uses NLP to extract entry prices, targets, stop losses, and timeframes from raw text
- 📊 Real-time Performance Tracking: Monitors P&L, win rates, and risk metrics using live CoinGecko price data
- 🏆 Influencer Leaderboard: Ranks signal providers by verified performance metrics
- 🔧 MCP Server Integration: Provides tools for conversational analysis via AI assistants
- 📈 Multiple Platforms: Supports Twitter, Discord, and Telegram signal sources
- ⚡ Fast API: RESTful endpoints for all operations with automatic documentation
🚀 Quick Start
Prerequisites
📦 Installation
- Clone the repository:
git clone https://github.com/your-repo/DeFi_Risk_Assessment_MCP_Server.git
cd DeFi_Risk_Assessment_MCP_Server
- Install Python dependencies:
pip install -r requirements.txt
python -m spacy download en_core_web_sm
- Setup environment:
cp .env.example .env
Edit .env with your configuration:
# Database
DATABASE_URL=postgresql://username:password@localhost/defi_signals
# Redis (for caching)
REDIS_URL=redis://localhost:6379/0
# Optional API keys for automated collection
TWITTER_BEARER_TOKEN=your_twitter_token
- Start required services:
Option A: Using local installations
# Start PostgreSQL (varies by OS)
brew services start postgresql # macOS
sudo service postgresql start # Ubuntu
# Start Redis
brew services start redis # macOS
sudo service redis-server start # Ubuntu
# Create database
createdb defi_signals
Option B: Using Docker
docker-compose up postgres redis -d
- Initialize database:
python setup_db.py
- Start the application:
# Terminal 1: API Server
uvicorn main:app --reload
# Terminal 2 (optional): MCP Server
python mcp_server.py
- Verify installation:
python test_functionality.py
🐳 Docker Quick Start
For a complete containerized setup:
docker-compose up
📡 API Reference
Core Endpoints
| Method | Endpoint | Description | Example |
|---|---|---|---|
GET | / | API health check | Test |
POST | /influencers/ | Add new influencer | See examples below |
GET | /influencers/{id} | Get influencer details | View |
GET | /influencers/{id}/performance | Get performance metrics | View |
POST | /signals/ | Add new signal manually | See examples below |
GET | /signals/{id} | Get signal details | View |
GET | /leaderboard | Get top influencers | View |
POST | /process-signal | Process raw text to signal | See examples below |
🔗 Interactive API Documentation
Once the server is running, visit:
- Swagger UI: http://localhost:8000/docs
- ReDoc: http://localhost:8000/redoc
💻 Usage Examples
1. Add a Crypto Influencer
Using curl:
curl -X POST "http://localhost:8000/influencers/" \
-H "Content-Type: application/json" \
-d '{
"username": "crypto_trader",
"platform": "twitter",
"display_name": "Crypto Trader",
"follower_count": 10000,
"verified": true,
"bio": "Professional crypto analyst with 5 years experience"
}'
Using Python:
import requests
influencer_data = {
"username": "crypto_trader",
"platform": "twitter",
"display_name": "Crypto Trader",
"follower_count": 10000,
"verified": True,
"bio": "Professional crypto analyst"
}
response = requests.post("http://localhost:8000/influencers/", json=influencer_data)
print(f"Created influencer with ID: {response.json()['id']}")
2. Process Trading Signals
Using curl:
curl -X POST "http://localhost:8000/process-signal" \
-G \
-d "text=🚀 BTC looking bullish! Entry at \$45000, target \$50000, stop loss \$42000" \
-d "platform=twitter" \
-d "influencer_id=1"
Using Python:
# Process various signal formats
signals = [
{
"text": "🚀 $BTC looking bullish! Entry at $45000, target $50000, stop loss $42000",
"platform": "twitter",
"influencer_id": 1
},
{
"text": "ETH breakout pattern forming. Buy zone $2900-3000, target $3500, SL $2700",
"platform": "discord",
"influencer_id": 2
},
{
"text": "LINK pump incoming! Long at $14.5, TP at $18, cut losses at $12.5",
"platform": "telegram",
"influencer_id": 3
}
]
for signal in signals:
response = requests.post("http://localhost:8000/process-signal", params=signal)
if response.status_code == 200:
print(f"✅ Processed {response.json()['signal']['symbol']} signal")
else:
print(f"❌ Failed to process signal")
3. Get Performance Data
# Get specific influencer performance
influencer_performance = requests.get("http://localhost:8000/influencers/1/performance")
print(f"Win Rate: {influencer_performance.json()['win_rate']}%")
# Get top performing influencers
leaderboard = requests.get("http://localhost:8000/leaderboard")
for rank, influencer in enumerate(leaderboard.json(), 1):
print(f"{rank}. {influencer['username']}: {influencer['win_rate']}% win rate")
🤖 MCP Server Integration
The system includes an MCP (Model Context Protocol) server for integration with AI assistants like Claude.
Available Tools
| Tool Name | Description | Input Parameters |
|---|---|---|
track_influencer_performance | Get detailed metrics for an influencer | influencer_id |
find_top_signals | Find best performing signals | limit (optional) |
analyze_market_sentiment | Analyze bullish/bearish sentiment | symbol, days (optional) |
verify_signal_accuracy | Check if a signal was profitable | signal_id |
get_leaderboard | Get ranked list of top influencers | limit (optional) |
process_signal_text | Extract trading data from raw text | text, platform, influencer_id |
🚀 Running MCP Server
# Start MCP server (in separate terminal)
python mcp_server.py
📱 Using with AI Assistants
Once running, you can ask AI assistants natural language questions like:
- "What's the performance of influencer #1?"
- "Show me the top 10 performing signals"
- "Analyze the market sentiment for BTC over the last 7 days"
- "Process this signal: 'BTC to the moon! Buy at 45k, target 50k'"
⚙️ Background Tasks (Optional)
For automated signal collection, the system supports Celery background workers:
Setup Background Processing
# Terminal 1: Start Redis (if not already running)
redis-server
# Terminal 2: Start Celery Worker
celery -A tasks worker --loglevel=info
# Terminal 3: Start Celery Scheduler
celery -A tasks beat --loglevel=info
Available Tasks
collect_twitter_signals: Automatically collects signals from Twitter every 5 minutesupdate_performance_metrics: Updates P&L calculations every 10 minutes
Note: Background tasks require API keys configured in your .env file
⚙️ Configuration
Environment Variables
| Variable | Description | Required | Default |
|---|---|---|---|
DATABASE_URL | PostgreSQL connection string | ✅ Yes | - |
REDIS_URL | Redis connection string | ✅ Yes | redis://localhost:6379/0 |
TWITTER_BEARER_TOKEN | Twitter API bearer token | ❌ Optional | - |
TWITTER_API_KEY | Twitter API key | ❌ Optional | - |
TWITTER_API_SECRET | Twitter API secret | ❌ Optional | - |
TWITTER_ACCESS_TOKEN | Twitter access token | ❌ Optional | - |
TWITTER_ACCESS_TOKEN_SECRET | Twitter access token secret | ❌ Optional | - |
DEBUG | Enable debug mode | ❌ Optional | True |
LOG_LEVEL | Logging level | ❌ Optional | INFO |
🔑 API Keys Setup (Optional)
For automated signal collection:
- Twitter API: Apply at developer.twitter.com
- Discord Bot: Create at discord.com/developers
- Telegram Bot: Message @BotFather on Telegram
📊 Data Models
👤 Influencer
{
"id": 1,
"username": "crypto_trader",
"platform": "twitter",
"display_name": "Crypto Trader",
"follower_count": 10000,
"verified": true,
"bio": "Professional crypto analyst",
"wallet_address": "0x...", # Optional for on-chain verification
"created_at": "2024-01-01T00:00:00"
}
📈 Signal
{
"id": 1,
"symbol": "BTC",
"signal_type": "buy",
"entry_price": 45000.0,
"target_price": 50000.0,
"stop_loss": 42000.0,
"timeframe": "2 weeks",
"confidence_score": 0.9,
"status": "active",
"original_text": "🚀 $BTC looking bullish!..."
}
📊 Performance Metrics
Influencer Metrics
- 📈 Win Rate: Percentage of profitable signals
- 💰 Average P&L: Mean profit/loss percentage
- 📊 Total P&L: Cumulative performance
- ⚖️ Sharpe Ratio: Risk-adjusted returns
- 📉 Max Drawdown: Largest peak-to-trough decline
Signal Metrics
- 💲 Current P&L: Real-time profit/loss percentage
- 🎯 Target Hit: Whether price target was reached
- ⛔ Stop Loss Hit: Whether stop loss was triggered
- 📅 Days Active: Time since signal creation
🧪 Testing & Verification
Run the test suite:
# Full functionality test
python test_functionality.py
# Unit tests (if available)
pytest
# Test specific components
python -c "
from performance_tracker import PerformanceTracker
pt = PerformanceTracker()
price = pt.get_current_price('BTC')
print(f'BTC Price: ${price:,}')
"
Test with real data:
# Add test influencer and signals
curl -X POST "http://localhost:8000/influencers/" \
-H "Content-Type: application/json" \
-d '{"username": "test_trader", "platform": "twitter", "display_name": "Test Trader"}'
# Process a real signal
curl -X POST "http://localhost:8000/process-signal" \
-G -d "text=BTC buy at 45000 target 50000" -d "platform=twitter" -d "influencer_id=1"
🚨 Troubleshooting
Common Issues
1. Database Connection Error
# Check PostgreSQL is running
pg_isready
# Reset database
dropdb defi_signals && createdb defi_signals
python setup_db.py
2. Price API Not Working
# Test price fetching
curl "https://api.coingecko.com/api/v3/simple/price?ids=bitcoin&vs_currencies=usd"
3. Import Errors
# Reinstall dependencies
pip install -r requirements.txt --force-reinstall
python -m spacy download en_core_web_sm
🤝 Contributing
- Fork the repository
- Create a feature branch:
git checkout -b feature/amazing-feature - Make your changes and add tests
- Run the test suite:
python test_functionality.py - Commit your changes:
git commit -m "Add amazing feature" - Push to the branch:
git push origin feature/amazing-feature - Open a Pull Request