Merge pull request #44 from 0xwi11iam/render-technical-overview-on-candlestick-chart
Browse files- backend/app/api/endpoints.py +30 -1
- backend/app/graphql/schema.py +13 -111
- backend/app/services/gemini.py +218 -1
- frontend/src/App.css +19 -0
- frontend/src/App.tsx +5 -0
- frontend/src/components/ChartChatbot.tsx +1 -1
- frontend/src/components/StockChart.tsx +255 -11
backend/app/api/endpoints.py
CHANGED
|
@@ -18,7 +18,7 @@ from backend.app.database.session import get_db
|
|
| 18 |
from backend.app.database import crud
|
| 19 |
from backend.app.schemas import schemas
|
| 20 |
from backend.app.config.metrics import payment_callbacks_total, external_api_calls_total
|
| 21 |
-
from backend.app.services.gemini import get_onnx_session_for_type
|
| 22 |
|
| 23 |
router= APIRouter()
|
| 24 |
|
|
@@ -1067,6 +1067,31 @@ async def get_market_movers():
|
|
| 1067 |
_market_movers_cache = {"data": result, "timestamp": now}
|
| 1068 |
return result
|
| 1069 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1070 |
from typing import List, Dict, Any, Optional
|
| 1071 |
|
| 1072 |
class ChatRequest(BaseModel):
|
|
@@ -1143,6 +1168,10 @@ async def chat_with_analyst(
|
|
| 1143 |
indicators_list.append("EMA 20 Overlay")
|
| 1144 |
if active_indicators.get("rsi"):
|
| 1145 |
indicators_list.append("RSI 14 Panel")
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1146 |
indicators_text = ", ".join(indicators_list) if indicators_list else "None"
|
| 1147 |
|
| 1148 |
# Construct system instructions
|
|
|
|
| 18 |
from backend.app.database import crud
|
| 19 |
from backend.app.schemas import schemas
|
| 20 |
from backend.app.config.metrics import payment_callbacks_total, external_api_calls_total
|
| 21 |
+
from backend.app.services.gemini import get_onnx_session_for_type, compute_chart_indicators
|
| 22 |
|
| 23 |
router= APIRouter()
|
| 24 |
|
|
|
|
| 1067 |
_market_movers_cache = {"data": result, "timestamp": now}
|
| 1068 |
return result
|
| 1069 |
|
| 1070 |
+
@router.get("/indicators")
|
| 1071 |
+
async def get_chart_indicators(
|
| 1072 |
+
ticker: str,
|
| 1073 |
+
range: str = "1d",
|
| 1074 |
+
db: AsyncSession = Depends(get_db)
|
| 1075 |
+
):
|
| 1076 |
+
"""
|
| 1077 |
+
Returns precomputed MACD (12/26/9) and Bollinger Bands (20, 2) series for the
|
| 1078 |
+
active chart range. Series are aligned by epoch timestamp with the candles
|
| 1079 |
+
served by the ``stockHistory`` GraphQL query, and computed with the exact same
|
| 1080 |
+
pandas-ta pipeline the backend ML model uses under the hood.
|
| 1081 |
+
|
| 1082 |
+
Example:
|
| 1083 |
+
GET /api/v1/indicators?ticker=BTC-USD&range=1d
|
| 1084 |
+
"""
|
| 1085 |
+
try:
|
| 1086 |
+
return await compute_chart_indicators(db, ticker, range)
|
| 1087 |
+
except Exception as e:
|
| 1088 |
+
print(f"Error computing chart indicators for {ticker} ({range}): {e}")
|
| 1089 |
+
return {
|
| 1090 |
+
"macd": {"line": [], "signal": [], "histogram": []},
|
| 1091 |
+
"bollinger_bands": {"upper": [], "middle": [], "lower": []},
|
| 1092 |
+
"candle_count": 0,
|
| 1093 |
+
}
|
| 1094 |
+
|
| 1095 |
from typing import List, Dict, Any, Optional
|
| 1096 |
|
| 1097 |
class ChatRequest(BaseModel):
|
|
|
|
| 1168 |
indicators_list.append("EMA 20 Overlay")
|
| 1169 |
if active_indicators.get("rsi"):
|
| 1170 |
indicators_list.append("RSI 14 Panel")
|
| 1171 |
+
if active_indicators.get("macd"):
|
| 1172 |
+
indicators_list.append("MACD (12, 26, 9) Panel")
|
| 1173 |
+
if active_indicators.get("bb"):
|
| 1174 |
+
indicators_list.append("Bollinger Bands (20, 2) Overlay")
|
| 1175 |
indicators_text = ", ".join(indicators_list) if indicators_list else "None"
|
| 1176 |
|
| 1177 |
# Construct system instructions
|
backend/app/graphql/schema.py
CHANGED
|
@@ -246,118 +246,20 @@ class Query:
|
|
| 246 |
async def stock_history(self, info: Info, ticker: str, range: str = "1d") -> List[StockHistoryType]:
|
| 247 |
"""Fetch historical aggregated candles for a ticker based on range (1d, 5d, 1m, 6m, ytd, 1y, 5y, max)."""
|
| 248 |
db = info.context["db"]
|
| 249 |
-
|
| 250 |
-
|
| 251 |
-
|
| 252 |
-
|
| 253 |
-
|
| 254 |
-
|
| 255 |
-
|
| 256 |
-
|
| 257 |
-
|
| 258 |
-
|
| 259 |
-
|
| 260 |
-
|
| 261 |
-
selected_range = range.lower()
|
| 262 |
-
if selected_range not in range_mapping:
|
| 263 |
-
selected_range = "1d"
|
| 264 |
-
|
| 265 |
-
config = range_mapping[selected_range]
|
| 266 |
-
|
| 267 |
-
# If it's 1d, let's try local DB first
|
| 268 |
-
if selected_range == "1d":
|
| 269 |
-
try:
|
| 270 |
-
local_data = await crud.get_stock_history(db, ticker, limit=100)
|
| 271 |
-
|
| 272 |
-
# Filter out flat closed candles (zero volume and zero movement) for non-crypto assets
|
| 273 |
-
is_crypto = ticker.upper().endswith("-USD") or ticker.upper().endswith("-BTC")
|
| 274 |
-
if not is_crypto:
|
| 275 |
-
local_data = [h for h in local_data if not (h.open == h.close and h.volume == 0)]
|
| 276 |
-
|
| 277 |
-
if len(local_data) > 10:
|
| 278 |
-
return [
|
| 279 |
-
StockHistoryType(
|
| 280 |
-
id=h.id,
|
| 281 |
-
ticker=h.ticker,
|
| 282 |
-
timestamp=h.timestamp,
|
| 283 |
-
open=h.open,
|
| 284 |
-
high=h.high,
|
| 285 |
-
low=h.low,
|
| 286 |
-
close=h.close,
|
| 287 |
-
volume=h.volume
|
| 288 |
-
) for h in local_data
|
| 289 |
-
]
|
| 290 |
-
except Exception as db_err:
|
| 291 |
-
print(f"Error querying local DB for ticker history: {db_err}")
|
| 292 |
-
|
| 293 |
-
|
| 294 |
-
# Otherwise, dynamically fetch from Yahoo Finance in a thread pool
|
| 295 |
-
try:
|
| 296 |
-
import yfinance as yf
|
| 297 |
-
loop = asyncio.get_event_loop()
|
| 298 |
-
yf_ticker = yf.Ticker(ticker)
|
| 299 |
-
|
| 300 |
-
df = await loop.run_in_executor(
|
| 301 |
-
None,
|
| 302 |
-
lambda: yf_ticker.history(period=config["period"], interval=config["interval"])
|
| 303 |
)
|
| 304 |
-
|
| 305 |
-
|
| 306 |
-
history_list = []
|
| 307 |
-
if not df.empty:
|
| 308 |
-
df = df.reset_index()
|
| 309 |
-
|
| 310 |
-
time_col = None
|
| 311 |
-
for col in ['Date', 'Datetime', 'index', 'timestamp']:
|
| 312 |
-
if col in df.columns:
|
| 313 |
-
time_col = col
|
| 314 |
-
break
|
| 315 |
-
|
| 316 |
-
if time_col:
|
| 317 |
-
# Limit to last 350 points to ensure smooth chart performance
|
| 318 |
-
df = df.tail(350)
|
| 319 |
-
for i, row in df.iterrows():
|
| 320 |
-
ts = row[time_col]
|
| 321 |
-
if hasattr(ts, 'to_pydatetime'):
|
| 322 |
-
ts_dt = ts.to_pydatetime()
|
| 323 |
-
elif isinstance(ts, str):
|
| 324 |
-
ts_dt = datetime.datetime.fromisoformat(ts)
|
| 325 |
-
else:
|
| 326 |
-
ts_dt = ts
|
| 327 |
-
|
| 328 |
-
if ts_dt.tzinfo is not None:
|
| 329 |
-
ts_dt = ts_dt.replace(tzinfo=None)
|
| 330 |
-
|
| 331 |
-
history_list.append(
|
| 332 |
-
StockHistoryType(
|
| 333 |
-
id=i,
|
| 334 |
-
ticker=ticker.upper(),
|
| 335 |
-
timestamp=ts_dt,
|
| 336 |
-
open=float(row["Open"]),
|
| 337 |
-
high=float(row["High"]),
|
| 338 |
-
low=float(row["Low"]),
|
| 339 |
-
close=float(row["Close"]),
|
| 340 |
-
volume=int(row["Volume"]) if "Volume" in row else 0
|
| 341 |
-
)
|
| 342 |
-
)
|
| 343 |
-
return history_list
|
| 344 |
-
except Exception as e:
|
| 345 |
-
external_api_calls_total.labels(provider="yfinance", status="failed").inc()
|
| 346 |
-
print(f"Error fetching yfinance history for {ticker}: {str(e)}")
|
| 347 |
-
# Failover fallback
|
| 348 |
-
local_data = await crud.get_stock_history(db, ticker, limit=100)
|
| 349 |
-
return [
|
| 350 |
-
StockHistoryType(
|
| 351 |
-
id=h.id,
|
| 352 |
-
ticker=h.ticker,
|
| 353 |
-
timestamp=h.timestamp,
|
| 354 |
-
open=h.open,
|
| 355 |
-
high=h.high,
|
| 356 |
-
low=h.low,
|
| 357 |
-
close=h.close,
|
| 358 |
-
volume=h.volume
|
| 359 |
-
) for h in local_data
|
| 360 |
-
]
|
| 361 |
|
| 362 |
@strawberry.field
|
| 363 |
async def recently_analyzed(self, info: Info, limit: Optional[int] = 5) -> List[str]:
|
|
|
|
| 246 |
async def stock_history(self, info: Info, ticker: str, range: str = "1d") -> List[StockHistoryType]:
|
| 247 |
"""Fetch historical aggregated candles for a ticker based on range (1d, 5d, 1m, 6m, ytd, 1y, 5y, max)."""
|
| 248 |
db = info.context["db"]
|
| 249 |
+
rows = await gemini.fetch_stock_history_rows(db, ticker, range)
|
| 250 |
+
return [
|
| 251 |
+
StockHistoryType(
|
| 252 |
+
id=idx,
|
| 253 |
+
ticker=ticker.upper(),
|
| 254 |
+
timestamp=row["timestamp"],
|
| 255 |
+
open=row["open"],
|
| 256 |
+
high=row["high"],
|
| 257 |
+
low=row["low"],
|
| 258 |
+
close=row["close"],
|
| 259 |
+
volume=row["volume"]
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 260 |
)
|
| 261 |
+
for idx, row in enumerate(rows)
|
| 262 |
+
]
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 263 |
|
| 264 |
@strawberry.field
|
| 265 |
async def recently_analyzed(self, info: Info, limit: Optional[int] = 5) -> List[str]:
|
backend/app/services/gemini.py
CHANGED
|
@@ -17,7 +17,8 @@ from backend.app.config.metrics import (
|
|
| 17 |
llm_tokens_total,
|
| 18 |
agent_steps_total,
|
| 19 |
agent_latency_seconds,
|
| 20 |
-
agent_tool_calls_total
|
|
|
|
| 21 |
)
|
| 22 |
|
| 23 |
# Global variables for ONNX inference sessions and hot-reloading metadata
|
|
@@ -221,6 +222,222 @@ def _fetch_yf_daily_cached(ticker_upper: str, period: str = "60d") -> "pd.DataFr
|
|
| 221 |
return df
|
| 222 |
|
| 223 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 224 |
async def compute_atr_levels(
|
| 225 |
history: list,
|
| 226 |
close_price: float,
|
|
|
|
| 17 |
llm_tokens_total,
|
| 18 |
agent_steps_total,
|
| 19 |
agent_latency_seconds,
|
| 20 |
+
agent_tool_calls_total,
|
| 21 |
+
external_api_calls_total
|
| 22 |
)
|
| 23 |
|
| 24 |
# Global variables for ONNX inference sessions and hot-reloading metadata
|
|
|
|
| 222 |
return df
|
| 223 |
|
| 224 |
|
| 225 |
+
# Range → yfinance period/interval mapping, shared by the chart history GraphQL
|
| 226 |
+
# query and the /api/v1/indicators REST endpoint so indicator series stay aligned
|
| 227 |
+
# with the exact candles rendered on the chart.
|
| 228 |
+
RANGE_MAPPING = {
|
| 229 |
+
"1d": {"period": "1d", "interval": "2m"},
|
| 230 |
+
"5d": {"period": "5d", "interval": "15m"},
|
| 231 |
+
"1m": {"period": "1mo", "interval": "1d"},
|
| 232 |
+
"6m": {"period": "6mo", "interval": "1d"},
|
| 233 |
+
"ytd": {"period": "ytd", "interval": "1d"},
|
| 234 |
+
"1y": {"period": "1y", "interval": "1d"},
|
| 235 |
+
"5y": {"period": "5y", "interval": "1wk"},
|
| 236 |
+
"max": {"period": "max", "interval": "1mo"}
|
| 237 |
+
}
|
| 238 |
+
|
| 239 |
+
|
| 240 |
+
async def fetch_stock_history_rows(db: AsyncSession, ticker: str, range: str = "1d") -> list:
|
| 241 |
+
"""
|
| 242 |
+
Fetches historical aggregated candles for a ticker based on range
|
| 243 |
+
(1d, 5d, 1m, 6m, ytd, 1y, 5y, max).
|
| 244 |
+
|
| 245 |
+
Serves as the single source of truth for both the ``stockHistory`` GraphQL
|
| 246 |
+
query and the ``/api/v1/indicators`` REST endpoint. Returns a list of dicts:
|
| 247 |
+
``{timestamp, open, high, low, close, volume}`` where ``timestamp`` is a
|
| 248 |
+
tz-naive ``datetime.datetime``.
|
| 249 |
+
|
| 250 |
+
- ``1d`` prefers the locally ingested live candles (Postgres) when available.
|
| 251 |
+
- All other ranges are fetched from Yahoo Finance in a thread pool.
|
| 252 |
+
- Falls back to local DB rows if yfinance is unreachable.
|
| 253 |
+
"""
|
| 254 |
+
selected_range = (range or "1d").lower()
|
| 255 |
+
config = RANGE_MAPPING.get(selected_range, RANGE_MAPPING["1d"])
|
| 256 |
+
|
| 257 |
+
# If it's 1d, try local DB first
|
| 258 |
+
if selected_range == "1d":
|
| 259 |
+
try:
|
| 260 |
+
local_data = await crud.get_stock_history(db, ticker, limit=100)
|
| 261 |
+
|
| 262 |
+
# Filter out flat closed candles (zero volume and zero movement) for non-crypto assets
|
| 263 |
+
is_crypto = ticker.upper().endswith("-USD") or ticker.upper().endswith("-BTC")
|
| 264 |
+
if not is_crypto:
|
| 265 |
+
local_data = [h for h in local_data if not (h.open == h.close and h.volume == 0)]
|
| 266 |
+
|
| 267 |
+
if len(local_data) > 10:
|
| 268 |
+
return [
|
| 269 |
+
{
|
| 270 |
+
"timestamp": h.timestamp,
|
| 271 |
+
"open": h.open,
|
| 272 |
+
"high": h.high,
|
| 273 |
+
"low": h.low,
|
| 274 |
+
"close": h.close,
|
| 275 |
+
"volume": h.volume,
|
| 276 |
+
}
|
| 277 |
+
for h in local_data
|
| 278 |
+
]
|
| 279 |
+
except Exception as db_err:
|
| 280 |
+
print(f"Error querying local DB for ticker history: {db_err}")
|
| 281 |
+
|
| 282 |
+
# Otherwise, dynamically fetch from Yahoo Finance in a thread pool
|
| 283 |
+
try:
|
| 284 |
+
import yfinance as yf
|
| 285 |
+
loop = asyncio.get_event_loop()
|
| 286 |
+
yf_ticker = yf.Ticker(ticker)
|
| 287 |
+
|
| 288 |
+
df = await loop.run_in_executor(
|
| 289 |
+
None,
|
| 290 |
+
lambda: yf_ticker.history(period=config["period"], interval=config["interval"])
|
| 291 |
+
)
|
| 292 |
+
external_api_calls_total.labels(provider="yfinance", status="success").inc()
|
| 293 |
+
|
| 294 |
+
rows = []
|
| 295 |
+
if not df.empty:
|
| 296 |
+
df = df.reset_index()
|
| 297 |
+
|
| 298 |
+
time_col = None
|
| 299 |
+
for col in ['Date', 'Datetime', 'index', 'timestamp']:
|
| 300 |
+
if col in df.columns:
|
| 301 |
+
time_col = col
|
| 302 |
+
break
|
| 303 |
+
|
| 304 |
+
if time_col:
|
| 305 |
+
# Limit to last 350 points to ensure smooth chart performance
|
| 306 |
+
df = df.tail(350)
|
| 307 |
+
for _, row in df.iterrows():
|
| 308 |
+
ts = row[time_col]
|
| 309 |
+
if hasattr(ts, 'to_pydatetime'):
|
| 310 |
+
ts_dt = ts.to_pydatetime()
|
| 311 |
+
elif isinstance(ts, str):
|
| 312 |
+
ts_dt = datetime.datetime.fromisoformat(ts)
|
| 313 |
+
else:
|
| 314 |
+
ts_dt = ts
|
| 315 |
+
|
| 316 |
+
if ts_dt.tzinfo is not None:
|
| 317 |
+
ts_dt = ts_dt.replace(tzinfo=None)
|
| 318 |
+
|
| 319 |
+
rows.append({
|
| 320 |
+
"timestamp": ts_dt,
|
| 321 |
+
"open": float(row["Open"]),
|
| 322 |
+
"high": float(row["High"]),
|
| 323 |
+
"low": float(row["Low"]),
|
| 324 |
+
"close": float(row["Close"]),
|
| 325 |
+
"volume": int(row["Volume"]) if "Volume" in row else 0,
|
| 326 |
+
})
|
| 327 |
+
return rows
|
| 328 |
+
except Exception as e:
|
| 329 |
+
external_api_calls_total.labels(provider="yfinance", status="failed").inc()
|
| 330 |
+
print(f"Error fetching yfinance history for {ticker}: {str(e)}")
|
| 331 |
+
# Failover fallback
|
| 332 |
+
local_data = await crud.get_stock_history(db, ticker, limit=100)
|
| 333 |
+
return [
|
| 334 |
+
{
|
| 335 |
+
"timestamp": h.timestamp,
|
| 336 |
+
"open": h.open,
|
| 337 |
+
"high": h.high,
|
| 338 |
+
"low": h.low,
|
| 339 |
+
"close": h.close,
|
| 340 |
+
"volume": h.volume,
|
| 341 |
+
}
|
| 342 |
+
for h in local_data
|
| 343 |
+
]
|
| 344 |
+
|
| 345 |
+
|
| 346 |
+
async def compute_chart_indicators(db: AsyncSession, ticker: str, range: str = "1d") -> dict:
|
| 347 |
+
"""
|
| 348 |
+
Computes MACD (12/26/9) and Bollinger Bands (20, 2) series for chart visualization.
|
| 349 |
+
|
| 350 |
+
Uses the exact same pandas-ta calculations the backend ML model relies on under
|
| 351 |
+
the hood (``ta.macd`` / ``ta.bbands``), so the visual overlays mirror the
|
| 352 |
+
features the Random Forest model is trained on. Series are aligned by epoch
|
| 353 |
+
timestamp with the candles returned by ``stockHistory``.
|
| 354 |
+
|
| 355 |
+
Returns::
|
| 356 |
+
|
| 357 |
+
{
|
| 358 |
+
"macd": {
|
| 359 |
+
"line": [{"time": <epoch_secs>, "value": <float|null>}, ...],
|
| 360 |
+
"signal": [...],
|
| 361 |
+
"histogram": [...]
|
| 362 |
+
},
|
| 363 |
+
"bollinger_bands": {
|
| 364 |
+
"upper": [...],
|
| 365 |
+
"middle": [...],
|
| 366 |
+
"lower": [...]
|
| 367 |
+
},
|
| 368 |
+
"candle_count": int
|
| 369 |
+
}
|
| 370 |
+
"""
|
| 371 |
+
import math
|
| 372 |
+
import pandas as pd
|
| 373 |
+
import pandas_ta as ta
|
| 374 |
+
|
| 375 |
+
empty = {
|
| 376 |
+
"macd": {"line": [], "signal": [], "histogram": []},
|
| 377 |
+
"bollinger_bands": {"upper": [], "middle": [], "lower": []},
|
| 378 |
+
"candle_count": 0,
|
| 379 |
+
}
|
| 380 |
+
|
| 381 |
+
rows = await fetch_stock_history_rows(db, ticker, range)
|
| 382 |
+
if not rows:
|
| 383 |
+
return empty
|
| 384 |
+
|
| 385 |
+
df = pd.DataFrame([{
|
| 386 |
+
"timestamp": r["timestamp"],
|
| 387 |
+
"open": float(r["open"]),
|
| 388 |
+
"high": float(r["high"]),
|
| 389 |
+
"low": float(r["low"]),
|
| 390 |
+
"close": float(r["close"]),
|
| 391 |
+
"volume": float(r.get("volume") or 0),
|
| 392 |
+
} for r in rows])
|
| 393 |
+
|
| 394 |
+
# Epoch seconds (local-time interpretation, matches frontend Date.parse of ISO strings)
|
| 395 |
+
epochs = [int(ts.timestamp()) for ts in df["timestamp"].tolist()]
|
| 396 |
+
|
| 397 |
+
# ── Compute indicators exactly like the ML model's feature pipeline ──
|
| 398 |
+
df.ta.macd(close="close", fast=12, slow=26, signal=9, append=True)
|
| 399 |
+
df.ta.bbands(close="close", length=20, std=2, append=True)
|
| 400 |
+
|
| 401 |
+
def find_col(prefix: str) -> str:
|
| 402 |
+
for col in df.columns:
|
| 403 |
+
if col.startswith(prefix):
|
| 404 |
+
return col
|
| 405 |
+
return None
|
| 406 |
+
|
| 407 |
+
macd_col = find_col("MACD_")
|
| 408 |
+
macds_col = find_col("MACDs_")
|
| 409 |
+
macdh_col = find_col("MACDh_")
|
| 410 |
+
bbu_col = find_col("BBU_")
|
| 411 |
+
bbm_col = find_col("BBM_")
|
| 412 |
+
bbl_col = find_col("BBL_")
|
| 413 |
+
|
| 414 |
+
def series(column) -> list:
|
| 415 |
+
"""Convert a pandas column to [{time, value}] with NaN → null (JSON-safe)."""
|
| 416 |
+
out = []
|
| 417 |
+
if column is None:
|
| 418 |
+
return out
|
| 419 |
+
for t, v in zip(epochs, df[column].tolist()):
|
| 420 |
+
if v is None or (isinstance(v, float) and math.isnan(v)):
|
| 421 |
+
out.append({"time": t, "value": None})
|
| 422 |
+
else:
|
| 423 |
+
out.append({"time": t, "value": round(float(v), 6)})
|
| 424 |
+
return out
|
| 425 |
+
|
| 426 |
+
return {
|
| 427 |
+
"macd": {
|
| 428 |
+
"line": series(macd_col),
|
| 429 |
+
"signal": series(macds_col),
|
| 430 |
+
"histogram": series(macdh_col),
|
| 431 |
+
},
|
| 432 |
+
"bollinger_bands": {
|
| 433 |
+
"upper": series(bbu_col),
|
| 434 |
+
"middle": series(bbm_col),
|
| 435 |
+
"lower": series(bbl_col),
|
| 436 |
+
},
|
| 437 |
+
"candle_count": len(df),
|
| 438 |
+
}
|
| 439 |
+
|
| 440 |
+
|
| 441 |
async def compute_atr_levels(
|
| 442 |
history: list,
|
| 443 |
close_price: float,
|
frontend/src/App.css
CHANGED
|
@@ -538,6 +538,25 @@
|
|
| 538 |
position: relative;
|
| 539 |
}
|
| 540 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 541 |
/* ─── 6. AI Analyst Panel ───────────────── */
|
| 542 |
.insight-panel {
|
| 543 |
padding: 20px;
|
|
|
|
| 538 |
position: relative;
|
| 539 |
}
|
| 540 |
|
| 541 |
+
/* Technical Indicator Sub-Panes (RSI / MACD stacked below the price chart) */
|
| 542 |
+
.chart-indicator-pane {
|
| 543 |
+
border-radius: 8px;
|
| 544 |
+
background: rgba(255, 255, 255, 0.008);
|
| 545 |
+
padding-bottom: 4px;
|
| 546 |
+
transition: opacity 0.2s ease;
|
| 547 |
+
}
|
| 548 |
+
|
| 549 |
+
/* MACD / Bollinger toggle accents for the Technical Overlays toolbar */
|
| 550 |
+
.control-toggle-btn.indicator-macd.active {
|
| 551 |
+
color: var(--neon-violet) !important;
|
| 552 |
+
background: rgba(161, 84, 255, 0.1) !important;
|
| 553 |
+
}
|
| 554 |
+
|
| 555 |
+
.control-toggle-btn.indicator-bb.active {
|
| 556 |
+
color: #f59e0b !important;
|
| 557 |
+
background: rgba(245, 158, 11, 0.1) !important;
|
| 558 |
+
}
|
| 559 |
+
|
| 560 |
/* ─── 6. AI Analyst Panel ───────────────── */
|
| 561 |
.insight-panel {
|
| 562 |
padding: 20px;
|
frontend/src/App.tsx
CHANGED
|
@@ -267,6 +267,8 @@ export default function App() {
|
|
| 267 |
const lowVal = parseFloat((h.low !== null && h.low !== undefined ? h.low : h.close).toFixed(2));
|
| 268 |
return {
|
| 269 |
time: timeLabel,
|
|
|
|
|
|
|
| 270 |
price: closeVal,
|
| 271 |
open: openVal,
|
| 272 |
high: highVal,
|
|
@@ -353,6 +355,7 @@ export default function App() {
|
|
| 353 |
});
|
| 354 |
|
| 355 |
const tickTime = new Date(tick.timestamp).toLocaleTimeString([], { hour: '2-digit', minute: '2-digit' });
|
|
|
|
| 356 |
|
| 357 |
setChartData((prevData) => {
|
| 358 |
const updated = [...prevData];
|
|
@@ -366,6 +369,7 @@ export default function App() {
|
|
| 366 |
|
| 367 |
updated[updated.length - 1] = {
|
| 368 |
time: tickTime,
|
|
|
|
| 369 |
price: newPrice,
|
| 370 |
open: openVal,
|
| 371 |
high: highVal,
|
|
@@ -379,6 +383,7 @@ export default function App() {
|
|
| 379 |
...updated,
|
| 380 |
{
|
| 381 |
time: tickTime,
|
|
|
|
| 382 |
price: newPrice,
|
| 383 |
open: newPrice,
|
| 384 |
high: newPrice,
|
|
|
|
| 267 |
const lowVal = parseFloat((h.low !== null && h.low !== undefined ? h.low : h.close).toFixed(2));
|
| 268 |
return {
|
| 269 |
time: timeLabel,
|
| 270 |
+
// Epoch seconds of the candle — used to align backend indicator series (MACD/BB) with the chart
|
| 271 |
+
ts: Math.floor(new Date(h.timestamp).getTime() / 1000),
|
| 272 |
price: closeVal,
|
| 273 |
open: openVal,
|
| 274 |
high: highVal,
|
|
|
|
| 355 |
});
|
| 356 |
|
| 357 |
const tickTime = new Date(tick.timestamp).toLocaleTimeString([], { hour: '2-digit', minute: '2-digit' });
|
| 358 |
+
const tickTs = Math.floor(new Date(tick.timestamp).getTime() / 1000);
|
| 359 |
|
| 360 |
setChartData((prevData) => {
|
| 361 |
const updated = [...prevData];
|
|
|
|
| 369 |
|
| 370 |
updated[updated.length - 1] = {
|
| 371 |
time: tickTime,
|
| 372 |
+
ts: last.ts ?? tickTs,
|
| 373 |
price: newPrice,
|
| 374 |
open: openVal,
|
| 375 |
high: highVal,
|
|
|
|
| 383 |
...updated,
|
| 384 |
{
|
| 385 |
time: tickTime,
|
| 386 |
+
ts: tickTs,
|
| 387 |
price: newPrice,
|
| 388 |
open: newPrice,
|
| 389 |
high: newPrice,
|
frontend/src/components/ChartChatbot.tsx
CHANGED
|
@@ -5,7 +5,7 @@ import Logo from './Logo';
|
|
| 5 |
interface ChartChatbotProps {
|
| 6 |
ticker: string;
|
| 7 |
markers: Array<{ price: number; label: string; color: string }>;
|
| 8 |
-
activeIndicators: { sma: boolean; ema: boolean; rsi: boolean };
|
| 9 |
user: any;
|
| 10 |
onOpenRecharge?: () => void;
|
| 11 |
liveData?: {
|
|
|
|
| 5 |
interface ChartChatbotProps {
|
| 6 |
ticker: string;
|
| 7 |
markers: Array<{ price: number; label: string; color: string }>;
|
| 8 |
+
activeIndicators: { sma: boolean; ema: boolean; rsi: boolean; macd: boolean; bb: boolean };
|
| 9 |
user: any;
|
| 10 |
onOpenRecharge?: () => void;
|
| 11 |
liveData?: {
|
frontend/src/components/StockChart.tsx
CHANGED
|
@@ -1,17 +1,29 @@
|
|
| 1 |
import { useState, useEffect, useRef } from 'react';
|
| 2 |
-
import { ResponsiveContainer, ComposedChart, Area, Bar, Line, XAxis, YAxis, Tooltip, ReferenceLine, LineChart } from 'recharts';
|
| 3 |
import { AreaChart as AreaIcon, BarChart2 as CandleIcon, Activity, Eye, EyeOff, Maximize2, Minimize2 } from 'lucide-react';
|
| 4 |
import ChartChatbot from './ChartChatbot';
|
| 5 |
|
|
|
|
|
|
|
| 6 |
|
| 7 |
interface ChartDataPoint {
|
| 8 |
time: string;
|
|
|
|
|
|
|
| 9 |
price: number;
|
| 10 |
open?: number;
|
| 11 |
high?: number;
|
| 12 |
low?: number;
|
| 13 |
close?: number;
|
| 14 |
range?: [number, number];
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 15 |
}
|
| 16 |
|
| 17 |
interface StockChartProps {
|
|
@@ -150,6 +162,30 @@ const CustomTooltip = ({ active, payload, label }: any) => {
|
|
| 150 |
</div>
|
| 151 |
);
|
| 152 |
}
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 153 |
return null;
|
| 154 |
})}
|
| 155 |
</div>
|
|
@@ -158,6 +194,35 @@ const CustomTooltip = ({ active, payload, label }: any) => {
|
|
| 158 |
return null;
|
| 159 |
};
|
| 160 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 161 |
export default function StockChart({ activeTicker, chartData, activeStats, chartRange, onRangeChange, user, onOpenRecharge }: StockChartProps) {
|
| 162 |
const currentPrice = chartData.length > 0 ? chartData[chartData.length - 1].price : null;
|
| 163 |
|
|
@@ -182,6 +247,16 @@ export default function StockChart({ activeTicker, chartData, activeStats, chart
|
|
| 182 |
const saved = localStorage.getItem(`quantiq_show_rsi_${email}_${activeTicker}`);
|
| 183 |
return saved === 'true';
|
| 184 |
});
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 185 |
const [isMaximized, setIsMaximized] = useState<boolean>(() => {
|
| 186 |
return sessionStorage.getItem('quantiq_restore_maximized_chart') === 'true';
|
| 187 |
});
|
|
@@ -217,6 +292,50 @@ export default function StockChart({ activeTicker, chartData, activeStats, chart
|
|
| 217 |
localStorage.setItem(`quantiq_show_rsi_${email}_${activeTicker}`, String(showRSI));
|
| 218 |
}, [showRSI, activeTicker, user]);
|
| 219 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 220 |
// Zoom Factor and Scroll/Pan states — active always (Binance-style interactions)
|
| 221 |
const [zoomFactor, setZoomFactor] = useState<number>(1.0);
|
| 222 |
const [scrollIndex, setScrollIndex] = useState<number>(0);
|
|
@@ -386,8 +505,9 @@ export default function StockChart({ activeTicker, chartData, activeStats, chart
|
|
| 386 |
});
|
| 387 |
};
|
| 388 |
|
| 389 |
-
// Pipeline processed chart data
|
| 390 |
-
|
|
|
|
| 391 |
if (showSMA) processedData = computeSMA(processedData, 20);
|
| 392 |
if (showEMA) processedData = computeEMA(processedData, 20);
|
| 393 |
|
|
@@ -416,6 +536,12 @@ export default function StockChart({ activeTicker, chartData, activeStats, chart
|
|
| 416 |
? rsiData.slice(currentScrollIndex, currentScrollIndex + visibleCount)
|
| 417 |
: rsiData;
|
| 418 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 419 |
// Calculate global Y-axis domain bounds dynamically to prevent clipping
|
| 420 |
// Filter to only finite, positive numbers to prevent garbage values like NaN/Infinity
|
| 421 |
// from corrupting Math.min/max and producing labels like 'i1499999986'
|
|
@@ -424,13 +550,29 @@ export default function StockChart({ activeTicker, chartData, activeStats, chart
|
|
| 424 |
const highs = filterFinite(visibleData.map(d => d.high ?? d.price));
|
| 425 |
const lows = filterFinite(visibleData.map(d => d.low ?? d.price));
|
| 426 |
|
| 427 |
-
|
| 428 |
-
const
|
|
|
|
|
|
|
|
|
|
|
|
|
| 429 |
|
| 430 |
// Add 5% padding to top/bottom to prevent lines touching borders
|
| 431 |
const yMin = rawMinPrice === rawMaxPrice ? rawMinPrice * 0.95 : (rawMinPrice > 0 ? rawMinPrice * 0.95 : rawMinPrice);
|
| 432 |
const yMax = rawMinPrice === rawMaxPrice ? rawMaxPrice * 1.05 : rawMaxPrice * 1.05;
|
| 433 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 434 |
// Mouse-wheel zoom is now handled via non-passive native addEventListener above.
|
| 435 |
// Drag-to-pan handlers (Binance-style: click + drag left/right to pan)
|
| 436 |
const handleMouseDown = (e: React.MouseEvent<HTMLDivElement>) => {
|
|
@@ -632,6 +774,24 @@ export default function StockChart({ activeTicker, chartData, activeStats, chart
|
|
| 632 |
<Activity size={13} />
|
| 633 |
RSI 14
|
| 634 |
</button>
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 635 |
</div>
|
| 636 |
</div>
|
| 637 |
|
|
@@ -738,7 +898,7 @@ export default function StockChart({ activeTicker, chartData, activeStats, chart
|
|
| 738 |
padding: isMaximized ? '16px 24px 24px' : '16px 16px 32px',
|
| 739 |
flex: 'unset',
|
| 740 |
flexShrink: 0,
|
| 741 |
-
height: isMaximized ?
|
| 742 |
}}>
|
| 743 |
{/* Floating Add Marker Form */}
|
| 744 |
{showAddMarkerForm && (
|
|
@@ -853,9 +1013,7 @@ export default function StockChart({ activeTicker, chartData, activeStats, chart
|
|
| 853 |
onMouseUp={handleMouseUp}
|
| 854 |
onMouseLeave={handleMouseLeave}
|
| 855 |
style={{
|
| 856 |
-
height:
|
| 857 |
-
? (isMaximized ? (isZoomed ? '62%' : '72%') : 'calc(100% - 110px)')
|
| 858 |
-
: (isMaximized ? (isZoomed ? '86%' : '100%') : '100%'),
|
| 859 |
width: '100%',
|
| 860 |
position: 'relative',
|
| 861 |
cursor: isZoomed ? (isDragging.current ? 'grabbing' : 'grab') : 'crosshair',
|
|
@@ -954,6 +1112,38 @@ export default function StockChart({ activeTicker, chartData, activeStats, chart
|
|
| 954 |
name="EMA 20"
|
| 955 |
/>
|
| 956 |
)}
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 957 |
</ComposedChart>
|
| 958 |
</ResponsiveContainer>
|
| 959 |
</div>
|
|
@@ -991,7 +1181,7 @@ export default function StockChart({ activeTicker, chartData, activeStats, chart
|
|
| 991 |
|
| 992 |
{/* Technical Indicator panel: RSI 14 (Auxiliary Chart below main price chart) */}
|
| 993 |
{showRSI && visibleRsiData.length > 0 && (
|
| 994 |
-
<div style={{ height:
|
| 995 |
<div style={{ display: 'flex', justifyContent: 'space-between', fontSize: '11px', color: 'var(--text-secondary)', marginBottom: '4px', paddingLeft: '10px' }}>
|
| 996 |
<span style={{ fontWeight: 700, color: 'var(--neon-cyan)' }}>RSI (14)</span>
|
| 997 |
<span style={{ color: 'var(--text-muted)' }}>Overbought >70 | Oversold <30</span>
|
|
@@ -1027,6 +1217,60 @@ export default function StockChart({ activeTicker, chartData, activeStats, chart
|
|
| 1027 |
</ResponsiveContainer>
|
| 1028 |
</div>
|
| 1029 |
)}
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1030 |
</div> {/* closes chart-container */}
|
| 1031 |
</div> {/* closes Left Column */}
|
| 1032 |
|
|
@@ -1035,7 +1279,7 @@ export default function StockChart({ activeTicker, chartData, activeStats, chart
|
|
| 1035 |
<ChartChatbot
|
| 1036 |
ticker={activeTicker}
|
| 1037 |
markers={markers}
|
| 1038 |
-
activeIndicators={{ sma: showSMA, ema: showEMA, rsi: showRSI }}
|
| 1039 |
user={user}
|
| 1040 |
onOpenRecharge={onOpenRecharge}
|
| 1041 |
liveData={chatbotLiveData}
|
|
|
|
| 1 |
import { useState, useEffect, useRef } from 'react';
|
| 2 |
+
import { ResponsiveContainer, ComposedChart, Area, Bar, Cell, Line, XAxis, YAxis, Tooltip, ReferenceLine, LineChart } from 'recharts';
|
| 3 |
import { AreaChart as AreaIcon, BarChart2 as CandleIcon, Activity, Eye, EyeOff, Maximize2, Minimize2 } from 'lucide-react';
|
| 4 |
import ChartChatbot from './ChartChatbot';
|
| 5 |
|
| 6 |
+
// Backend REST base URL (matches the rest of the frontend)
|
| 7 |
+
const API_URL = import.meta.env.VITE_API_URL || 'http://localhost:8000';
|
| 8 |
|
| 9 |
interface ChartDataPoint {
|
| 10 |
time: string;
|
| 11 |
+
// Epoch seconds of the candle — used to align backend indicator series with the chart
|
| 12 |
+
ts?: number;
|
| 13 |
price: number;
|
| 14 |
open?: number;
|
| 15 |
high?: number;
|
| 16 |
low?: number;
|
| 17 |
close?: number;
|
| 18 |
range?: [number, number];
|
| 19 |
+
// Bollinger Bands (aligned by ts from /api/v1/indicators)
|
| 20 |
+
bb_upper?: number | null;
|
| 21 |
+
bb_middle?: number | null;
|
| 22 |
+
bb_lower?: number | null;
|
| 23 |
+
// MACD (aligned by ts from /api/v1/indicators)
|
| 24 |
+
macd?: number | null;
|
| 25 |
+
macd_signal?: number | null;
|
| 26 |
+
macd_hist?: number | null;
|
| 27 |
}
|
| 28 |
|
| 29 |
interface StockChartProps {
|
|
|
|
| 162 |
</div>
|
| 163 |
);
|
| 164 |
}
|
| 165 |
+
if (entry.dataKey === 'bb_upper' && entry.value !== undefined && entry.value !== null) {
|
| 166 |
+
return (
|
| 167 |
+
<div key={`bbu-${index}`} style={{ display: 'flex', justifyContent: 'space-between', gap: '16px', color: '#a154ff', borderTop: '1px solid rgba(255,255,255,0.06)', paddingTop: '4px', marginTop: '4px' }}>
|
| 168 |
+
<span>BB Upper</span>
|
| 169 |
+
<span style={{ fontWeight: 600 }}>${entry.value.toFixed(2)}</span>
|
| 170 |
+
</div>
|
| 171 |
+
);
|
| 172 |
+
}
|
| 173 |
+
if (entry.dataKey === 'bb_middle' && entry.value !== undefined && entry.value !== null) {
|
| 174 |
+
return (
|
| 175 |
+
<div key={`bbm-${index}`} style={{ display: 'flex', justifyContent: 'space-between', gap: '16px', color: '#f59e0b', borderTop: '1px solid rgba(255,255,255,0.06)', paddingTop: '4px', marginTop: '4px' }}>
|
| 176 |
+
<span>BB Middle</span>
|
| 177 |
+
<span style={{ fontWeight: 600 }}>${entry.value.toFixed(2)}</span>
|
| 178 |
+
</div>
|
| 179 |
+
);
|
| 180 |
+
}
|
| 181 |
+
if (entry.dataKey === 'bb_lower' && entry.value !== undefined && entry.value !== null) {
|
| 182 |
+
return (
|
| 183 |
+
<div key={`bbl-${index}`} style={{ display: 'flex', justifyContent: 'space-between', gap: '16px', color: '#a154ff', borderTop: '1px solid rgba(255,255,255,0.06)', paddingTop: '4px', marginTop: '4px' }}>
|
| 184 |
+
<span>BB Lower</span>
|
| 185 |
+
<span style={{ fontWeight: 600 }}>${entry.value.toFixed(2)}</span>
|
| 186 |
+
</div>
|
| 187 |
+
);
|
| 188 |
+
}
|
| 189 |
return null;
|
| 190 |
})}
|
| 191 |
</div>
|
|
|
|
| 194 |
return null;
|
| 195 |
};
|
| 196 |
|
| 197 |
+
// Merges backend-computed indicator series (from /api/v1/indicators) into the chart
|
| 198 |
+
// data, keyed by each candle's epoch timestamp (ts). Any candle without a matching
|
| 199 |
+
// backend value (e.g. live ticks appended after the fetch) falls back to null so
|
| 200 |
+
// recharts simply leaves a gap instead of drawing garbage.
|
| 201 |
+
const mergeIndicators = (data: ChartDataPoint[], ind: any): ChartDataPoint[] => {
|
| 202 |
+
if (!ind) return data;
|
| 203 |
+
const toMap = (arr?: any[]) => new Map((arr || []).map((p: any) => [p.time, p.value]));
|
| 204 |
+
|
| 205 |
+
const bbUpper = toMap(ind.bollinger_bands?.upper);
|
| 206 |
+
const bbMiddle = toMap(ind.bollinger_bands?.middle);
|
| 207 |
+
const bbLower = toMap(ind.bollinger_bands?.lower);
|
| 208 |
+
const macdLine = toMap(ind.macd?.line);
|
| 209 |
+
const macdSignal = toMap(ind.macd?.signal);
|
| 210 |
+
const macdHist = toMap(ind.macd?.histogram);
|
| 211 |
+
|
| 212 |
+
return data.map((d) => {
|
| 213 |
+
const t = d.ts;
|
| 214 |
+
return {
|
| 215 |
+
...d,
|
| 216 |
+
bb_upper: t !== undefined && bbUpper.has(t) ? bbUpper.get(t) : null,
|
| 217 |
+
bb_middle: t !== undefined && bbMiddle.has(t) ? bbMiddle.get(t) : null,
|
| 218 |
+
bb_lower: t !== undefined && bbLower.has(t) ? bbLower.get(t) : null,
|
| 219 |
+
macd: t !== undefined && macdLine.has(t) ? macdLine.get(t) : null,
|
| 220 |
+
macd_signal: t !== undefined && macdSignal.has(t) ? macdSignal.get(t) : null,
|
| 221 |
+
macd_hist: t !== undefined && macdHist.has(t) ? macdHist.get(t) : null,
|
| 222 |
+
};
|
| 223 |
+
});
|
| 224 |
+
};
|
| 225 |
+
|
| 226 |
export default function StockChart({ activeTicker, chartData, activeStats, chartRange, onRangeChange, user, onOpenRecharge }: StockChartProps) {
|
| 227 |
const currentPrice = chartData.length > 0 ? chartData[chartData.length - 1].price : null;
|
| 228 |
|
|
|
|
| 247 |
const saved = localStorage.getItem(`quantiq_show_rsi_${email}_${activeTicker}`);
|
| 248 |
return saved === 'true';
|
| 249 |
});
|
| 250 |
+
const [showMACD, setShowMACD] = useState<boolean>(() => {
|
| 251 |
+
const email = localStorage.getItem('quantiq_last_logged_in_email') || 'generic';
|
| 252 |
+
const saved = localStorage.getItem(`quantiq_show_macd_${email}_${activeTicker}`);
|
| 253 |
+
return saved === 'true';
|
| 254 |
+
});
|
| 255 |
+
const [showBB, setShowBB] = useState<boolean>(() => {
|
| 256 |
+
const email = localStorage.getItem('quantiq_last_logged_in_email') || 'generic';
|
| 257 |
+
const saved = localStorage.getItem(`quantiq_show_bb_${email}_${activeTicker}`);
|
| 258 |
+
return saved === 'true';
|
| 259 |
+
});
|
| 260 |
const [isMaximized, setIsMaximized] = useState<boolean>(() => {
|
| 261 |
return sessionStorage.getItem('quantiq_restore_maximized_chart') === 'true';
|
| 262 |
});
|
|
|
|
| 292 |
localStorage.setItem(`quantiq_show_rsi_${email}_${activeTicker}`, String(showRSI));
|
| 293 |
}, [showRSI, activeTicker, user]);
|
| 294 |
|
| 295 |
+
useEffect(() => {
|
| 296 |
+
const email = user?.email || localStorage.getItem('quantiq_last_logged_in_email') || 'generic';
|
| 297 |
+
localStorage.setItem(`quantiq_show_macd_${email}_${activeTicker}`, String(showMACD));
|
| 298 |
+
}, [showMACD, activeTicker, user]);
|
| 299 |
+
|
| 300 |
+
useEffect(() => {
|
| 301 |
+
const email = user?.email || localStorage.getItem('quantiq_last_logged_in_email') || 'generic';
|
| 302 |
+
localStorage.setItem(`quantiq_show_bb_${email}_${activeTicker}`, String(showBB));
|
| 303 |
+
}, [showBB, activeTicker, user]);
|
| 304 |
+
|
| 305 |
+
// ── Backend-computed indicators (MACD + Bollinger Bands) ──
|
| 306 |
+
// Fetched from /api/v1/indicators whenever MACD/BB is toggled on or the ticker /
|
| 307 |
+
// range changes. Series are aligned by epoch timestamp (ts) with the candles
|
| 308 |
+
// served by the stockHistory query, so they always line up with the chart.
|
| 309 |
+
const [indicatorData, setIndicatorData] = useState<any>(null);
|
| 310 |
+
const [indicatorLoading, setIndicatorLoading] = useState<boolean>(false);
|
| 311 |
+
|
| 312 |
+
useEffect(() => {
|
| 313 |
+
if (!showMACD && !showBB) {
|
| 314 |
+
setIndicatorData(null);
|
| 315 |
+
setIndicatorLoading(false);
|
| 316 |
+
return;
|
| 317 |
+
}
|
| 318 |
+
let cancelled = false;
|
| 319 |
+
setIndicatorLoading(true);
|
| 320 |
+
const url = `${API_URL}/api/v1/indicators?ticker=${encodeURIComponent(activeTicker)}&range=${encodeURIComponent(chartRange)}`;
|
| 321 |
+
fetch(url)
|
| 322 |
+
.then((res) => {
|
| 323 |
+
if (!res.ok) throw new Error(`Indicators API responded with ${res.status}`);
|
| 324 |
+
return res.json();
|
| 325 |
+
})
|
| 326 |
+
.then((data) => {
|
| 327 |
+
if (!cancelled) setIndicatorData(data);
|
| 328 |
+
})
|
| 329 |
+
.catch((err) => {
|
| 330 |
+
console.error('Failed to load chart indicators:', err);
|
| 331 |
+
if (!cancelled) setIndicatorData(null);
|
| 332 |
+
})
|
| 333 |
+
.finally(() => {
|
| 334 |
+
if (!cancelled) setIndicatorLoading(false);
|
| 335 |
+
});
|
| 336 |
+
return () => { cancelled = true; };
|
| 337 |
+
}, [activeTicker, chartRange, showMACD, showBB]);
|
| 338 |
+
|
| 339 |
// Zoom Factor and Scroll/Pan states — active always (Binance-style interactions)
|
| 340 |
const [zoomFactor, setZoomFactor] = useState<number>(1.0);
|
| 341 |
const [scrollIndex, setScrollIndex] = useState<number>(0);
|
|
|
|
| 505 |
});
|
| 506 |
};
|
| 507 |
|
| 508 |
+
// Pipeline processed chart data — enrich with backend MACD/BB series first,
|
| 509 |
+
// then apply the client-side SMA/EMA overlays.
|
| 510 |
+
let processedData = mergeIndicators([...chartData], indicatorData);
|
| 511 |
if (showSMA) processedData = computeSMA(processedData, 20);
|
| 512 |
if (showEMA) processedData = computeEMA(processedData, 20);
|
| 513 |
|
|
|
|
| 536 |
? rsiData.slice(currentScrollIndex, currentScrollIndex + visibleCount)
|
| 537 |
: rsiData;
|
| 538 |
|
| 539 |
+
// MACD data is enriched onto processedData by mergeIndicators (aligned by ts)
|
| 540 |
+
const macdData = showMACD ? processedData : [];
|
| 541 |
+
const visibleMacdData = isZoomed
|
| 542 |
+
? macdData.slice(currentScrollIndex, currentScrollIndex + visibleCount)
|
| 543 |
+
: macdData;
|
| 544 |
+
|
| 545 |
// Calculate global Y-axis domain bounds dynamically to prevent clipping
|
| 546 |
// Filter to only finite, positive numbers to prevent garbage values like NaN/Infinity
|
| 547 |
// from corrupting Math.min/max and producing labels like 'i1499999986'
|
|
|
|
| 550 |
const highs = filterFinite(visibleData.map(d => d.high ?? d.price));
|
| 551 |
const lows = filterFinite(visibleData.map(d => d.low ?? d.price));
|
| 552 |
|
| 553 |
+
// Include Bollinger Band extremes so the overlay never clips against the Y domain
|
| 554 |
+
const bbHighs = showBB ? filterFinite(visibleData.map(d => d.bb_upper as number)) : [];
|
| 555 |
+
const bbLows = showBB ? filterFinite(visibleData.map(d => d.bb_lower as number)) : [];
|
| 556 |
+
|
| 557 |
+
const rawMinPrice = prices.length > 0 ? Math.min(...lows.length > 0 ? lows : prices, ...prices, ...bbLows) : 0;
|
| 558 |
+
const rawMaxPrice = prices.length > 0 ? Math.max(...highs.length > 0 ? highs : prices, ...prices, ...bbHighs) : 100;
|
| 559 |
|
| 560 |
// Add 5% padding to top/bottom to prevent lines touching borders
|
| 561 |
const yMin = rawMinPrice === rawMaxPrice ? rawMinPrice * 0.95 : (rawMinPrice > 0 ? rawMinPrice * 0.95 : rawMinPrice);
|
| 562 |
const yMax = rawMinPrice === rawMaxPrice ? rawMaxPrice * 1.05 : rawMaxPrice * 1.05;
|
| 563 |
|
| 564 |
+
// Sub-pane sizing: RSI + MACD are stacked below the main chart. The container
|
| 565 |
+
// grows with each active pane and the main chart shrinks proportionally so the
|
| 566 |
+
// multi-pane layout stays balanced in both normal and maximized modes.
|
| 567 |
+
const subPaneCount = (showRSI ? 1 : 0) + (showMACD ? 1 : 0);
|
| 568 |
+
const subPanePct = isZoomed ? 18 : 24;
|
| 569 |
+
const mainChartHeight = isMaximized
|
| 570 |
+
? `calc(${100 - subPanePct * subPaneCount - (isZoomed ? 20 : 4)}%)`
|
| 571 |
+
: `calc(100% - ${110 * subPaneCount}px)`;
|
| 572 |
+
const subPaneHeight = isMaximized
|
| 573 |
+
? `calc(${subPanePct}%)`
|
| 574 |
+
: '100px';
|
| 575 |
+
|
| 576 |
// Mouse-wheel zoom is now handled via non-passive native addEventListener above.
|
| 577 |
// Drag-to-pan handlers (Binance-style: click + drag left/right to pan)
|
| 578 |
const handleMouseDown = (e: React.MouseEvent<HTMLDivElement>) => {
|
|
|
|
| 774 |
<Activity size={13} />
|
| 775 |
RSI 14
|
| 776 |
</button>
|
| 777 |
+
<button
|
| 778 |
+
onClick={() => setShowMACD(!showMACD)}
|
| 779 |
+
className={`control-toggle-btn indicator-macd ${showMACD ? 'active' : ''}`}
|
| 780 |
+
title="Moving Average Convergence Divergence"
|
| 781 |
+
style={{ padding: '6px 12px', background: showMACD ? 'rgba(161, 84, 255, 0.1)' : 'none', border: '1px solid var(--border-glass)', borderRadius: '6px', cursor: 'pointer', display: 'flex', alignItems: 'center', gap: '6px', color: showMACD ? 'var(--neon-violet)' : 'var(--text-secondary)', fontSize: '12px', transition: 'all 0.2s ease', outline: 'none' }}
|
| 782 |
+
>
|
| 783 |
+
{showMACD ? <Eye size={13} /> : <EyeOff size={13} />}
|
| 784 |
+
MACD
|
| 785 |
+
</button>
|
| 786 |
+
<button
|
| 787 |
+
onClick={() => setShowBB(!showBB)}
|
| 788 |
+
className={`control-toggle-btn indicator-bb ${showBB ? 'active' : ''}`}
|
| 789 |
+
title="Bollinger Bands (20, 2)"
|
| 790 |
+
style={{ padding: '6px 12px', background: showBB ? 'rgba(245, 158, 11, 0.1)' : 'none', border: '1px solid var(--border-glass)', borderRadius: '6px', cursor: 'pointer', display: 'flex', alignItems: 'center', gap: '6px', color: showBB ? '#f59e0b' : 'var(--text-secondary)', fontSize: '12px', transition: 'all 0.2s ease', outline: 'none' }}
|
| 791 |
+
>
|
| 792 |
+
{showBB ? <Eye size={13} /> : <EyeOff size={13} />}
|
| 793 |
+
Bollinger
|
| 794 |
+
</button>
|
| 795 |
</div>
|
| 796 |
</div>
|
| 797 |
|
|
|
|
| 898 |
padding: isMaximized ? '16px 24px 24px' : '16px 16px 32px',
|
| 899 |
flex: 'unset',
|
| 900 |
flexShrink: 0,
|
| 901 |
+
height: isMaximized ? `${650 + subPaneCount * 200}px` : `${340 + subPaneCount * 110}px`
|
| 902 |
}}>
|
| 903 |
{/* Floating Add Marker Form */}
|
| 904 |
{showAddMarkerForm && (
|
|
|
|
| 1013 |
onMouseUp={handleMouseUp}
|
| 1014 |
onMouseLeave={handleMouseLeave}
|
| 1015 |
style={{
|
| 1016 |
+
height: mainChartHeight,
|
|
|
|
|
|
|
| 1017 |
width: '100%',
|
| 1018 |
position: 'relative',
|
| 1019 |
cursor: isZoomed ? (isDragging.current ? 'grabbing' : 'grab') : 'crosshair',
|
|
|
|
| 1112 |
name="EMA 20"
|
| 1113 |
/>
|
| 1114 |
)}
|
| 1115 |
+
|
| 1116 |
+
{/* Bollinger Bands Overlay (backend-computed via pandas-ta, aligned by ts) */}
|
| 1117 |
+
{showBB && (
|
| 1118 |
+
<>
|
| 1119 |
+
<Line
|
| 1120 |
+
type="monotone"
|
| 1121 |
+
dataKey="bb_upper"
|
| 1122 |
+
stroke="#a154ff"
|
| 1123 |
+
strokeWidth={1.2}
|
| 1124 |
+
strokeDasharray="3 3"
|
| 1125 |
+
dot={false}
|
| 1126 |
+
name="BB Upper"
|
| 1127 |
+
/>
|
| 1128 |
+
<Line
|
| 1129 |
+
type="monotone"
|
| 1130 |
+
dataKey="bb_middle"
|
| 1131 |
+
stroke="#f59e0b"
|
| 1132 |
+
strokeWidth={1.2}
|
| 1133 |
+
dot={false}
|
| 1134 |
+
name="BB Middle"
|
| 1135 |
+
/>
|
| 1136 |
+
<Line
|
| 1137 |
+
type="monotone"
|
| 1138 |
+
dataKey="bb_lower"
|
| 1139 |
+
stroke="#a154ff"
|
| 1140 |
+
strokeWidth={1.2}
|
| 1141 |
+
strokeDasharray="3 3"
|
| 1142 |
+
dot={false}
|
| 1143 |
+
name="BB Lower"
|
| 1144 |
+
/>
|
| 1145 |
+
</>
|
| 1146 |
+
)}
|
| 1147 |
</ComposedChart>
|
| 1148 |
</ResponsiveContainer>
|
| 1149 |
</div>
|
|
|
|
| 1181 |
|
| 1182 |
{/* Technical Indicator panel: RSI 14 (Auxiliary Chart below main price chart) */}
|
| 1183 |
{showRSI && visibleRsiData.length > 0 && (
|
| 1184 |
+
<div style={{ height: subPaneHeight, width: '100%', borderTop: '1px dashed var(--border-glass)', paddingTop: '10px' }}>
|
| 1185 |
<div style={{ display: 'flex', justifyContent: 'space-between', fontSize: '11px', color: 'var(--text-secondary)', marginBottom: '4px', paddingLeft: '10px' }}>
|
| 1186 |
<span style={{ fontWeight: 700, color: 'var(--neon-cyan)' }}>RSI (14)</span>
|
| 1187 |
<span style={{ color: 'var(--text-muted)' }}>Overbought >70 | Oversold <30</span>
|
|
|
|
| 1217 |
</ResponsiveContainer>
|
| 1218 |
</div>
|
| 1219 |
)}
|
| 1220 |
+
|
| 1221 |
+
{/* Technical Indicator panel: MACD (12, 26, 9) — separate pane below the price chart */}
|
| 1222 |
+
{showMACD && visibleMacdData.length > 0 && (
|
| 1223 |
+
<div className="chart-indicator-pane" style={{ height: subPaneHeight, width: '100%', borderTop: '1px dashed var(--border-glass)', paddingTop: '10px' }}>
|
| 1224 |
+
<div style={{ display: 'flex', justifyContent: 'space-between', fontSize: '11px', color: 'var(--text-secondary)', marginBottom: '4px', paddingLeft: '10px' }}>
|
| 1225 |
+
<span style={{ fontWeight: 700, color: 'var(--neon-violet)' }}>MACD (12, 26, 9)</span>
|
| 1226 |
+
<span style={{ color: 'var(--text-muted)' }}>
|
| 1227 |
+
{indicatorLoading ? 'Loading…' : 'Line · Signal · Histogram'}
|
| 1228 |
+
</span>
|
| 1229 |
+
</div>
|
| 1230 |
+
<ResponsiveContainer width="100%" height="100%">
|
| 1231 |
+
<ComposedChart data={visibleMacdData} margin={{ top: 5, right: 5, left: 20, bottom: 5 }}>
|
| 1232 |
+
<XAxis dataKey="time" hide />
|
| 1233 |
+
<YAxis stroke="#475569" fontSize={9} tickLine={false} />
|
| 1234 |
+
<Tooltip
|
| 1235 |
+
contentStyle={{
|
| 1236 |
+
background: '#0d101b',
|
| 1237 |
+
borderColor: '#2e303a',
|
| 1238 |
+
borderRadius: '8px',
|
| 1239 |
+
color: '#fff',
|
| 1240 |
+
fontSize: '11px'
|
| 1241 |
+
}}
|
| 1242 |
+
/>
|
| 1243 |
+
|
| 1244 |
+
{/* Zero baseline */}
|
| 1245 |
+
<ReferenceLine y={0} stroke="#475569" strokeWidth={1} />
|
| 1246 |
+
|
| 1247 |
+
{/* Histogram (green above / red below the zero line) */}
|
| 1248 |
+
<Bar dataKey="macd_hist" name="MACD Histogram" maxBarSize={8} isAnimationActive={false}>
|
| 1249 |
+
{visibleMacdData.map((entry, idx) => (
|
| 1250 |
+
<Cell key={`hist-${idx}`} fill={(entry.macd_hist ?? 0) >= 0 ? 'rgba(16, 185, 129, 0.45)' : 'rgba(239, 68, 68, 0.45)'} />
|
| 1251 |
+
))}
|
| 1252 |
+
</Bar>
|
| 1253 |
+
|
| 1254 |
+
<Line
|
| 1255 |
+
type="monotone"
|
| 1256 |
+
dataKey="macd"
|
| 1257 |
+
stroke="var(--neon-cyan)"
|
| 1258 |
+
strokeWidth={1.5}
|
| 1259 |
+
dot={false}
|
| 1260 |
+
name="MACD"
|
| 1261 |
+
/>
|
| 1262 |
+
<Line
|
| 1263 |
+
type="monotone"
|
| 1264 |
+
dataKey="macd_signal"
|
| 1265 |
+
stroke="#fb923c"
|
| 1266 |
+
strokeWidth={1.5}
|
| 1267 |
+
dot={false}
|
| 1268 |
+
name="Signal"
|
| 1269 |
+
/>
|
| 1270 |
+
</ComposedChart>
|
| 1271 |
+
</ResponsiveContainer>
|
| 1272 |
+
</div>
|
| 1273 |
+
)}
|
| 1274 |
</div> {/* closes chart-container */}
|
| 1275 |
</div> {/* closes Left Column */}
|
| 1276 |
|
|
|
|
| 1279 |
<ChartChatbot
|
| 1280 |
ticker={activeTicker}
|
| 1281 |
markers={markers}
|
| 1282 |
+
activeIndicators={{ sma: showSMA, ema: showEMA, rsi: showRSI, macd: showMACD, bb: showBB }}
|
| 1283 |
user={user}
|
| 1284 |
onOpenRecharge={onOpenRecharge}
|
| 1285 |
liveData={chatbotLiveData}
|