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.
- Architecture Overview
- Multi-Agent Design & Hermes Loop
- Setup & Installation
- Docker Deployment
- API Documentation & Sample Requests
- SQLite Database Schema
- Mathematical Formulation
- Future Scalability Ideas
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)]
The system features 5 distinct agents structured using the Hermes Agent philosophy:
- 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.
-
DataCollectionAgent: Fetches the last 1000 candles (OHLCV). It supports
apify-clientfor scraping. It computes technical indicators (EMA, RSI, MACD, volatility). - 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.
-
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. - 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.
- Python 3.10 or 3.11
- Git
git clone https://github.com/rishabh-108272/Crypto-Agentic-AI.git
cd "Crypto-Agentic-AI"python -m venv venv
# On Windows
venv\Scripts\activate
# On Linux/macOS
source venv/bin/activatepip install -r requirements.txtCopy .env.example to .env and fill in your keys:
cp .env.example .envEnsure 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.
To test metrics and feedback loops immediately with dummy historical trades:
python scripts/seed_db.pypython run.pyThe API documentation will be available at: http://localhost:8000/docs
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.
docker compose up --build -ddocker compose logs -fdocker compose down- 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"
}- 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
}
}- Endpoint:
GET /api/history
The SQLite schema consists of two tables:
prediction_records: Stores price details, Polymarket/Kalshi JSON odds, technical indicators, predicted directions, Kelly sizes, actual settlements, and Brier scores.agent_logs: Stores runtime operation logs for audit trails.
For contract price
NO_BET (bet size = 0).
0.25 for Quarter-Kelly).
-
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$ ). - 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.
- WebSocket Live Feeds: Replace REST polling with real-time WebSocket streams from Binance and Polymarket to execute prediction pipelines asynchronously on every tick.
- User Visibility Dashboards: Develop a sleek Next.js dashboard featuring chart overlays of predicted vs. actual prices, cumulative returns curves, and agent activity terminals.
- 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.