Skip to content

chumbacash/pebble-crypto-backend

Folders and files

NameName
Last commit message
Last commit date

Latest commit

Β 

History

9 Commits
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 

Repository files navigation

πŸš€ Pebble Crypto Analytics API

Banner Image

Advanced Cryptocurrency Analytics & AI-Powered Trading Assistant

A production-ready FastAPI backend providing real-time market data, AI-powered analysis, and multi-exchange integration for cryptocurrency trading and analytics.

Python 3.8+ FastAPI License: MIT API Status

πŸ“‹ Table of Contents

πŸš€ Quick Start

1. Install and Run

# Clone the repository
git clone https://github.com/your-org/pebble-crypto-backend.git
cd pebble-crypto-backend

# Install dependencies
pip install -r requirements.txt

# Start the API server
uvicorn main:app --reload --port 8000

2. Access the API Documentation

Once the server is running, visit these URLs:

πŸ”₯ Primary Documentation (Recommended)

πŸ₯ Quick Health Check

πŸ”₯ Interactive API Documentation

πŸ“– Using the /docs Interface

The FastAPI automatically generates interactive API documentation at /docs. This is your main tool for exploring and testing the API:

Key Features of /docs:

  • βœ… Try It Out: Test any endpoint directly in the browser
  • βœ… Real Responses: See actual API responses with live data
  • βœ… Request Examples: Auto-generated request/response schemas
  • βœ… Authentication: Test with API keys if required
  • βœ… Download Schemas: Export OpenAPI specs for integration

How to Use /docs:

  1. Navigate to http://localhost:8000/docs
  2. Browse available endpoints by category
  3. Click "Try it out" on any endpoint
  4. Fill in required parameters
  5. Execute to see real responses
  6. Copy curl commands for your applications

πŸ“š Complete API Reference

πŸ₯ System Health & Status

Monitor API health and system performance.

Endpoint Method Description Try It
/api/health GET API status, version, and metrics πŸ“Š Test

Example Response:

{
  "status": "healthy",
  "version": "1.0.0",
  "timestamp": "2025-01-09T12:00:00Z",
  "uptime": "2 hours 15 minutes"
}

πŸ“Š Market Data Endpoints

Get comprehensive cryptocurrency market information.

Endpoint Method Description Try It
/api/market/symbols GET List all available trading symbols πŸ“ˆ Test
/api/market/data/{symbol} GET Complete market data for a symbol πŸ“Š Test

Example - Get Bitcoin Data:

curl "http://localhost:8000/api/market/data/BTCUSDT"

Response Structure:

{
  "symbol": "BTCUSDT",
  "price": 45000.00,
  "change_24h": 2.5,
  "volume": 1000000,
  "indicators": {
    "rsi": 65.2,
    "macd": "bullish"
  }
}

πŸ€– AI Assistant Endpoints

Natural language market analysis and trading advice.

Endpoint Method Description Try It
/api/ai/ask POST Ask questions about markets in natural language πŸ€– Test

Example - AI Market Query:

curl -X POST "http://localhost:8000/api/ai/ask" \
  -H "Content-Type: application/json" \
  -d '{
    "query": "Should I buy Bitcoin now? What does the technical analysis say?",
    "context": {
      "timeframe": "1d",
      "risk_tolerance": "moderate"
    }
  }'

Response Structure:

{
  "response": "Based on current technical analysis...",
  "confidence": 0.85,
  "recommendations": ["Consider DCA strategy", "Monitor support at $44,000"],
  "risk_assessment": "moderate"
}

πŸ“ˆ Technical Analysis Endpoints

Advanced technical analysis and price predictions.

Endpoint Method Description Try It
/api/analysis/predict/{symbol} GET Price predictions and trading signals πŸ“Š Test
/api/analysis/compare/{primary_symbol} GET Compare multiple assets πŸ“Š Test

Example - Bitcoin Prediction:

curl "http://localhost:8000/api/analysis/predict/BTCUSDT?timeframe=1d"

πŸ”„ Multi-Exchange Endpoints

Aggregate data from multiple cryptocurrency exchanges.

Endpoint Method Description Try It
/api/exchanges/health GET Check status of all exchanges πŸ₯ Test
/api/exchanges/summary POST Get aggregated market data πŸ“Š Test
/api/exchanges/arbitrage POST Find arbitrage opportunities πŸ’° Test
/api/exchanges/coverage GET Exchange information and coverage ℹ️ Test

Example - Arbitrage Detection:

curl -X POST "http://localhost:8000/api/exchanges/arbitrage" \
  -H "Content-Type: application/json" \
  -d '{
    "symbols": ["BTCUSDT", "ETHUSDT", "SOLUSDT"]
  }'

⚑ Real-Time WebSocket Endpoints

