Skip to content

Latest commit

 

History

1 Commit

Folders and files

NameName
Last commit message
Last commit date
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

🚀 Crypto Alert Service

Service Spring Boot 3 de suivi de prix d'actifs financiers (crypto + actions) avec alertes Telegram automatiques.


🏗️ Architecture

crypto-alert-service/
├── src/main/java/com/example/cryptoalert/
│   ├── LauncherApplication.java          # Point d'entrée (@EnableScheduling)
│   │
│   ├── shared/                           # Noyau transversal (Cross-cutting)
│   │   ├── exception/
│   │   │   ├── ErrorCode.java            # Catalogue centralisé des codes d'erreur
│   │   │   ├── BusinessException.java    # Exception racine + sous-classes sémantiques
│   │   │   ├── ErrorResponse.java        # DTO JSON uniforme pour toutes les erreurs
│   │   │   └── GlobalExceptionHandler.java # @RestControllerAdvice global
│   │   └── config/
│   │       ├── RedisConfig.java          # Sérialisation JSON, TTL, CacheManager
│   │       └── RestClientConfig.java     # Beans RestClient (CoinGecko, AlphaVantage, Telegram)
│   │
│   ├── tracker/                          # MODULE 1 : Suivi des prix
│   │   ├── api/
│   │   │   ├── PriceTrackerService.java  # Service public (Cache-Aside + résolution client)
│   │   │   └── PriceController.java      # REST endpoints /api/v1/prices
│   │   ├── domain/
│   │   │   ├── model/
│   │   │   │   ├── AssetPrice.java       # Agrégat DDD (immuable)
│   │   │   │   └── AssetType.java        # Enum CRYPTO / STOCK
│   │   │   ├── factory/
│   │   │   │   └── AssetPriceFactory.java # Factory Method (fromCoinGecko, fromAlphaVantage)
│   │   │   └── ports/
│   │   │       └── AssetClient.java      # Interface SPI (Port secondaire)
│   │   └── infrastructure/
│   │       ├── client/
│   │       │   ├── CoinGeckoRestClient.java     # Adaptateur CoinGecko + Resilience4j
│   │       │   └── AlphaVantageRestClient.java  # Adaptateur Alpha Vantage + Resilience4j
│   │       └── cache/
│   │           └── RedisPriceRepository.java    # Cache-Aside + gestion cooldown
│   │
│   └── notification/                     # MODULE 2 : Alertes Telegram
│       ├── api/
│       │   ├── AlertService.java         # CRUD alertes + polling @Scheduled + cooldown
│       │   ├── AlertController.java      # REST endpoints /api/v1/alerts
│       │   ├── Alert.java                # Entité domaine (shouldTrigger logic)
│       │   ├── AlertRequest.java         # DTO entrée (validation @Valid)
│       │   ├── AlertResponse.java        # DTO sortie
│       │   └── AlertDirection.java       # Enum ABOVE / BELOW
│       └── infrastructure/
│           ├── TelegramClient.java            # POST sendMessage → Telegram Bot API
│           └── InMemoryAlertRepository.java   # Dépôt thread-safe (ConcurrentHashMap)

⚙️ Technologies

Technologie Version Rôle
Spring Boot 3.3.4 Framework principal
Spring Modulith 1.2.3 Modules applicatifs vérifiés
Spring Data Redis 3.x Cache + Cooldown
Resilience4j 2.2.0 Rate Limiting + Circuit Breaker
Lombok Latest Réduction boilerplate
Java 21 LTS, Records, Pattern Matching
Docker Multi-stage Conteneurisation optimisée

🚀 Démarrage rapide

Prérequis

  • Java 21+
  • Docker & Docker Compose
  • Clé API Alpha Vantage (gratuite)
  • Token Bot Telegram (via @BotFather)

1. Configuration

cp .env.example .env
# Éditer .env avec vos clés

2. Lancement complet (Docker)

docker-compose up -d
# L'application démarre sur http://localhost:8080

3. Lancement local (développement)

# Démarrer Redis uniquement
docker-compose up -d redis

# Lancer Spring Boot
./mvnw spring-boot:run

📡 Endpoints REST

Prix

Méthode URL Description
GET /api/v1/prices/CRYPTO/bitcoin Prix Bitcoin (cache ou API)
GET /api/v1/prices/CRYPTO?ids=bitcoin,ethereum Batch crypto
GET /api/v1/prices/STOCK/AAPL Prix action Apple
POST /api/v1/prices/CRYPTO/bitcoin/refresh Force le refresh du cache

Alertes

Méthode URL Description
POST /api/v1/alerts Créer une alerte
GET /api/v1/alerts Lister toutes les alertes
DELETE /api/v1/alerts/{id}/deactivate Désactiver (soft delete)
DELETE /api/v1/alerts/{id} Supprimer définitivement

Exemple — Créer une alerte

curl -X POST http://localhost:8080/api/v1/alerts \
  -H "Content-Type: application/json" \
  -d '{
    "assetId": "bitcoin",
    "assetType": "CRYPTO",
    "thresholdPrice": 70000,
    "direction": "ABOVE",
    "telegramChatId": "YOUR_CHAT_ID"
  }'

❌ Gestion des erreurs

Toutes les erreurs retournent un JSON uniforme :

{
  "timestamp": "2024-10-15T14:23:01",
  "status": 404,
  "code": "TRACKER-001",
  "message": "Actif introuvable : xyz",
  "path": "/api/v1/prices/CRYPTO/xyz"
}

Codes d'erreur

Code Statut HTTP Description
TRACKER-001 404 Actif introuvable
TRACKER-002 502 Échec récupération prix (API externe)
TRACKER-003 400 Type d'actif non supporté
NOTIF-001 502 Échec envoi Telegram
NOTIF-003 404 Alerte introuvable
NOTIF-004 429 Cooldown actif
GLOBAL-001 400 Validation échouée
GLOBAL-002 429 Rate limit dépassé

🔒 Rate Limiting (Resilience4j)

API Limite Stratégie
CoinGecko (démo) 28 req/min RateLimiter + fallback 429
Alpha Vantage (gratuit) 4 req/min RateLimiter + fallback 429

🔕 Système anti-spam (Cooldown)

Après chaque alerte envoyée, un cooldown est positionné dans Redis.

  • Durée par défaut : 60 minutes (configurable)
  • Clé Redis : alert-cooldown:{alertId}
  • La même alerte ne peut pas se redéclencher pendant le cooldown.

🧪 Tests

# Tous les tests
./mvnw test

# Tests de structure modulaire uniquement
./mvnw test -Dtest=ModularityTest

🏥 Health Check

curl http://localhost:8080/actuator/health

📋 Variables d'environnement

Variable Défaut Description
REDIS_HOST localhost Hôte Redis
REDIS_PORT 6379 Port Redis
COINGECKO_API_KEY (vide) Clé API CoinGecko (optionnel)
ALPHAVANTAGE_API_KEY demo Clé API Alpha Vantage
TELEGRAM_BOT_TOKEN (obligatoire) Token Bot Telegram

About

system dalert crypto

Resources

Stars

0 stars

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages