Skip to content

rishabh-108272/Crypto-Agentic-AI

Repository files navigation

CrowdWisdomTrading Crypto Predictions Agent

A complete, production-ready Python backend implementing a modular multi-agent architecture to search prediction markets, fetch historical candlesticks, forecast prices using the Kronos model, and manage risk using the Kelly Criterion. Built with FastAPI and SQLite.

Table of Contents

  1. Architecture Overview
  2. Multi-Agent Design & Hermes Loop
  3. Setup & Installation
  4. Docker Deployment
  5. API Documentation & Sample Requests
  6. SQLite Database Schema
  7. Mathematical Formulation
  8. Future Scalability Ideas

Architecture Overview

The system operates as a sequential multi-agent workflow. The FastAPI app exposes endpoints that trigger the orchestrator. The orchestrator invokes each agent, manages state, saves predictions in the SQLite database, and resolves historical predictions through a closed-loop feedback system.

graph TD
    A[FastAPI Endpoints] --> B[Orchestrator]
    B --> C[SearchAgent]
    B --> D[DataCollectionAgent]
    B --> E[PredictionAgent]
    B --> F[RiskManagementAgent]
    B --> G[FeedbackAgent]

    C -->|Query Event Odds| H[Polymarket & Kalshi APIs]
    D -->|Fetch 1000 candles| I[Apify]
    E -->|Normalized Forecast| J[Kronos Model / OpenRouter]
    F -->|Position Sizing| K[Kelly Criterion Math]
    G -->|Resolve & Adapt Multiplier| L[(SQLite Database)]
Loading

Multi-Agent Design & Hermes Loop

The system features 5 distinct agents structured using the Hermes Agent philosophy:

  1. SearchAgent: Queries the Polymarket Gamma API and Kalshi Markets API. It extracts current contract prices, representing the "crowd wisdom" implied probability of an UP/DOWN movement.
  2. DataCollectionAgent: Fetches the last 1000 candles (OHLCV). It supports apify-client for scraping. It computes technical indicators (EMA, RSI, MACD, volatility).
  3. PredictionAgent (Kronos): Handles data z-score normalization on the lookback window. If enabled, it runs PyTorch inference on the Kronos model. By default, it operates in AI-Assisted Mode, sending normalized candle structures to OpenRouter for zero-shot time-series forecasting.
  4. RiskManagementAgent: Uses the prediction confidence $p$ and market contract price to compute the Kelly Criterion fraction. It applies capital safety controls like a Quarter-Kelly multiplier and maximum position limits.
  5. FeedbackAgent: Performs performance evaluation. It matches past predictions with realized candle closes, calculates accuracy, Brier scores, and PnL. It implements self-evolution by dynamically scaling down risk parameters if recent accuracy degrades.

Setup & Installation

Prerequisites

  • Python 3.10 or 3.11
  • Git

1. Clone the repository

git clone https://github.com/rishabh-108272/Crypto-Agentic-AI.git
cd "Crypto-Agentic-AI"

2. Set up virtual environment

python -m venv venv
# On Windows
venv\Scripts\activate
# On Linux/macOS
source venv/bin/activate

3. Install dependencies

pip install -r requirements.txt

4. Configure Environment Variables

Copy .env.example to .env and fill in your keys:

cp .env.example .env

Ensure you add:

  • OPENROUTER_API_KEY: Key from OpenRouter to enable LLM forecasting.
  • APIFY_API_TOKEN: Key from Apify to run actors. If left blank, the system will throw error and will stop the pipeline.

5. Seed the Database

To test metrics and feedback loops immediately with dummy historical trades:

python scripts/seed_db.py

6. Run the server

python run.py

The API documentation will be available at: http://localhost:8000/docs


Docker Deployment

The application is containerized with a lightweight Dockerfile and configured for easy deployment with docker-compose.yml. SQLite data and logs persist in local volume mounts.

1. Build and Run Container

docker compose up --build -d

2. View Logs

docker compose logs -f

3. Tear Down Container

docker compose down

API Documentation & Sample Requests

1. Trigger Prediction Pipeline

  • Endpoint: POST /api/predict
  • Body:
{
  "asset": "BTC",
  "timeframe": "5m"
}
  • Response:
{
  "id": 11,
  "asset": "BTC",
  "timestamp": "2026-06-28T14:18:00Z",
  "current_price": 95200.0,
  "predicted_direction": "UP",
  "probability": 0.58,
  "kelly_fraction": 0.16,
  "bet_size": 0.04,
  "status": "PENDING"
}

2. Fetch Aggregated Metrics

  • Endpoint: GET /api/metrics
  • Response:
{
  "total_predictions": 12,
  "resolved_predictions": 10,
  "pending_predictions": 2,
  "correct_predictions": 7,
  "incorrect_predictions": 3,
  "win_rate": 0.70,
  "average_brier_score": 0.175,
  "cumulative_pnl": 0.108,
  "average_bet_size": 0.035,
  "win_rate_by_asset": {
    "BTC": 0.6,
    "ETH": 0.8
  }
}

3. Fetch Historical Logs

  • Endpoint: GET /api/history

SQLite Database Schema

The SQLite schema consists of two tables:

  1. prediction_records: Stores price details, Polymarket/Kalshi JSON odds, technical indicators, predicted directions, Kelly sizes, actual settlements, and Brier scores.
  2. agent_logs: Stores runtime operation logs for audit trails.

Mathematical Formulation

1. Payout Odds ($b$)

For contract price $C$ paying out $$1$ on win: $$b = \frac{1 - C}{C}$$

2. Kelly Criterion ($f^*$)

$$f^* = p - \frac{1 - p}{b}$$ Where $p$ is the forecasted probability. If $f^* \leq 0$, the system outputs NO_BET (bet size = 0).

3. Fractional Kelly Sizing

$$f_{\text{sized}} = \min(f^* \times \lambda, \text{Max Size})$$ Where $\lambda$ is the risk-scaling factor (default = 0.25 for Quarter-Kelly).

4. Brier Score

$$\text{Brier Score} = (p_{\text{predicted}} - y_{\text{true}})^2$$ Where $y_{\text{true}} \in {0, 1}$ represents the outcome. A lower score (closer to 0) indicates higher calibration accuracy.


Future Scalability Ideas

  1. Multi-Timeframe Cascading Prediction: Run high-frequency predicting (e.g., 1-minute $n+5$) to guide low-frequency position sizing (e.g., 5-minute $n+1$).
  2. Internal Prediction Market Arbitrage: Scan discrepancies between 15-minute up/down markets and the rolling average of three consecutive 5-minute markets, executing delta-neutral trades to capture arbitrage spread.
  3. WebSocket Live Feeds: Replace REST polling with real-time WebSocket streams from Binance and Polymarket to execute prediction pipelines asynchronously on every tick.
  4. User Visibility Dashboards: Develop a sleek Next.js dashboard featuring chart overlays of predicted vs. actual prices, cumulative returns curves, and agent activity terminals.
  5. Ensemble Models: Combine Kronos forecasts with classic machine learning (LightGBM, LSTM) and sentiment analysis (scraping Twitter/Telegram via Apify) using a meta-learner or voting ensemble.

About

A lightweight multi agentic AI backend api for crypto market prediction.

Resources

Stars

Watchers

Forks

Releases

No releases published

Packages

 
 
 

Contributors