Skip to content

Nfectious/crypto-trade-analysis

Folders and files

NameName
Last commit message
Last commit date

Latest commit

Β 

History

14 Commits
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 

Repository files navigation

Crypto Trade Analysis API

A professional, production-ready FastAPI service for fetching cryptocurrency OHLCV (Open, High, Low, Close, Volume) data and technical indicators using ccxt.

Features

  • πŸš€ FastAPI - Modern, fast web framework for building APIs
  • πŸ“Š Technical Indicators - EMA (20, 50, 200), RSI (14), ATR (14)
  • πŸ”Œ Multi-Exchange Support - Powered by ccxt library
  • πŸ”„ WebSocket Streaming - Real-time data updates via WebSocket
  • 🐳 Docker Ready - Easy deployment with Docker and docker-compose
  • βœ… Type Safe - Full type hints with mypy strict mode
  • πŸ§ͺ Tested - Comprehensive test suite with pytest (including mocked tests)
  • πŸ“ Well Documented - Clear API documentation with FastAPI's built-in docs

Quick Start

Local Development

  1. Clone the repository

    git clone https://github.com/Nfectious/crypto-trade-analysis.git
    cd crypto-trade-analysis
  2. Create a virtual environment

    python -m venv .venv
    source .venv/bin/activate  # On Windows: .venv\Scripts\activate
  3. Install dependencies

    pip install -e ".[dev]"
  4. Create environment file (optional)

    cp .env.example .env
    # Edit .env to customize settings
  5. Run the application

    uvicorn app.main:app --reload
  6. Access the API

Using Docker

  1. Build and run with docker-compose

    docker-compose up --build
  2. Access the API

API Endpoints

Health Check

GET /

Returns service status.

Response:

{
  "status": "ok",
  "message": "Simple Crypto Data API is running"
}

Live Market Data

GET /api/v1/live_data

Query Parameters:

  • symbol (string, default: "BTC/USDT") - Trading pair symbol
  • timeframe (string, default: "1h") - Candle timeframe (e.g., "1m", "5m", "1h", "1d")
  • limit (integer, default: 250, range: 20-2000) - Number of candles to fetch
  • exchange (string, default: "binance") - Exchange name

Example Request:

curl "http://localhost:8000/api/v1/live_data?symbol=BTC/USDT&timeframe=1h&limit=100"

Response:

{
  "symbol": "BTC/USDT",
  "timeframe": "1h",
  "exchange": "binance",
  "last_price": 43250.5,
  "last_timestamp": "2024-01-15T12:00:00Z",
  "candles_count": 100,
  "recent_candles": [
    {
      "timestamp": "2024-01-15T12:00:00Z",
      "open": 43200.0,
      "high": 43300.0,
      "low": 43150.0,
      "close": 43250.5,
      "volume": 125.5,
      "ema_20": 43180.2,
      "ema_50": 43050.8,
      "ema_200": null,
      "rsi_14": 55.3,
      "atr_14": 150.2
    }
  ],
  "latest_indicators": {
    "ema_20": 43180.2,
    "ema_50": 43050.8,
    "ema_200": null,
    "rsi_14": 55.3,
    "atr_14": 150.2
  },
  "meta": {
    "defaultType": "spot"
  }
}

WebSocket Live Data Stream

WS /api/v1/live_data/ws

Query Parameters:

  • symbol (string, default: "BTC/USDT") - Trading pair symbol
  • timeframe (string, default: "1h") - Candle timeframe
  • limit (integer, default: 250, range: 20-2000) - Number of candles to fetch
  • exchange (string, default: "binance") - Exchange name
  • interval (integer, default: 30, range: 5-300) - Update interval in seconds

Description: Streams live market data at regular intervals. The server will send updated candle data every interval seconds.

Example (using websocat):

websocat "ws://localhost:8000/api/v1/live_data/ws?symbol=BTC/USDT&interval=10"

Example (using JavaScript):

const ws = new WebSocket("ws://localhost:8000/api/v1/live_data/ws?symbol=BTC/USDT&interval=10");

ws.onmessage = (event) => {
  const data = JSON.parse(event.data);
  console.log("Received update:", data);
};

