Defi_risk_mcp_server

xoxo3413/Defi_risk_mcp_server

3.1

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.

Tools
6
Resources
0
Prompts
0

🚀 DeFi Signal Tracker MVP

A comprehensive system for tracking and verifying cryptocurrency trading signal performance from social media influencers and crypto traders.

Python PostgreSQL FastAPI MCP

✨ 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

  1. Clone the repository:
git clone https://github.com/your-repo/DeFi_Risk_Assessment_MCP_Server.git
cd DeFi_Risk_Assessment_MCP_Server
  1. Install Python dependencies:
pip install -r requirements.txt
python -m spacy download en_core_web_sm
  1. 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
  1. 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
  1. Initialize database:
python setup_db.py
  1. Start the application:
# Terminal 1: API Server
uvicorn main:app --reload

# Terminal 2 (optional): MCP Server
python mcp_server.py
  1. Verify installation:
python test_functionality.py

🐳 Docker Quick Start

For a complete containerized setup:

docker-compose up

📡 API Reference

Core Endpoints

MethodEndpointDescriptionExample
GET/API health checkTest
POST/influencers/Add new influencerSee examples below
GET/influencers/{id}Get influencer detailsView
GET/influencers/{id}/performanceGet performance metricsView
POST/signals/Add new signal manuallySee examples below
GET/signals/{id}Get signal detailsView
GET/leaderboardGet top influencersView
POST/process-signalProcess raw text to signalSee examples below

🔗 Interactive API Documentation

Once the server is running, visit:

💻 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 NameDescriptionInput Parameters
track_influencer_performanceGet detailed metrics for an influencerinfluencer_id
find_top_signalsFind best performing signalslimit (optional)
analyze_market_sentimentAnalyze bullish/bearish sentimentsymbol, days (optional)
verify_signal_accuracyCheck if a signal was profitablesignal_id
get_leaderboardGet ranked list of top influencerslimit (optional)
process_signal_textExtract trading data from raw texttext, 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 minutes
  • update_performance_metrics: Updates P&L calculations every 10 minutes

Note: Background tasks require API keys configured in your .env file

⚙️ Configuration

Environment Variables

VariableDescriptionRequiredDefault
DATABASE_URLPostgreSQL connection string✅ Yes-
REDIS_URLRedis connection string✅ Yesredis://localhost:6379/0
TWITTER_BEARER_TOKENTwitter API bearer token❌ Optional-
TWITTER_API_KEYTwitter API key❌ Optional-
TWITTER_API_SECRETTwitter API secret❌ Optional-
TWITTER_ACCESS_TOKENTwitter access token❌ Optional-
TWITTER_ACCESS_TOKEN_SECRETTwitter access token secret❌ Optional-
DEBUGEnable debug mode❌ OptionalTrue
LOG_LEVELLogging level❌ OptionalINFO

🔑 API Keys Setup (Optional)

For automated signal collection:

  1. Twitter API: Apply at developer.twitter.com
  2. Discord Bot: Create at discord.com/developers
  3. 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

  1. Fork the repository
  2. Create a feature branch: git checkout -b feature/amazing-feature
  3. Make your changes and add tests
  4. Run the test suite: python test_functionality.py
  5. Commit your changes: git commit -m "Add amazing feature"
  6. Push to the branch: git push origin feature/amazing-feature
  7. Open a Pull Request