Live streaming market data updates.

Endpoint Protocol Description Try It
/api/ws/live/{symbol} WebSocket Real-time price updates πŸ”΄ Test

Example - WebSocket Connection:

const ws = new WebSocket('ws://localhost:8000/api/ws/live/BTCUSDT?interval=1h');
ws.onmessage = (event) => {
  const data = JSON.parse(event.data);
  console.log('Live Bitcoin update:', data);
};

✨ Features

πŸ€– AI-Powered Analysis

  • Natural language query processing for market insights
  • Investment advice with confidence scores and risk assessment
  • Multi-timeframe technical analysis with actionable recommendations
  • Context-aware responses based on user preferences

πŸ“Š Comprehensive Market Data

  • Real-time data from 6+ major cryptocurrency exchanges
  • 1,400+ trading pairs with live price updates
  • OHLCV data with configurable intervals (1h to 1M)
  • Advanced technical indicators (RSI, Bollinger Bands, Moving Averages)

πŸ”„ Multi-Exchange Integration

  • Binance, KuCoin, Bybit, Gate.io, Bitget, OKX support
  • Cross-exchange price comparison and arbitrage detection
  • Automatic failover and load balancing
  • Real-time exchange health monitoring

⚑ Production Features

  • Async-first architecture with high concurrency
  • Smart caching with TTL for optimal performance
  • Rate limiting and request throttling
  • WebSocket streaming for real-time updates
  • Comprehensive error handling and monitoring

πŸ› οΈ Installation

Standard Installation

# Clone the repository
git clone https://github.com/your-org/pebble-crypto-backend.git
cd pebble-crypto-backend

# Create virtual environment (recommended)
python -m venv venv
source venv/bin/activate  # On Windows: venv\Scripts\activate

# Install dependencies
pip install -r requirements.txt

# Run the application
uvicorn main:app --reload --port 8000

Docker Installation

# Using Docker Compose (recommended)
docker-compose up -d

# Or build manually
docker build -t pebble-crypto-api .
docker run -d -p 8000:8000 --env-file .env pebble-crypto-api

Environment Configuration

Create a .env file with the following configuration:

# API Configuration
HOST=0.0.0.0
PORT=8000
RELOAD=true
WORKERS=1
ENVIRONMENT=development

# Rate Limits
AI_ASSISTANT_RATE_LIMIT=60/minute
MARKET_DATA_RATE_LIMIT=30/minute
HEALTH_CHECK_RATE_LIMIT=100/minute

# Security
ALLOWED_ORIGINS=*

# Optional: External API Keys
GEMINI_API_KEY=your_gemini_key_here
ANTHROPIC_API_KEY=your_anthropic_key_here

πŸ’‘ Usage Examples

Using the Interactive Documentation

The easiest way to explore the API is through the interactive documentation:

  1. Start the server: uvicorn main:app --reload --port 8000
  2. Open your browser: Go to http://localhost:8000/docs
  3. Pick an endpoint: Click on any endpoint to expand it
  4. Try it out: Click "Try it out" button
  5. Fill parameters: Enter required parameters
  6. Execute: Click "Execute" to see real responses

AI-Powered Market Queries

import requests

# Natural language market analysis
response = requests.post('http://localhost:8000/api/ai/ask', json={
    "query": "What's the best cryptocurrency to buy today under $100?",
    "context": {"risk_tolerance": "moderate", "timeframe": "1w"}
})

analysis = response.json()
print(analysis['response'])

Multi-Asset Price Comparison

# Compare multiple cryptocurrencies
response = requests.get(
    'http://localhost:8000/api/analysis/compare/BTCUSDT',
    params={
        'comparison_symbols': 'ETHUSDT,SOLUSDT,ADAUSDT',
        'time_period': '7d'
    }
)

comparison = response.json()

Real-Time Market Data

import asyncio
import websockets
import json

async def live_market_feed():
    uri = "ws://localhost:8000/api/ws/live/BTCUSDT?interval=1h"
    async with websockets.connect(uri) as websocket:
        while True:
            data = await websocket.recv()
            market_update = json.loads(data)
            print(f"BTC Price: ${market_update['data']['close']}")

# Run the live feed
asyncio.run(live_market_feed())

πŸ“ Project Structure