ws.onerror = (error) => {
  console.error("WebSocket error:", error);
};

Response Format: Same as the REST endpoint - sends the full LiveDataResponse object every interval.

Note about null values: Technical indicators may return null for early candles where there isn't enough historical data to calculate the indicator. For example:

  • EMA-20 requires at least 20 candles
  • EMA-50 requires at least 50 candles
  • EMA-200 requires at least 200 candles
  • RSI-14 requires at least 14 candles
  • ATR-14 requires at least 14 candles

Technical Indicators

The API calculates the following technical indicators using the ta library:

  • EMA (Exponential Moving Average): 20, 50, and 200 periods
  • RSI (Relative Strength Index): 14 period (momentum oscillator)
  • ATR (Average True Range): 14 period (volatility indicator)

Development

Running Tests

pytest

Linting

ruff check .

Type Checking

mypy src/

Code Formatting

ruff check --fix .

Configuration

Configuration is managed through environment variables. Copy .env.example to .env and customize as needed:

# Application Configuration
APP_NAME="Simple Crypto Data API"
API_PREFIX="/api/v1"

# Exchange Configuration
DEFAULT_EXCHANGE="binance"
DEFAULT_MARKET_TYPE="spot"

# Rate Limiting
ENABLE_RATE_LIMIT=true

Project Structure

crypto-trade-analysis/
β”œβ”€β”€ src/
β”‚   └── app/
β”‚       β”œβ”€β”€ __init__.py
β”‚       β”œβ”€β”€ main.py              # FastAPI application
β”‚       β”œβ”€β”€ api/
β”‚       β”‚   β”œβ”€β”€ __init__.py
β”‚       β”‚   └── v1/
β”‚       β”‚       β”œβ”€β”€ __init__.py
β”‚       β”‚       β”œβ”€β”€ routes_live_data.py  # REST endpoints
β”‚       β”‚       └── ws_live_data.py      # WebSocket endpoint
β”‚       β”œβ”€β”€ core/
β”‚       β”‚   β”œβ”€β”€ __init__.py
β”‚       β”‚   β”œβ”€β”€ config.py        # Application settings
β”‚       β”‚   └── logging.py       # Logging configuration
β”‚       β”œβ”€β”€ integrations/
β”‚       β”‚   β”œβ”€β”€ __init__.py
β”‚       β”‚   └── exchanges.py     # ccxt exchange wrapper
β”‚       β”œβ”€β”€ schemas/
β”‚       β”‚   β”œβ”€β”€ __init__.py
β”‚       β”‚   └── live_data.py     # Pydantic models
β”‚       └── services/
β”‚           β”œβ”€β”€ __init__.py
β”‚           β”œβ”€β”€ indicators.py    # Technical indicators
β”‚           └── market_data.py   # Market data processing
β”œβ”€β”€ tests/
β”‚   β”œβ”€β”€ __init__.py
β”‚   β”œβ”€β”€ test_health.py
β”‚   β”œβ”€β”€ test_live_data.py
β”‚   └── test_live_data_mocked.py  # Mocked tests for CI
β”œβ”€β”€ .github/
β”‚   └── workflows/
β”‚       └── ci.yml              # GitHub Actions CI
β”œβ”€β”€ Dockerfile
β”œβ”€β”€ docker-compose.yml
β”œβ”€β”€ pyproject.toml
β”œβ”€β”€ .gitignore
β”œβ”€β”€ .env.example
└── README.md

CI/CD

The project uses GitHub Actions for continuous integration. On every push and pull request, the workflow:

  1. Installs dependencies
  2. Runs ruff linting
  3. Runs mypy type checking
  4. Runs pytest tests

See .github/workflows/ci.yml for details.

Error Handling

The API handles various error conditions gracefully:

  • Network Errors (503): Issues connecting to the exchange
  • Exchange Errors (400): Invalid parameters or exchange-specific errors
  • Validation Errors (422): Invalid query parameters
  • Internal Errors (500): Unexpected server errors

License

This project is open source and available for educational and commercial use.

Contributing

Contributions are welcome! Please feel free to submit a Pull Request.

About

No description, website, or topics provided.

Resources

Stars

Watchers

Forks

Releases

No releases published

Packages

 
 
 

Contributors