Repository navigation
Expand file tree
/
Copy pathmain.py
More file actions
179 lines (157 loc) · 7.11 KB
/
Copy pathmain.py
File metadata and controls
179 lines (157 loc) · 7.11 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
from fastapi import FastAPI, Depends, HTTPException, status
from fastapi.middleware.cors import CORSMiddleware
from sqlalchemy.orm import Session
from typing import List, Dict, Any
import database
import models
import schemas
from config import settings
from orchestrator import Orchestrator
from agents.feedback_agent import FeedbackAgent
# Initialize DB tables
models.Base.metadata.create_all(bind=database.engine)
app = FastAPI(
title="CrowdWisdomTrading Crypto Agent API",
description="A multi-agent, production-ready system utilizing the Hermes framework to predict crypto market movements and manage risk via the Kelly Criterion.",
version="1.0.0"
)
# CORS configurations
app.add_middleware(
CORSMiddleware,
allow_origins=["*"],
allow_credentials=True,
allow_methods=["*"],
allow_headers=["*"],
)
@app.get("/")
def read_root():
return {
"status": "online",
"message": "Welcome to CrowdWisdomTrading Crypto Prediction Agent Backend",
"documentation": "/docs"
}
@app.post("/api/predict", response_model=schemas.PredictionResponse, status_code=status.HTTP_201_CREATED, tags=["Predictions"])
def execute_prediction(payload: schemas.PredictRequest, db: Session = Depends(database.get_db)):
"""
Triggers the multi-agent orchestration pipeline:
1. Search Polymarket/Kalshi prediction markets for BTC/ETH contracts.
2. Gathers OHLCV historical candle data (via Apify or Binance fallback).
3. Feeds K-line patterns to the Kronos-inspired forecasting agent.
4. Calculates position sizes with the Kelly Criterion risk agent.
5. Stores the result as 'PENDING' in SQLite database.
6. Triggers feedback evaluation loop on old pending trades.
"""
asset = payload.asset.upper()
if asset not in ["BTC", "ETH"]:
raise HTTPException(
status_code=status.HTTP_400_BAD_REQUEST,
detail=f"Unsupported asset '{asset}'. Currently, only BTC and ETH are supported."
)
try:
orchestrator = Orchestrator(db=db)
prediction_record = orchestrator.run_pipeline(asset=asset, timeframe=payload.timeframe)
return prediction_record
except Exception as e:
raise HTTPException(
status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
detail=f"Pipeline execution failed: {str(e)}"
)
@app.get("/api/metrics", response_model=schemas.MetricSummary, tags=["Analytics"])
def get_performance_metrics(db: Session = Depends(database.get_db)):
"""
Queries historical database prediction history to evaluate accuracy,
cumulative profit/loss, average Brier scores, and win rate splits by asset.
"""
try:
feedback_agent = FeedbackAgent(db=db)
metrics = feedback_agent.evaluate_performance()
# Structure the final response
# Query total count by statuses
total_predictions = db.query(models.PredictionRecord).count()
pending_count = db.query(models.PredictionRecord).filter(models.PredictionRecord.status == "PENDING").count()
resolved_count = metrics.get("total_resolved", 0)
correct_count = metrics.get("correct_predictions", 0)
incorrect_count = resolved_count - correct_count
avg_bet = db.query(models.PredictionRecord.bet_size).filter(models.PredictionRecord.status == "RESOLVED")
avg_bet_val = sum([x[0] for x in avg_bet if x[0] is not None]) / len(list(avg_bet)) if resolved_count > 0 else 0.0
return {
"total_predictions": total_predictions,
"resolved_predictions": resolved_count,
"pending_predictions": pending_count,
"correct_predictions": correct_count,
"incorrect_predictions": incorrect_count,
"win_rate": metrics.get("win_rate", 0.5),
"average_brier_score": metrics.get("avg_brier_score", 0.25),
"cumulative_pnl": metrics.get("cumulative_pnl", 0.0),
"average_bet_size": round(avg_bet_val, 4),
"win_rate_by_asset": metrics.get("asset_win_rates", {})
}
except Exception as e:
raise HTTPException(
status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
detail=f"Failed to compile metrics: {str(e)}"
)
@app.get("/api/history", response_model=List[schemas.PredictionResponse], tags=["Analytics"])
def get_prediction_history(limit: int = 50, db: Session = Depends(database.get_db)):
"""Retrieves list of recent prediction records and settlements."""
try:
records = db.query(models.PredictionRecord).order_by(
models.PredictionRecord.timestamp.desc()
).limit(limit).all()
return records
except Exception as e:
raise HTTPException(
status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
detail=f"History query failed: {str(e)}"
)
@app.post("/api/feedback/resolve", tags=["Admin"])
def resolve_prediction_manually(payload: schemas.ResolveRequest, db: Session = Depends(database.get_db)):
"""
Manually forces the settlement resolution of a specific pending prediction ID.
If 'actual_close_price' is omitted, uses the latest close price from Binance.
"""
record = db.query(models.PredictionRecord).filter(
models.PredictionRecord.id == payload.prediction_id
).first()
if not record:
raise HTTPException(
status_code=status.HTTP_404_NOT_FOUND,
detail=f"Prediction record ID {payload.prediction_id} not found."
)
if record.status != "PENDING":
raise HTTPException(
status_code=status.HTTP_400_BAD_REQUEST,
detail=f"Prediction record ID {payload.prediction_id} is already resolved or failed."
)
try:
# Determine actual price
actual_price = payload.actual_close_price
if not actual_price:
# Call data collection agent to fetch latest close
from agents.data_collection_agent import DataCollectionAgent
collector = DataCollectionAgent(db=db)
market_data = collector.execute(record.asset)
actual_price = market_data["current_price"]
feedback_agent = FeedbackAgent(db=db)
# Standardize resolving dictionary
dummy_candle = {
"open_time": int(record.timestamp.timestamp() * 1000),
"close_time": int(record.timestamp.timestamp() * 1000) + 1,
"close": actual_price
}
feedback_agent._resolve_prediction(record, dummy_candle)
# Compile response metrics after resolution
metrics = feedback_agent.evaluate_performance()
return {
"status": "success",
"message": f"Successfully resolved prediction ID {payload.prediction_id} manually.",
"actual_close": actual_price,
"actual_direction": record.actual_direction,
"profit_loss": record.profit_loss,
"overall_metrics": metrics
}
except Exception as e:
raise HTTPException(
status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
detail=f"Failed to resolve prediction: {str(e)}"
)