pebble-crypto-backend/
β”œβ”€β”€ πŸ“š Core Application
β”‚   β”œβ”€β”€ main.py                    # FastAPI application entry point
β”‚   └── app/
β”‚       β”œβ”€β”€ core/
β”‚       β”‚   β”œβ”€β”€ ai/                # AI assistant components
β”‚       β”‚   β”‚   β”œβ”€β”€ agent.py       # Market analysis agent
β”‚       β”‚   β”‚   β”œβ”€β”€ enhanced_investment_advisor.py
β”‚       β”‚   β”‚   └── multi_llm_router.py
β”‚       β”‚   β”œβ”€β”€ analysis/          # Market analysis tools
β”‚       β”‚   β”œβ”€β”€ indicators/        # Technical indicators
β”‚       β”‚   └── prediction/        # Price prediction models
β”‚       └── services/
β”‚           β”œβ”€β”€ binance.py         # Binance integration
β”‚           β”œβ”€β”€ kucoin.py          # KuCoin integration
β”‚           β”œβ”€β”€ exchange_aggregator.py # Multi-exchange orchestration
β”‚           └── metrics.py         # Performance monitoring
β”œβ”€β”€ πŸ§ͺ Testing & Quality Assurance
β”‚   └── tests/
β”‚       β”œβ”€β”€ test_complete_system.py     # End-to-end testing
β”‚       β”œβ”€β”€ test_system_direct.py       # Direct API testing
β”‚       └── test_data_quality.py        # Data quality validation
β”œβ”€β”€ 🐳 Deployment
β”‚   β”œβ”€β”€ Dockerfile
β”‚   β”œβ”€β”€ docker-compose.yml
β”‚   └── .env.example
└── πŸ“– Documentation
    β”œβ”€β”€ README.md
    └── static/images/

πŸ§ͺ Testing

Run All Tests

# Run the complete test suite
python -m pytest tests/ -v

# Run with coverage report
python -m pytest tests/ --cov=app --cov-report=html

# Run specific test categories
python -m pytest tests/test_complete_system.py -v      # System tests
python -m pytest tests/test_data_quality.py -v        # Data quality
python -m pytest tests/test_system_direct.py -v       # Direct API tests

Test Categories

  • System Tests: End-to-end API functionality
  • Data Quality: Market data accuracy and completeness
  • Integration Tests: Multi-exchange and AI components
  • Performance Tests: Load testing and response times

Test Results

  • βœ… 100% Success Rate across all endpoints
  • βœ… Real Market Data validated from 6+ exchanges
  • βœ… AI Processing tested with diverse query types
  • βœ… Error Handling verified with edge cases

πŸš€ Deployment

Production Deployment

# Using Docker Compose (recommended)
docker-compose -f docker-compose.prod.yml up -d

# Scale for high availability
docker-compose up --scale api=3

Environment Variables

# Production settings
ENVIRONMENT=production
WORKERS=4
RELOAD=false
LOG_LEVEL=info

# Security
ALLOWED_ORIGINS=https://your-frontend-domain.com
API_RATE_LIMIT=100/minute

Health Monitoring

# Check API health
curl https://api.your-domain.com/api/health

# Monitor exchange connectivity
curl https://api.your-domain.com/api/exchanges/health

πŸ“Š API Rate Limits

Endpoint Category Rate Limit Purpose
πŸ€– AI Assistant 60/minute Natural language processing
πŸ“Š Market Data 30/minute Real-time market information
πŸ“ˆ Technical Analysis 20-30/minute Complex calculations
πŸ”„ Multi-Exchange 15-20/minute Cross-exchange operations
πŸ₯ Health Check 100/minute System monitoring
⚑ WebSocket Unlimited Real-time streaming

🀝 Contributing

We welcome contributions! Please see our Contributing Guidelines for details.

Quick Contribution Guide

  1. Fork the repository
  2. Create a feature branch: git checkout -b feature/amazing-feature
  3. Make your changes and add tests
  4. Ensure all tests pass: python -m pytest tests/ -v
  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

Development Standards

  • Write comprehensive tests for new features
  • Follow Python PEP 8 style guidelines
  • Add docstrings for all functions and classes
  • Update documentation for API changes

πŸ“„ License

This project is licensed under the MIT License - see the LICENSE file for details.

⚠️ Disclaimer

This software is for informational purposes only. Cryptocurrency trading carries significant financial risk. Always conduct your own research and consult with financial advisors before making investment decisions. The authors are not responsible for any financial losses incurred through the use of this software.

πŸ†˜ Support

🎯 Roadmap

  • Advanced ML Models: Integration of machine learning prediction models
  • Social Sentiment Analysis: Twitter and Reddit sentiment integration
  • Portfolio Management: Advanced portfolio optimization tools
  • Mobile API: React Native/Flutter optimized endpoints
  • Enterprise Features: Multi-tenant support and advanced analytics

Made with ❀️ by the Pebble Crypto Team

πŸ”— Quick Links

For the most comprehensive and up-to-date API information, always use the interactive documentation at /docs

About

This is the backend service for the Pebble Crypto app, a cryptocurrency signals platform built using FastAPI.

Topics

Resources

Stars

Watchers

Forks

Releases

No releases published

Packages

 
 
 

Contributors