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i import FastAPI, HTTPException, Query
|
| 2 |
+
from fastapi.middleware.cors import CORSMiddleware
|
| 3 |
+
from pydantic import BaseModel
|
| 4 |
+
from typing import Dict, Any, List, Optional
|
| 5 |
+
|
| 6 |
+
# Import core logic modules
|
| 7 |
+
from data_processor import DataProcessor
|
| 8 |
+
from sentiment_analyzer import SentimentAnalyzer
|
| 9 |
+
from model_handler import ModelHandler
|
| 10 |
+
from trading_logic import TradingLogic
|
| 11 |
+
from plotter import create_mplfinance_chart
|
| 12 |
+
|
| 13 |
+
# Initialize core components
|
| 14 |
+
data_processor = DataProcessor()
|
| 15 |
+
sentiment_analyzer = SentimentAnalyzer()
|
| 16 |
+
model_handler = ModelHandler()
|
| 17 |
+
trading_logic = TradingLogic()
|
| 18 |
+
|
| 19 |
+
# FastAPI app setup
|
| 20 |
+
app = FastAPI(
|
| 21 |
+
title="Ultimate Market Analysis & Prediction API",
|
| 22 |
+
version="1.0.0",
|
| 23 |
+
description="API for fetching market data, technical indicators, Chronos-2 predictions, and simulated analysis for GC=F and BTC-USD."
|
| 24 |
+
)
|
| 25 |
+
|
| 26 |
+
# Add CORS middleware for frontend access
|
| 27 |
+
# HATI-HATI: Ganti "*" dengan domain frontend React Anda saat deployment produksi
|
| 28 |
+
app.add_middleware(
|
| 29 |
+
CORSMiddleware,
|
| 30 |
+
allow_origins=["*"],
|
| 31 |
+
allow_credentials=True,
|
| 32 |
+
allow_methods=["*"],
|
| 33 |
+
allow_headers=["*"],
|
| 34 |
+
)
|
| 35 |
+
|
| 36 |
+
# --- Skema Respon Pydantic ---
|
| 37 |
+
|
| 38 |
+
class TradingMetrics(BaseModel):
|
| 39 |
+
Ticker: str
|
| 40 |
+
Current_Price: str
|
| 41 |
+
Signal: str
|
| 42 |
+
Confidence: str
|
| 43 |
+
Take_Profit: str
|
| 44 |
+
Stop_Loss: str
|
| 45 |
+
RSI: str
|
| 46 |
+
MACD: str
|
| 47 |
+
Volume: str
|
| 48 |
+
|
| 49 |
+
class ChartAnalysisResponse(BaseModel):
|
| 50 |
+
chart_html_base64: Optional[str] = None # String base64 gambar, siap untuk tag <img src="data:image/png;base64,...">
|
| 51 |
+
metrics: Optional[TradingMetrics] = None
|
| 52 |
+
raw_predictions: Optional[List[float]] = None
|
| 53 |
+
error: Optional[str] = None
|
| 54 |
+
|
| 55 |
+
class SentimentAnalysisResponse(BaseModel):
|
| 56 |
+
sentiment_score: float
|
| 57 |
+
news_summary_html: str
|
| 58 |
+
|
| 59 |
+
class FundamentalsResponse(BaseModel):
|
| 60 |
+
fundamentals_data: Dict[str, Any]
|
| 61 |
+
|
| 62 |
+
# --- Endpoint API ---
|
| 63 |
+
|
| 64 |
+
@app.get("/")
|
| 65 |
+
def read_root():
|
| 66 |
+
return {"message": "Welcome to the Ultimate Market Analysis API. Use /docs for API documentation."}
|
| 67 |
+
|
| 68 |
+
@app.get("/analysis/chart", response_model=ChartAnalysisResponse)
|
| 69 |
+
def get_chart_analysis(
|
| 70 |
+
ticker: str = Query(..., description="Market Ticker (e.g., GC=F, BTC-USD)"),
|
| 71 |
+
interval: str = Query(..., description="Time Interval (e.g., 1d, 1h, 5m)")
|
| 72 |
+
):
|
| 73 |
+
"""
|
| 74 |
+
Mengambil data pasar, menghitung indikator, menghasilkan prediksi,
|
| 75 |
+
dan mengembalikan gambar chart (Base64) serta metrik trading.
|
| 76 |
+
"""
|
| 77 |
+
try:
|
| 78 |
+
# 1. Fetch data
|
| 79 |
+
df = data_processor.get_market_data(ticker, interval)
|
| 80 |
+
if df.empty:
|
| 81 |
+
return ChartAnalysisResponse(error=f"No data available for {ticker} at {interval}")
|
| 82 |
+
|
| 83 |
+
# 2. Calculate Indicators
|
| 84 |
+
df = data_processor.calculate_indicators(df)
|
| 85 |
+
|
| 86 |
+
# 3. Prepare and Predict
|
| 87 |
+
prepared_data = data_processor.prepare_for_chronos(df)
|
| 88 |
+
predictions = model_handler.predict(prepared_data, horizon=10)
|
| 89 |
+
|
| 90 |
+
current_price = df['Close'].iloc[-1]
|
| 91 |
+
|
| 92 |
+
# 4. Generate Chart (returns Base64 HTML string)
|
| 93 |
+
chart_html = create_mplfinance_chart(
|
| 94 |
+
df,
|
| 95 |
+
ticker=f'{ticker} ({interval})',
|
| 96 |
+
predictions=predictions
|
| 97 |
+
)
|
| 98 |
+
|
| 99 |
+
# 5. Generate Signal and Metrics
|
| 100 |
+
signal, confidence = trading_logic.generate_signal(
|
| 101 |
+
predictions, current_price, df
|
| 102 |
+
)
|
| 103 |
+
|
| 104 |
+
tp, sl = trading_logic.calculate_tp_sl(
|
| 105 |
+
current_price, df['ATR'].iloc[-1], signal
|
| 106 |
+
)
|
| 107 |
+
|
| 108 |
+
# 6. Format Metrics
|
| 109 |
+
metrics = TradingMetrics(
|
| 110 |
+
Ticker=ticker,
|
| 111 |
+
Current_Price=f"${current_price:.2f}",
|
| 112 |
+
Signal=signal.upper(),
|
| 113 |
+
Confidence=f"{confidence:.1%}",
|
| 114 |
+
Take_Profit=f"${tp:.2f}" if tp else "N/A",
|
| 115 |
+
Stop_Loss=f"${sl:.2f}" if sl else "N/A",
|
| 116 |
+
RSI=f"{df['RSI'].iloc[-1]:.1f}",
|
| 117 |
+
MACD=f"{df['MACD'].iloc[-1]:.4f}",
|
| 118 |
+
Volume=f"{df['Volume'].iloc[-1]:,.0f}"
|
| 119 |
+
)
|
| 120 |
+
|
| 121 |
+
return ChartAnalysisResponse(
|
| 122 |
+
chart_html_base64=chart_html,
|
| 123 |
+
metrics=metrics,
|
| 124 |
+
raw_predictions=predictions.tolist()
|
| 125 |
+
)
|
| 126 |
+
|
| 127 |
+
except Exception as e:
|
| 128 |
+
# Gunakan HTTPException untuk penanganan kesalahan API
|
| 129 |
+
raise HTTPException(status_code=500, detail=f"Error in chart analysis: {str(e)}")
|
| 130 |
+
|
| 131 |
+
@app.get("/analysis/sentiment", response_model=SentimentAnalysisResponse)
|
| 132 |
+
def get_sentiment_analysis(ticker: str = Query(..., description="Market Ticker (e.g., GC=F, BTC-USD)")):
|
| 133 |
+
"""
|
| 134 |
+
Menganalisis dan mengembalikan skor sentimen pasar dan ringkasan berita (Simulasi).
|
| 135 |
+
"""
|
| 136 |
+
try:
|
| 137 |
+
sentiment_score, news_summary_html = sentiment_analyzer.analyze_market_sentiment(ticker)
|
| 138 |
+
|
| 139 |
+
return SentimentAnalysisResponse(
|
| 140 |
+
sentiment_score=sentiment_score,
|
| 141 |
+
news_summary_html=news_summary_html
|
| 142 |
+
)
|
| 143 |
+
|
| 144 |
+
except Exception as e:
|
| 145 |
+
raise HTTPException(status_code=500, detail=f"Error in sentiment analysis: {str(e)}")
|
| 146 |
+
|
| 147 |
+
@app.get("/analysis/fundamentals", response_model=FundamentalsResponse)
|
| 148 |
+
def get_fundamentals_analysis(ticker: str = Query(..., description="Market Ticker (e.g., GC=F, BTC-USD)")):
|
| 149 |
+
"""
|
| 150 |
+
Mengambil data fundamental pasar utama (Simulasi).
|
| 151 |
+
"""
|
| 152 |
+
try:
|
| 153 |
+
fundamentals = data_processor.get_fundamental_data(ticker)
|
| 154 |
+
|
| 155 |
+
return FundamentalsResponse(fundamentals_data=fundamentals)
|
| 156 |
+
|
| 157 |
+
except Exception as e:
|
| 158 |
+
raise HTTPException(status_code=500, detail=f"Error in fundamentals analysis: {str(e)}")
|