Files
signal-platform/frontend/src/pages/TickerDetailPage.tsx
T
dennisthiessen 0e9f1846f6
Deploy / lint (push) Successful in 6s
Deploy / test (push) Successful in 34s
Deploy / deploy (push) Successful in 23s
fix watchlist remove (was undone by auto-populate); add watch toggle on ticker page
Removing a ticker did nothing because get_watchlist re-runs auto_populate on
every read, instantly re-adding any top-ranked ticker the user had just removed.
Removals are now tombstoned as a "dismissed" entry_type: auto-population skips
them, the list hides them, and a later manual add revives the row. Also exposes
an Add/Remove-watchlist toggle in the ticker detail header.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-06-14 14:17:27 +02:00

399 lines
16 KiB
TypeScript

import { useMemo, useEffect, useState } from 'react';
import { useParams } from 'react-router-dom';
import { useTickerDetail } from '../hooks/useTickerDetail';
import { useFetchSymbolData } from '../hooks/useFetchSymbolData';
import { useWatchlist, useAddToWatchlist, useRemoveFromWatchlist } from '../hooks/useWatchlist';
import type { FetchSelector } from '../api/ingestion';
import { CandlestickChart } from '../components/charts/CandlestickChart';
import { ScoreCard } from '../components/ui/ScoreCard';
import { SkeletonCard } from '../components/ui/Skeleton';
import { SentimentPanel } from '../components/ticker/SentimentPanel';
import { FundamentalsPanel } from '../components/ticker/FundamentalsPanel';
import { IndicatorSelector } from '../components/ticker/IndicatorSelector';
import { RecommendationPanel } from '../components/ticker/RecommendationPanel';
import { Button } from '../components/ui/Button';
import { Callout } from '../components/ui/Callout';
import { Section } from '../components/ui/Section';
import { Tabs } from '../components/ui/Tabs';
import { formatPrice } from '../lib/format';
import type { TradeSetup } from '../lib/types';
const detailTabs = ['Analysis', 'Indicators', 'S/R Levels'] as const;
type DetailTab = (typeof detailTabs)[number];
function SectionError({ message, onRetry }: { message: string; onRetry?: () => void }) {
return (
<Callout variant="error" onRetry={onRetry}>
{message}
</Callout>
);
}
function timeAgo(iso: string): string {
const diff = Date.now() - new Date(iso).getTime();
const mins = Math.floor(diff / 60_000);
if (mins < 1) return 'just now';
if (mins < 60) return `${mins}m ago`;
const hrs = Math.floor(mins / 60);
if (hrs < 24) return `${hrs}h ago`;
const days = Math.floor(hrs / 24);
return `${days}d ago`;
}
interface DataStatusItem {
label: string;
available: boolean;
timestamp?: string | null;
selector: FetchSelector; // what a refresh of this row fetches
paid?: boolean; // provider call that may cost money/quota
}
function RefreshIcon({ spinning }: { spinning: boolean }) {
return (
<svg className={`h-3.5 w-3.5 ${spinning ? 'animate-spin' : ''}`} viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth={2}>
<path strokeLinecap="round" strokeLinejoin="round" d="M4 4v5h5M20 20v-5h-5M4 9a8 8 0 0114-3M20 15a8 8 0 01-14 3" />
</svg>
);
}
function DataFreshnessBar({
items,
onRefresh,
pendingLabel,
busy,
}: {
items: DataStatusItem[];
onRefresh: (item: DataStatusItem) => void;
pendingLabel: string | null;
busy: boolean;
}) {
return (
<div className="glass-sm p-3 flex flex-wrap gap-x-5 gap-y-2">
{items.map((item) => (
<div key={item.label} className="flex items-center gap-1.5">
<span className={`inline-block h-2 w-2 rounded-full shrink-0 ${
item.available ? 'bg-emerald-400 shadow-lg shadow-emerald-400/40' : 'bg-gray-600'
}`} />
<span className="text-xs text-gray-400">{item.label}</span>
{item.available && item.timestamp ? (
<span className="text-[10px] text-gray-500">{timeAgo(item.timestamp)}</span>
) : !item.available ? (
<span className="text-[10px] text-gray-600">no data</span>
) : null}
<button
onClick={() => onRefresh(item)}
disabled={busy}
title={item.paid ? `Fetch ${item.label} (uses provider quota)` : `Recompute ${item.label}`}
className="ml-0.5 text-gray-500 hover:text-blue-300 disabled:opacity-40 transition-colors"
>
<RefreshIcon spinning={pendingLabel === item.label} />
</button>
{item.paid && <span className="text-[9px] text-amber-500/70" title="Uses a paid/quota provider call">$</span>}
</div>
))}
</div>
);
}
export default function TickerDetailPage() {
const { symbol = '' } = useParams<{ symbol: string }>();
const { ohlcv, scores, srLevels, sentiment, fundamentals, trades } = useTickerDetail(symbol);
const ingestion = useFetchSymbolData();
const watchlist = useWatchlist();
const addToWatchlist = useAddToWatchlist();
const removeFromWatchlist = useRemoveFromWatchlist();
const onWatchlist = useMemo(
() => (watchlist.data ?? []).some((e) => e.symbol.toUpperCase() === symbol.toUpperCase()),
[watchlist.data, symbol],
);
const watchlistBusy = addToWatchlist.isPending || removeFromWatchlist.isPending;
const [activeTab, setActiveTab] = useState<DetailTab>('Analysis');
const [refreshingLabel, setRefreshingLabel] = useState<string | null>(null);
const dataStatus: DataStatusItem[] = useMemo(() => [
{
label: 'OHLCV',
available: !!ohlcv.data && ohlcv.data.length > 0,
timestamp: ohlcv.data?.[ohlcv.data.length - 1]?.created_at,
selector: ['ohlcv'] as FetchSelector,
paid: true,
},
{
label: 'Sentiment',
available: !!sentiment.data && sentiment.data.count > 0,
timestamp: sentiment.data?.scores?.[0]?.timestamp,
selector: ['sentiment'] as FetchSelector,
paid: true,
},
{
label: 'Fundamentals',
available: !!fundamentals.data && fundamentals.data.fetched_at !== null,
timestamp: fundamentals.data?.fetched_at,
selector: ['fundamentals'] as FetchSelector,
paid: true,
},
{
label: 'S/R Levels',
available: !!srLevels.data && srLevels.data.count > 0,
timestamp: srLevels.data?.levels?.[0]?.created_at,
selector: 'recompute' as FetchSelector,
},
{
label: 'Scores',
available: !!scores.data && scores.data.composite_score !== null,
timestamp: scores.data?.computed_at,
selector: 'recompute' as FetchSelector,
},
], [ohlcv.data, sentiment.data, fundamentals.data, srLevels.data, scores.data]);
const handleRefresh = (item: DataStatusItem) => {
setRefreshingLabel(item.label);
ingestion.mutate(
{ symbol, sources: item.selector },
{ onSettled: () => setRefreshingLabel(null) },
);
};
// Log trades API errors but don't disrupt the page
useEffect(() => {
if (trades.error) {
console.error('Failed to fetch trade setups:', trades.error);
}
}, [trades.error]);
const setupsForSymbol: TradeSetup[] = useMemo(() => {
if (trades.error || !trades.data) return [];
return trades.data.filter((t) => t.symbol.toUpperCase() === symbol.toUpperCase());
}, [trades.data, trades.error, symbol]);
const longSetup = useMemo(
() => setupsForSymbol?.find((s) => s.direction === 'long'),
[setupsForSymbol],
);
const shortSetup = useMemo(
() => setupsForSymbol?.find((s) => s.direction === 'short'),
[setupsForSymbol],
);
// Current price = latest close, with day-over-day change
const priceInfo = useMemo(() => {
const bars = ohlcv.data;
if (!bars || bars.length === 0) return null;
const last = bars[bars.length - 1];
const prev = bars.length > 1 ? bars[bars.length - 2] : null;
const change = prev && prev.close ? ((last.close - prev.close) / prev.close) * 100 : null;
return { price: last.close, date: last.date, change };
}, [ohlcv.data]);
// Which setup the chart overlays. 'auto' = the ticker's preferred direction.
const [overlayChoice, setOverlayChoice] = useState<'auto' | 'long' | 'short' | 'none'>('auto');
const action = (longSetup ?? shortSetup)?.recommended_action ?? null;
const overlaySetup: TradeSetup | undefined = useMemo(() => {
if (overlayChoice === 'none') return undefined;
if (overlayChoice === 'long') return longSetup;
if (overlayChoice === 'short') return shortSetup;
// auto: preferred direction's setup, else the highest-confidence available
if (action?.startsWith('LONG') && longSetup) return longSetup;
if (action?.startsWith('SHORT') && shortSetup) return shortSetup;
const candidates = [longSetup, shortSetup].filter(Boolean) as TradeSetup[];
return candidates.sort((a, b) => (b.confidence_score ?? 0) - (a.confidence_score ?? 0))[0];
}, [overlayChoice, longSetup, shortSetup, action]);
// Sort visible S/R levels by strength for the table (only levels within chart zones)
const sortedLevels = useMemo(() => {
if (!srLevels.data?.visible_levels) return [];
return [...srLevels.data.visible_levels].sort((a, b) => b.strength - a.strength);
}, [srLevels.data]);
return (
<div className="space-y-6 animate-slide-up">
{/* Header */}
<div className="flex flex-wrap items-center justify-between gap-4">
<div className="flex items-baseline gap-4">
<h1 className="text-3xl font-semibold text-gray-100">{symbol.toUpperCase()}</h1>
{priceInfo && (
<div className="flex items-baseline gap-2">
<span className="num text-2xl font-semibold text-gray-100">{formatPrice(priceInfo.price)}</span>
{priceInfo.change !== null && (
<span className={`num text-sm font-medium ${priceInfo.change >= 0 ? 'text-emerald-400' : 'text-red-400'}`}>
{priceInfo.change >= 0 ? '+' : ''}{priceInfo.change.toFixed(2)}%
</span>
)}
<span className="text-xs text-gray-500">last close · {timeAgo(priceInfo.date)}</span>
</div>
)}
</div>
<div className="flex items-center gap-2">
<Button
variant="ghost"
onClick={() =>
onWatchlist
? removeFromWatchlist.mutate(symbol)
: addToWatchlist.mutate(symbol)
}
loading={watchlistBusy}
disabled={watchlist.isLoading}
title={onWatchlist ? 'Remove from watchlist' : 'Add to watchlist'}
className={onWatchlist ? '!text-amber-300' : ''}
>
{onWatchlist ? '★ Watching' : '☆ Add to watchlist'}
</Button>
<Button
onClick={() => { setRefreshingLabel(null); ingestion.mutate(symbol); }}
loading={ingestion.isPending}
>
{ingestion.isPending ? 'Fetching…' : 'Fetch All'}
</Button>
</div>
</div>
{/* Data freshness bar */}
<DataFreshnessBar
items={dataStatus}
onRefresh={handleRefresh}
pendingLabel={refreshingLabel}
busy={ingestion.isPending}
/>
<RecommendationPanel
symbol={symbol}
longSetup={longSetup}
shortSetup={shortSetup}
currentPrice={priceInfo?.price}
/>
{/* Chart — always visible */}
<Section title="Price Chart">
{ohlcv.isLoading && <SkeletonCard className="h-[400px]" />}
{ohlcv.isError && (
<SectionError
message={ohlcv.error instanceof Error ? ohlcv.error.message : 'Failed to load OHLCV data'}
onRetry={() => ohlcv.refetch()}
/>
)}
{ohlcv.data && (
<div className="glass p-5 space-y-3">
{(longSetup || shortSetup) && (
<div className="flex flex-wrap items-center gap-2 text-xs">
<span className="text-gray-500">Overlay setup:</span>
{([
{ key: 'auto', label: 'Auto', show: true },
{ key: 'long', label: 'Long', show: !!longSetup },
{ key: 'short', label: 'Short', show: !!shortSetup },
{ key: 'none', label: 'None', show: true },
] as const).filter((o) => o.show).map((o) => (
<button
key={o.key}
onClick={() => setOverlayChoice(o.key)}
className={`rounded-md px-2.5 py-1 transition-colors ${
overlayChoice === o.key
? 'bg-blue-400/15 text-blue-200 border border-blue-400/30'
: 'text-gray-400 border border-white/[0.08] hover:text-gray-200 hover:bg-white/[0.04]'
}`}
>
{o.label}
</button>
))}
{overlaySetup && (
<span className="num ml-1 text-gray-500">
showing {overlaySetup.direction.toUpperCase()} · entry {formatPrice(overlaySetup.entry_price)} target {formatPrice(overlaySetup.target)}
</span>
)}
</div>
)}
<CandlestickChart
data={ohlcv.data}
srLevels={srLevels.data?.levels}
zones={srLevels.data?.zones}
tradeSetup={overlaySetup}
currentPrice={priceInfo?.price}
/>
<p className="text-[11px] text-gray-500">
Only the nearest support &amp; resistance are drawn. Full list in the S/R Levels tab.
{srLevels.isError && ' S/R levels unavailable.'}
</p>
</div>
)}
</Section>
{/* Detail tabs */}
<Tabs tabs={detailTabs} active={activeTab} onChange={setActiveTab} />
{activeTab === 'Analysis' && (
<div className="grid gap-6 lg:grid-cols-3 animate-fade-in">
<Section title="Scores">
{scores.isLoading && <SkeletonCard />}
{scores.isError && (
<SectionError message={scores.error instanceof Error ? scores.error.message : 'Failed to load scores'} onRetry={() => scores.refetch()} />
)}
{scores.data && (
<ScoreCard compositeScore={scores.data.composite_score} dimensions={scores.data.dimensions} compositeBreakdown={scores.data.composite_breakdown} />
)}
</Section>
<Section title="Sentiment">
{sentiment.isLoading && <SkeletonCard />}
{sentiment.isError && (
<SectionError message={sentiment.error instanceof Error ? sentiment.error.message : 'Failed to load sentiment'} onRetry={() => sentiment.refetch()} />
)}
{sentiment.data && <SentimentPanel data={sentiment.data} />}
</Section>
<Section title="Fundamentals">
{fundamentals.isLoading && <SkeletonCard />}
{fundamentals.isError && (
<SectionError message={fundamentals.error instanceof Error ? fundamentals.error.message : 'Failed to load fundamentals'} onRetry={() => fundamentals.refetch()} />
)}
{fundamentals.data && <FundamentalsPanel data={fundamentals.data} />}
</Section>
</div>
)}
{activeTab === 'Indicators' && (
<div className="animate-fade-in">
<Section title="Technical Indicators">
<IndicatorSelector symbol={symbol} />
</Section>
</div>
)}
{activeTab === 'S/R Levels' && (
<div className="animate-fade-in">
<Section title="Support & Resistance Levels" hint="sorted by strength">
{sortedLevels.length === 0 ? (
<Callout variant="empty">No S/R levels detected for this ticker yet.</Callout>
) : (
<div className="glass overflow-x-auto">
<table className="w-full text-sm">
<thead>
<tr className="border-b border-white/[0.06] text-left text-xs uppercase tracking-wider text-gray-500">
<th className="px-4 py-3">Type</th>
<th className="px-4 py-3">Price Level</th>
<th className="px-4 py-3">Strength</th>
<th className="px-4 py-3">Method</th>
</tr>
</thead>
<tbody>
{sortedLevels.map((level) => (
<tr key={level.id} className="border-b border-white/[0.04] transition-colors duration-150 hover:bg-white/[0.03]">
<td className="px-4 py-3">
<span className={level.type === 'support' ? 'text-emerald-400' : 'text-red-400'}>{level.type}</span>
</td>
<td className="px-4 py-3 text-gray-200 font-mono">{formatPrice(level.price_level)}</td>
<td className="px-4 py-3 text-gray-200">{level.strength}</td>
<td className="px-4 py-3 text-gray-400">{level.detection_method}</td>
</tr>
))}
</tbody>
</table>
</div>
)}
</Section>
</div>
)}
</div>
);
}