refactor: migrate TrumpSignal to TypeScript monorepo and Pages Router

This commit is contained in:
2026-11-03 20:42:30 +08:00
parent de1a903462
commit 1791dbb557
188 changed files with 52461 additions and 2 deletions
@@ -0,0 +1,522 @@
'use client'
import { useEffect, useRef, useState } from 'react'
import type { TrumpPost, Candle } from '@/types'
import { useDashboardStore } from '@/store/dashboard'
interface ChartPanelProps {
posts?: TrumpPost[]
candles?: Candle[]
externalSelectedId?: number | null
onSelectPost?: (id: number | null) => void
onSelectDayPosts?: (posts: TrumpPost[]) => void
}
export default function ChartPanel({
posts = [],
candles = [],
externalSelectedId,
onSelectPost,
onSelectDayPosts,
}: ChartPanelProps) {
const { timeframe, asset, livePrices } = useDashboardStore()
const containerRef = useRef<HTMLDivElement>(null)
const chartRef = useRef<unknown>(null)
const seriesRef = useRef<unknown>(null)
const macroPriceLineRef = useRef<unknown>(null)
const macroVerticalRef = useRef<HTMLDivElement | null>(null)
const macroLabelRef = useRef<HTMLDivElement | null>(null)
// Macro overlay state. The vertical line + label are absolutely-positioned
// DOM nodes (lightweight-charts has no first-class "vertical marker"
// primitive), so we have to manually re-project signal time → pixel X
// every time the visible range / chart width changes. Without this the
// line stays anchored to the SCREEN while the candles pan beneath it,
// which looks exactly like a draggable / floating line.
const macroBucketTimeRef = useRef<number | null>(null)
const macroLabelTextRef = useRef<string>('')
// Imperative reposition fn — set up by the chart-creation effect, called
// from BOTH the data effect (when the signal changes) AND from a
// subscribeVisibleTimeRangeChange callback (when the user pans / zooms).
const repositionMacroRef = useRef<(() => void) | null>(null)
const fittedRef = useRef(false)
// Chart creation is async (dynamic import). If the candles fetch wins the
// race (common — SWR serves them instantly from cache), the data effect
// runs while seriesRef is still null and bails; nothing re-triggers it
// afterwards, so the chart stays EMPTY and the 2s live-tick effect then
// paints a single lone candle via series.update(). This state flips when
// the chart actually exists so the data effect re-runs.
const [chartReady, setChartReady] = useState(false)
// The live-tick effect must never run before setData() — updating an empty
// series creates a one-candle chart.
const dataLoadedRef = useRef(false)
const postsRef = useRef(posts)
postsRef.current = posts
const selectedPostIdRef = useRef(externalSelectedId)
selectedPostIdRef.current = externalSelectedId
const timeframeRef = useRef(timeframe)
timeframeRef.current = timeframe
const onSelectRef = useRef(onSelectPost)
onSelectRef.current = onSelectPost
const onSelectDayPostsRef = useRef(onSelectDayPosts)
onSelectDayPostsRef.current = onSelectDayPosts
// Detect current theme for chart colors
function getChartColors() {
const isDark = document.documentElement.dataset.theme === 'dark'
return {
background: isDark ? '#121212' : '#ffffff',
textColor: isDark ? '#666666' : '#888888',
gridColor: isDark ? '#1e1e1e' : '#f0ede8',
borderColor: isDark ? '#2a2a2a' : '#e8e4de',
macroAccent: isDark ? '#f59e0b' : '#b45309',
macroAccentSoft: isDark ? 'rgba(245,158,11,0.24)' : 'rgba(180,83,9,0.18)',
}
}
// Create chart once on mount
useEffect(() => {
if (!containerRef.current || typeof window === 'undefined') return
let destroyed = false
let ro: ResizeObserver | null = null
let themeObserver: MutationObserver | null = null
import('lightweight-charts').then(({ createChart, CrosshairMode }) => {
if (destroyed || !containerRef.current) return
const colors = getChartColors()
const vertical = document.createElement('div')
vertical.style.position = 'absolute'
vertical.style.top = '0'
vertical.style.bottom = '0'
vertical.style.width = '0'
vertical.style.borderLeft = `2px dashed ${colors.macroAccent}`
vertical.style.opacity = '0'
vertical.style.pointerEvents = 'none'
vertical.style.zIndex = '2'
// NO transition on `left` — the reposition callback fires on every
// pan/zoom frame; a 160ms ease there makes the line lag visibly
// behind the candles and looks exactly like the original bug.
vertical.style.transition = 'opacity 120ms ease'
containerRef.current.appendChild(vertical)
macroVerticalRef.current = vertical
const label = document.createElement('div')
label.style.position = 'absolute'
label.style.top = '14px'
label.style.left = '0'
label.style.padding = '5px 8px'
label.style.borderRadius = '999px'
label.style.border = `1px solid ${colors.macroAccentSoft}`
label.style.background = colors.background
label.style.boxShadow = '0 6px 24px rgba(15, 23, 42, 0.08)'
label.style.color = colors.macroAccent
label.style.fontSize = '11px'
label.style.fontWeight = '700'
label.style.letterSpacing = '0.04em'
label.style.textTransform = 'uppercase'
label.style.whiteSpace = 'nowrap'
label.style.pointerEvents = 'none'
label.style.opacity = '0'
label.style.transform = 'translateX(-50%)'
label.style.zIndex = '3'
// Same reasoning as the vertical line: no transition on `left` —
// panning must keep the label glued to its timestamp without lag.
label.style.transition = 'opacity 120ms ease'
containerRef.current.appendChild(label)
macroLabelRef.current = label
const chart = createChart(containerRef.current, {
width: containerRef.current.clientWidth,
// Follow the container, don't hardcode: .chart-wrap is 360px on
// desktop but 300/240px behind !important media queries. A fixed
// 360 overflows those and overflow:hidden cuts off the bottom of
// the chart — lowest candles, markers, and the whole time axis.
height: containerRef.current.clientHeight || 360,
layout: {
background: { color: colors.background },
textColor: colors.textColor,
},
grid: {
vertLines: { color: colors.gridColor },
horzLines: { color: colors.gridColor },
},
crosshair: { mode: CrosshairMode.Normal },
rightPriceScale: { borderColor: colors.borderColor },
timeScale: {
borderColor: colors.borderColor,
timeVisible: true,
rightOffset: 5,
barSpacing: 10,
},
handleScroll: true,
handleScale: true,
})
chartRef.current = chart
const series = chart.addCandlestickSeries({
upColor: '#26a69a',
downColor: '#ef5350',
borderUpColor: '#26a69a',
borderDownColor: '#ef5350',
wickUpColor: '#26a69a',
wickDownColor: '#ef5350',
})
seriesRef.current = series
// Breathing room above/below the candles. Markers render ~10px outside
// the bar's high/low; with the default tight bottom margin a crash
// candle at the bottom of the autoscaled range gets its marker dots
// clipped by the pane edge.
series.priceScale().applyOptions({
scaleMargins: { top: 0.12, bottom: 0.16 },
})
setChartReady(true)
// Re-project macro signal time → pixel X on every visible-range
// change (pan / zoom / data update / resize). Without this the line
// is set ONCE in the data effect and then stays stuck at a fixed
// pixel column while the user scrolls the chart — the bug the user
// reported as "this line is draggable".
const reposition = () => {
const c = chartRef.current as any
const vert = macroVerticalRef.current
const lbl = macroLabelRef.current
const container = containerRef.current
if (!c || !vert || !container) return
const bucket = macroBucketTimeRef.current
if (bucket == null) {
vert.style.opacity = '0'
if (lbl) lbl.style.opacity = '0'
return
}
const x = c.timeScale?.().timeToCoordinate?.(bucket)
const w = container.clientWidth
// Hide (don't clamp) when the signal time is OUTSIDE the visible
// range. Clamping to the edge would put the "MACRO BOTTOM" label
// on candles that have nothing to do with the signal — actively
// misleading.
if (typeof x !== 'number' || !Number.isFinite(x) || x < 0 || x > w) {
vert.style.opacity = '0'
if (lbl) lbl.style.opacity = '0'
return
}
vert.style.left = `${x}px`
vert.style.opacity = '1'
if (lbl) {
lbl.textContent = macroLabelTextRef.current
const clamped = Math.max(76, Math.min(w - 76, x))
lbl.style.left = `${clamped}px`
lbl.style.opacity = '1'
}
}
repositionMacroRef.current = reposition
// lightweight-charts fires this on user pan, wheel zoom, programmatic
// setVisibleRange, and on each new candle. We piggy-back on it for
// every reposition trigger we care about.
chart.timeScale().subscribeVisibleTimeRangeChange(reposition)
chart.subscribeClick((param: any) => {
if (!param.time) return
const clickTime = typeof param.time === 'number' ? param.time : 0
if (!clickTime) return
const bucketByTf: Record<string, number> = {
'5m': 300,
'15m': 900,
'1h': 3600,
'4h': 14400,
'1d': 86400,
'1w': 604800,
}
const bucketSecs = bucketByTf[timeframeRef.current.toLowerCase()] ?? 3600
const clickBucket = Math.floor(clickTime / bucketSecs) * bucketSecs
const inBucket = postsRef.current.filter((p) => {
if (!p.published_at) return false
const pt = Math.floor(new Date(p.published_at).getTime() / 1000)
return Math.floor(pt / bucketSecs) * bucketSecs === clickBucket
})
if (inBucket.length === 0) {
onSelectRef.current?.(null)
return
}
// Multiple posts in this candle bucket → show all of them in the right rail
if (inBucket.length > 1 && onSelectDayPostsRef.current) {
const sorted = [...inBucket].sort(
(a, b) => new Date(b.published_at).getTime() - new Date(a.published_at).getTime(),
)
onSelectDayPostsRef.current(sorted)
return
}
// Single post → show detail directly
onSelectRef.current?.(inBucket[0].id)
})
ro = new ResizeObserver(() => {
if (containerRef.current && !destroyed) {
chart.applyOptions({
width: containerRef.current.clientWidth,
height: containerRef.current.clientHeight || 360,
})
// Width change → new pixel coordinates → re-project the macro
// marker too, otherwise it'd drift relative to the candles on
// window resize / sidebar toggle.
repositionMacroRef.current?.()
}
})
ro.observe(containerRef.current)
themeObserver = new MutationObserver(() => {
const colors = getChartColors()
chart.applyOptions({
layout: {
background: { color: colors.background },
textColor: colors.textColor,
},
grid: {
vertLines: { color: colors.gridColor },
horzLines: { color: colors.gridColor },
},
rightPriceScale: { borderColor: colors.borderColor },
timeScale: { borderColor: colors.borderColor },
})
if (macroVerticalRef.current) {
macroVerticalRef.current.style.borderLeft = `2px dashed ${colors.macroAccent}`
}
if (macroLabelRef.current) {
macroLabelRef.current.style.color = colors.macroAccent
macroLabelRef.current.style.borderColor = colors.macroAccentSoft
macroLabelRef.current.style.background = colors.background
}
})
themeObserver.observe(document.documentElement, {
attributes: true,
attributeFilter: ['data-theme'],
})
})
return () => {
destroyed = true
ro?.disconnect()
themeObserver?.disconnect()
fittedRef.current = false
dataLoadedRef.current = false
setChartReady(false)
if (chartRef.current) {
// @ts-expect-error lightweight-charts type
chartRef.current.remove()
chartRef.current = null
seriesRef.current = null
}
if (macroVerticalRef.current?.parentNode) {
macroVerticalRef.current.parentNode.removeChild(macroVerticalRef.current)
}
if (macroLabelRef.current?.parentNode) {
macroLabelRef.current.parentNode.removeChild(macroLabelRef.current)
}
macroVerticalRef.current = null
macroLabelRef.current = null
macroPriceLineRef.current = null
}
}, [])
// Update candles + markers
useEffect(() => {
const series = seriesRef.current
const chart = chartRef.current
if (!series || !chart || candles.length === 0) {
dataLoadedRef.current = false
return
}
const sorted = [...candles].sort((a, b) => a.time - b.time)
// @ts-expect-error lightweight-charts type
series.setData(
sorted.map((c) => ({
time: c.time as number,
open: c.open,
high: c.high,
low: c.low,
close: c.close,
})),
)
dataLoadedRef.current = true
const minTime = sorted[0].time
const maxTime = sorted[sorted.length - 1].time
const visible = posts.filter((p) => {
if (!p.published_at) return false
const t = Math.floor(new Date(p.published_at).getTime() / 1000)
return t >= minTime && t <= maxTime
})
// Markers show actionable signals only. Hold/filtered posts vastly
// outnumber signals and their gray dots pile into unreadable clusters;
// they stay browsable in the Recent-signals list instead.
const markerPosts = visible.filter(
(p) => p.signal === 'buy' || p.signal === 'short' || p.signal === 'sell',
)
const bucketByTf: Record<string, number> = {
'5m': 300,
'15m': 900,
'1h': 3600,
'4h': 14400,
'1d': 86400,
'1w': 604800,
}
const candleSpacing = sorted.length > 1 ? sorted[1].time - sorted[0].time : 300
const bucketSecs = bucketByTf[timeframeRef.current.toLowerCase()] ?? candleSpacing
const bucketMap = new Map<number, typeof visible>()
for (const p of markerPosts) {
const pt = Math.floor(new Date(p.published_at).getTime() / 1000)
const bucket = Math.floor(pt / bucketSecs) * bucketSecs
if (!bucketMap.has(bucket)) bucketMap.set(bucket, [])
bucketMap.get(bucket)!.push(p)
}
bucketMap.forEach((ps) => ps.sort((a, b) => (b.ai_confidence ?? 0) - (a.ai_confidence ?? 0)))
const markers = Array.from(bucketMap.entries())
.sort(([a], [b]) => a - b)
.map(([bucketTime, bPosts]) => {
const isSelected = bPosts.some((p) => p.id === externalSelectedId)
const best = bPosts[0]
const count = bPosts.length
const signalColor = isSelected
? '#f59e0b'
: best.signal === 'short' || best.signal === 'sell'
? '#ef5350'
: best.signal === 'buy'
? '#26a69a'
: '#aaaaaa'
return {
time: bucketTime as number,
position: 'aboveBar' as const,
color: signalColor,
shape: 'circle' as const,
text: count > 1 ? String(count) : '',
size: isSelected ? 2 : count > 1 ? 1.5 : 1,
}
})
// @ts-expect-error lightweight-charts type
series.setMarkers(markers)
// Highlight the most recent visible Macro Vibes reversal signal on BTC.
const visibleMacro =
asset === 'BTC'
? visible
.filter(
(p) =>
((p.source || '') === 'btc_bottom_reversal' ||
(p.source || '') === 'funding_reversal') &&
(p.signal === 'buy' || p.signal === 'short'),
)
.sort((a, b) => new Date(b.published_at).getTime() - new Date(a.published_at).getTime())
: []
const macroSignal = visibleMacro[0] ?? null
const colors = getChartColors()
const priceSeries = series as any
if (macroPriceLineRef.current && priceSeries?.removePriceLine) {
try {
priceSeries.removePriceLine(macroPriceLineRef.current as any)
} catch {}
macroPriceLineRef.current = null
}
if (macroSignal && chart && macroVerticalRef.current) {
const pt = Math.floor(new Date(macroSignal.published_at).getTime() / 1000)
const bucketTime = Math.floor(pt / bucketSecs) * bucketSecs
// Only draw the horizontal reference when we have a true signal-entry
// price from the backend. Falling back to a bucket close made the line
// drift across timeframe changes and looked like a bug because it was.
const priceAtSignal =
macroSignal.price_impact?.asset === 'BTC' && macroSignal.price_impact?.price_at_post
? macroSignal.price_impact.price_at_post
: null
if (priceAtSignal != null && priceSeries?.createPriceLine) {
macroPriceLineRef.current = priceSeries.createPriceLine({
price: priceAtSignal,
color: colors.macroAccent,
lineWidth: 2,
lineStyle: 2,
axisLabelVisible: false,
title:
(macroSignal.source || '') === 'btc_bottom_reversal'
? 'Macro bottom'
: 'Funding reversal',
})
}
// Hand off positioning to the shared reposition fn — it knows how
// to re-project on every pan/zoom too, not just on data update.
// (Before this fix, the line was positioned ONCE here and never
// moved with the chart; it looked like a draggable floating element
// because the candles slid out from under it.)
macroBucketTimeRef.current = bucketTime
macroLabelTextRef.current =
(macroSignal.source || '') === 'btc_bottom_reversal' ? 'Macro bottom' : 'Funding reversal'
repositionMacroRef.current?.()
} else {
macroBucketTimeRef.current = null
repositionMacroRef.current?.()
}
if (!fittedRef.current) {
// @ts-expect-error lightweight-charts type
chart.timeScale().fitContent()
fittedRef.current = true
}
}, [candles, posts, externalSelectedId, asset, chartReady])
useEffect(() => {
fittedRef.current = false
}, [timeframe, asset])
// Live-tick the rightmost candle so the chart feels alive between REST polls.
// lightweight-charts' `series.update()` either appends a new bar (newer time)
// or in-place mutates the bar at that timestamp. We always keep `time` ==
// the last candle's bucket so the bar grows in place; high/low expand if
// the live tick exceeds them.
useEffect(() => {
const series = seriesRef.current as any
// dataLoadedRef: update() on a series that hasn't had setData() yet
// creates a chart with a single lone candle.
if (!series || !dataLoadedRef.current) return
const live = livePrices[asset]
if (live == null || !candles.length) return
const last = candles[candles.length - 1]
series.update({
time: last.time as number,
open: last.open,
high: Math.max(last.high, live),
low: Math.min(last.low, live),
close: live,
})
}, [livePrices, asset, candles])
return (
<div
ref={containerRef}
style={{
width: '100%',
height: '100%',
borderRadius: 'var(--r-sm)',
overflow: 'hidden',
cursor: 'crosshair',
position: 'relative',
}}
/>
)
}
+418
View File
@@ -0,0 +1,418 @@
'use client'
import { memo, useEffect, useState } from 'react'
import type { TrumpPost } from '@/types'
/**
* Was this post actually AI-scored, or filtered as off-topic noise before any
* AI call? Single source of truth — used both by the card (to de-emphasise
* noise) and by list views (to offer a "collapse off-topic" toggle), so the
* two can never disagree about what counts as noise.
*/
export function isAiScored(post: Pick<TrumpPost, 'ai_confidence' | 'ai_reasoning'>): boolean {
return (post.ai_confidence ?? 0) > 0 || !!post.ai_reasoning
}
function fmtPct(n: number | null | undefined) {
if (n == null || isNaN(n)) return '—' // null = window not yet closed
const s = n.toFixed(2) + '%'
return n >= 0 ? '+' + s : s
}
function fmtImpactPct(v: number | null | undefined) {
if (v == null || isNaN(v)) return '—'
const s = Math.abs(v).toFixed(2) + '%'
return v >= 0 ? '+' + s : '-' + s
}
function timeAgo(iso: string) {
const diff = Date.now() - new Date(iso).getTime()
const m = Math.floor(diff / 60000)
if (m < 1) return 'just now'
if (m < 60) return m + 'm'
const h = Math.floor(m / 60)
if (h < 24) return h + 'h'
return Math.floor(h / 24) + 'd'
}
/**
* Hydration-safe wrapper for relative time. Returns an empty placeholder on
* SSR / first client render, then the real relative time after mount. Prevents
* the SSR/CSR "5m vs 6m" mismatch error.
*/
function TimeAgo({ iso, suffix = '' }: { iso: string; suffix?: string }) {
const [mounted, setMounted] = useState(false)
useEffect(() => {
setMounted(true)
}, [])
if (!mounted) return <span suppressHydrationWarning>…</span>
return (
<span>
{timeAgo(iso)}
{suffix}
</span>
)
}
/**
* Hydration-safe absolute date formatter. Uses fixed 'en-US' locale + options
* so the server/client outputs match once mounted; renders a placeholder before
* mount to avoid timezone mismatches.
*/
function LocalDateTime({ iso, opts }: { iso: string; opts?: Intl.DateTimeFormatOptions }) {
const [mounted, setMounted] = useState(false)
useEffect(() => {
setMounted(true)
}, [])
if (!mounted) return <span suppressHydrationWarning>…</span>
return <span>{new Date(iso).toLocaleString('en-US', opts)}</span>
}
// Visual identity per signal source. The post stream now mixes Trump posts
// with scanner-emitted technical signals — operators need to tell them
// apart at a glance without reading the text.
//
// When adding a new scanner source, register it here too — otherwise it
// falls through to the generic "first letter" fallback which has no title
// or accent colour.
export const SOURCE_DISPLAY: Record<
string,
{ glyph: string; cls: string; title: string; label: string }
> = {
truth: { glyph: 'T', cls: 'truth', title: 'Trump · Truth Social', label: '@realDonaldTrump' },
breakout: {
glyph: '▲',
cls: 'breakout',
title: 'VCP / breakout scanner',
label: 'Breakout scanner',
},
vcp_breakout: {
glyph: '▲',
cls: 'breakout',
title: 'VCP / breakout scanner',
label: 'Breakout scanner',
},
reversal: { glyph: '⇋', cls: 'reversal', title: 'Reversal scanner', label: 'Reversal scanner' },
btc_bottom_reversal: {
glyph: '₿',
cls: 'reversal',
title: 'BTC Macro Bottom scanner',
label: 'BTC Macro Bottom',
},
funding_reversal: {
glyph: 'ƒ',
cls: 'reversal',
title: 'BTC Funding Rate Reversal scanner',
label: 'Funding Reversal',
},
kol_divergence: {
glyph: '⚖',
cls: 'whale',
title: 'KOL Talks-vs-Trades Divergence',
label: 'KOL Divergence',
},
sma_reclaim: { glyph: '〽', cls: 'breakout', title: 'SMA reclaim scanner', label: 'SMA Reclaim' },
rsi_reversal: {
glyph: '⇋',
cls: 'reversal',
title: 'RSI reversal scanner',
label: 'RSI Reversal',
},
whale: { glyph: '🐋', cls: 'whale', title: 'On-chain whale alert', label: 'Whale alert' },
manual: { glyph: '✋', cls: 'manual', title: 'Manual entry', label: 'Manual' },
}
function SourceIcon({ source }: { source: string }) {
const d = SOURCE_DISPLAY[source.toLowerCase()]
if (d) {
return (
<div className={`src-ico ${d.cls}`} title={d.title}>
{d.glyph}
</div>
)
}
// Unknown source — show first letter so user can still tell it apart.
return (
<div className="src-ico external" title={`Source: ${source}`}>
{source.charAt(0).toUpperCase()}
</div>
)
}
function SignalPill({ signal }: { signal: string | null }) {
if (!signal || signal === 'hold') return <span className="sig hold">HOLD</span>
if (signal === 'buy') return <span className="sig buy">BUY</span>
if (signal === 'short') return <span className="sig short">SHORT</span>
if (signal === 'sell') return <span className="sig sell">SELL</span>
return <span className={`sig ${signal}`}>{signal.toUpperCase()}</span>
}
interface PostRowProps {
post: TrumpPost
selected?: boolean
onClick?: () => void
}
const PostRow = memo(function PostRow({ post, selected, onClick }: PostRowProps) {
const [expanded, setExpanded] = useState(false)
const impact = post.price_impact
function handleClick() {
if (!onClick) setExpanded((e) => !e)
onClick?.()
}
// Off-topic Trump posts (most of them) are filtered before any AI call, so
// they carry confidence 0 + no reasoning. Treat those as un-scored noise and
// de-emphasise them. Shared helper so list-level "collapse off-topic" agrees.
const aiScored = isAiScored(post)
return (
<div
className={`post-row ${selected ? 'selected' : ''} ${aiScored ? '' : 'noise'} ${post.signal === 'buy' ? 'signal-buy' : post.signal === 'short' ? 'signal-short' : ''}`}
onClick={handleClick}
>
{/* ── main row ── */}
<div className="post-row-main">
<SourceIcon source={post.source} />
<div className="post-body">
<div className="meta">
{/* Author label depends on source — non-Trump signals come from
technical scanners or external modules, not @realDonaldTrump. */}
<span className="mono" style={{ color: 'var(--ink-2)', fontWeight: 500 }}>
{SOURCE_DISPLAY[post.source?.toLowerCase?.()]?.label ?? post.source ?? 'Signal'}
</span>
<span>·</span>
<TimeAgo iso={post.published_at} suffix=" ago" />
<span>·</span>
{aiScored ? (
<span
className={`chip ${post.sentiment === 'bullish' ? 'up' : post.sentiment === 'bearish' ? 'down' : 'neutral'}`}
style={{ padding: '2px 8px', fontSize: 11 }}
>
{post.sentiment}
</span>
) : (
<span
style={{
padding: '2px 8px',
fontSize: 11,
fontWeight: 600,
borderRadius: 4,
color: 'var(--ink-4)',
background: 'var(--bg-sunk)',
border: '1px solid var(--line)',
letterSpacing: '0.02em',
}}
>
off-topic · not crypto
</span>
)}
</div>
<p
className="text"
style={{
...(expanded
? { display: 'block', overflow: 'visible', WebkitLineClamp: 'unset' }
: {}),
// Noise posts are de-emphasised: dimmer text + shorter preview so
// the reader can skip them at a glance without opening.
...(aiScored ? {} : { color: 'var(--ink-4)' }),
}}
>
{expanded
? post.text
: post.text.slice(0, aiScored ? 180 : 90) +
(post.text.length > (aiScored ? 180 : 90) ? '…' : '')}
</p>
</div>
{/* Aside (signal pill / target / impact / AI%) only for scored posts.
Noise posts render as a compact two-column row (no aside) — the
'off-topic · not crypto' tag in the meta line is enough. */}
{aiScored && (
<div className="post-aside">
<SignalPill signal={post.signal} />
{/* Target asset chip for actionable signals */}
{post.target_asset && (post.signal === 'buy' || post.signal === 'short') && (
<span
style={{
fontSize: 10,
fontWeight: 700,
fontFamily: 'var(--mono)',
padding: '2px 6px',
borderRadius: 4,
background:
post.signal === 'buy' ? 'rgba(34,197,94,0.12)' : 'rgba(239,68,68,0.12)',
color: post.signal === 'buy' ? '#22c55e' : '#ef4444',
letterSpacing: '0.04em',
}}
>
{post.target_asset}
{post.expected_move_pct ? ` +${post.expected_move_pct}%` : ''}
</span>
)}
<div className="impact-mini">
{impact ? (
<>
<span className="tf">1h move</span>
<span
className={`delta ${impact.m1h == null ? '' : impact.m1h >= 0 ? 'up' : 'down'}`}
>
{impact.m1h == null ? '…' : fmtPct(impact.m1h)}
</span>
</>
) : (
<span className="tf">no data</span>
)}
</div>
<div className="row gap-s" style={{ fontSize: 11, color: 'var(--ink-3)' }}>
<span>AI</span>
<span className="mono" style={{ color: 'var(--ink-2)', fontWeight: 500 }}>
{post.ai_confidence}%
</span>
</div>
</div>
)}
</div>
{/* ── expanded detail ── */}
{expanded && (
<div className="post-row-detail" onClick={(e) => e.stopPropagation()}>
{/* AI confidence bar — only when the post was actually AI-scored.
Off-topic/noise posts (relevant=false, conf 0, no reasoning) show
a neutral note instead of a misleading empty 0% bar. */}
{aiScored ? (
<div>
<div className="ai-metric-head">
<span>AI confidence</span>
<strong>{post.ai_confidence}%</strong>
</div>
<div className="confidence-bar">
<div style={{ width: post.ai_confidence + '%' }} />
</div>
</div>
) : (
<div style={{ fontSize: 12, color: 'var(--ink-3)', padding: '4px 0' }}>
Not crypto-relevant — skipped AI scoring.
</div>
)}
{/* Trade routing — target asset + expected move */}
{post.target_asset && (post.signal === 'buy' || post.signal === 'short') && (
<div style={{ display: 'flex', gap: 8, alignItems: 'center', marginBottom: 4 }}>
<span className="tiny">Trade</span>
<span
style={{
fontSize: 12,
fontWeight: 700,
fontFamily: 'var(--mono)',
padding: '3px 8px',
borderRadius: 5,
background:
post.signal === 'buy' ? 'rgba(34,197,94,0.12)' : 'rgba(239,68,68,0.12)',
color: post.signal === 'buy' ? '#22c55e' : '#ef4444',
}}
>
{post.signal === 'buy'
? `↑ LONG ${post.target_asset}`
: `↓ SHORT ${post.target_asset}`}
</span>
{post.expected_move_pct != null && (
<span style={{ fontSize: 11, color: 'var(--ink-3)' }}>
{`model projection ~${post.expected_move_pct}% · 1h`}
</span>
)}
{post.category && (
<span
style={{
fontSize: 10,
color: 'var(--ink-4)',
textTransform: 'uppercase',
letterSpacing: '0.05em',
}}
>
{post.category.replace(/_/g, ' ')}
</span>
)}
</div>
)}
{/* AI reasoning */}
{post.ai_reasoning && (
<div>
<div className="ai-reasoning-label">
{post.signal === 'buy' || post.signal === 'short'
? 'Why this signal fired'
: 'Why this was filtered out'}
</div>
<div className="ai-reasoning-card">{post.ai_reasoning}</div>
</div>
)}
{/* Price impact — peak move in signal direction per window */}
{impact && (
<div>
<div
className="tiny"
style={{ marginBottom: 8 }}
>{`Price moved · ${impact.asset} · after signal`}</div>
<div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr 1fr', gap: 8 }}>
{(['m5', 'm15', 'm1h'] as const).map((key) => {
const label = key === 'm5' ? '5m' : key === 'm15' ? '15m' : '1h'
const v = impact[key] // null = window still open
const correct =
impact[`correct_${key}` as 'correct_m5' | 'correct_m15' | 'correct_m1h']
const pending = v == null
return (
<div
key={key}
style={{
padding: 10,
background: 'var(--bg-sunk)',
borderRadius: 'var(--r-sm)',
border: `1px solid ${pending ? 'var(--amber)' : 'var(--line)'}`,
textAlign: 'center',
opacity: pending ? 0.75 : 1,
}}
>
<div style={{ fontSize: 10, color: 'var(--ink-3)', marginBottom: 4 }}>
{label}
</div>
<div
className={pending ? '' : `delta ${v >= 0 ? 'up' : 'down'}`}
style={{
fontSize: 14,
fontWeight: 600,
color: pending ? 'var(--ink-3)' : undefined,
}}
>
{pending ? '…' : fmtImpactPct(v)}
</div>
{!pending && correct != null && (
<div
style={{
fontSize: 10,
marginTop: 4,
color: correct ? 'var(--up)' : 'var(--down)',
}}
>
{correct ? '✓' : '✗'}
</div>
)}
{pending && (
<div style={{ fontSize: 9, marginTop: 4, color: 'var(--amber)' }}>live</div>
)}
</div>
)
})}
</div>
</div>
)}
</div>
)}
</div>
)
})
export default PostRow
export { SignalPill, SourceIcon, fmtPct, timeAgo, TimeAgo, LocalDateTime }
@@ -0,0 +1,299 @@
'use client'
import { useState, useEffect } from 'react'
import { useWsSubscribe } from '@/lib/wsContext'
const API_BASE = '/api/proxy/api'
interface SignalAlert {
type: 'funding_signal'
symbol: string
time: string
close: number
tbr: number
vol_mult: number
bb_pct: number
bb_upper: number
btc_trend: string
enabled: boolean
}
function symbolLabel(s: string) {
return s.replace('USDT', '')
}
function timeAgo(iso: string) {
const diff = (Date.now() - new Date(iso).getTime()) / 1000
if (diff < 60) return `${Math.round(diff)}s ago`
if (diff < 3600) return `${Math.round(diff / 60)}m ago`
return `${Math.round(diff / 3600)}h ago`
}
// ── Main component ────────────────────────────────────────────────────────────
// Display-only: toggle is operator-only (requires X-Ingest-Key) so the
// on/off switch is intentionally absent from the user-facing UI.
export default function SignalMonitor() {
const isZh = false // i18n shelved — Chinese branches kept as dead code for future revival; see messages/zh.json
const [enabled, setEnabledState] = useState(false)
const [signals, setSignals] = useState<SignalAlert[]>([])
const [btcTrend, setBtcTrend] = useState<string | null>(null)
const [lastScan, setLastScan] = useState<Date | null>(null)
// ── Load initial state ───────────────────────────────────────────────────
useEffect(() => {
fetch(`${API_BASE}/signal/status`)
.then((r) => {
if (!r.ok) throw new Error()
return r.json()
})
.then((d) => {
setEnabledState(d.enabled)
})
.catch(() => {})
fetch(`${API_BASE}/signal/history?limit=20`)
.then((r) => r.json())
.then((list: SignalAlert[]) => {
if (!Array.isArray(list)) return
setSignals(list)
if (list.length > 0) {
setBtcTrend(list[0].btc_trend)
setLastScan(new Date(list[0].time))
}
})
.catch(() => {})
}, [])
// ── WebSocket listener (shared singleton connection via WsProvider) ─────────
useWsSubscribe('funding_signal', (msg) => {
const alert = msg as SignalAlert
setBtcTrend(alert.btc_trend)
setLastScan(new Date(alert.time))
setSignals((prev) => [alert, ...prev].slice(0, 50))
})
// ── Render ───────────────────────────────────────────────────────────────
const btcUp = btcTrend?.includes('↑')
return (
<div className="card" style={{ padding: 20, marginTop: 12 }}>
{/* Header */}
<div
style={{
display: 'flex',
alignItems: 'flex-start',
justifyContent: 'space-between',
marginBottom: 14,
}}
>
<div>
<div
style={{
fontSize: 12,
fontWeight: 700,
letterSpacing: '0.06em',
textTransform: 'uppercase',
color: 'var(--ink-3)',
marginBottom: 3,
}}
>
{isZh ? '突破监控' : 'Breakout Monitor'}
</div>
<div style={{ fontSize: 11, color: 'var(--ink-3)' }}>
{isZh ? 'ETH · LINK · 5 分钟扫描' : 'ETH · LINK · 5m scan'}
</div>
</div>
{/* Enabled status dot — display-only; toggle is operator-only (X-Ingest-Key) */}
<div
style={{
display: 'flex',
alignItems: 'center',
gap: 6,
fontSize: 11,
color: enabled ? '#22c55e' : 'var(--ink-3)',
}}
>
<div
style={{
width: 7,
height: 7,
borderRadius: '50%',
background: enabled ? '#22c55e' : 'var(--ink-4)',
boxShadow: enabled ? '0 0 0 2px rgba(34,197,94,0.25)' : 'none',
}}
/>
{enabled ? (isZh ? '监控中' : 'Active') : isZh ? '已暂停' : 'Paused'}
</div>
</div>
{/* Status row: BTC trend + last scan */}
<div
style={{
display: 'flex',
alignItems: 'center',
justifyContent: 'space-between',
fontSize: 11,
color: 'var(--ink-3)',
padding: '6px 10px',
borderRadius: 8,
background: 'rgba(255,255,255,0.04)',
marginBottom: 14,
}}
>
<span>
BTC &nbsp;
{btcTrend ? (
<strong style={{ color: btcUp ? '#22c55e' : '#ef4444' }}>{btcTrend}</strong>
) : (
<span style={{ opacity: 0.5 }}>—</span>
)}
</span>
<span>
{lastScan
? isZh
? `最近信号 ${timeAgo(lastScan.toISOString())}`
: `Last signal ${timeAgo(lastScan.toISOString())}`
: enabled
? isZh
? '扫描中…'
: 'Scanning…'
: isZh
? '已暂停'
: 'Paused'}
</span>
</div>
{/* Signal list */}
{signals.length === 0 ? (
<div
style={{
fontSize: 13,
color: 'var(--ink-3)',
textAlign: 'center',
padding: '20px 0',
lineHeight: 1.5,
}}
>
{enabled
? isZh
? '· 正在等待信号…'
: '· Watching for signals…'
: isZh
? '· 暂无历史信号'
: '· No signals yet'}
</div>
) : (
<div style={{ display: 'flex', flexDirection: 'column', gap: 8 }}>
{signals.map((s) => (
<div
key={`${s.symbol}-${s.time}`}
style={{
padding: '11px 13px',
borderRadius: 10,
background: 'rgba(255,255,255,0.04)',
borderLeft: `3px solid ${s.enabled ? '#22c55e' : 'rgba(255,255,255,0.15)'}`,
}}
>
{/* Top row */}
<div
style={{
display: 'flex',
justifyContent: 'space-between',
alignItems: 'center',
marginBottom: 8,
}}
>
<div style={{ display: 'flex', alignItems: 'center', gap: 8 }}>
<span
style={{
fontWeight: 700,
fontSize: 14,
fontFamily: 'var(--mono)',
color: 'var(--ink)',
}}
>
{symbolLabel(s.symbol)}
</span>
{!s.enabled && (
<span
style={{
fontSize: 9,
padding: '2px 6px',
borderRadius: 4,
background: 'rgba(255,255,255,0.08)',
color: 'var(--ink-3)',
textTransform: 'uppercase',
letterSpacing: '0.05em',
}}
>
silent
</span>
)}
</div>
<span style={{ fontSize: 11, color: 'var(--ink-3)' }}>{timeAgo(s.time)}</span>
</div>
{/* Metrics grid */}
<div style={{ display: 'grid', gridTemplateColumns: 'repeat(3, 1fr)', gap: 6 }}>
{[
{
label: isZh ? '价格' : 'Price',
value: `$${s.close.toLocaleString(undefined, { maximumFractionDigits: 2 })}`,
color: 'var(--ink)',
},
{
label: isZh ? '主动买入' : 'Taker Buy',
value: `${(s.tbr * 100).toFixed(1)}%`,
color: '#22c55e',
},
{
label: isZh ? '成交量倍数' : 'Vol ×',
value: `${s.vol_mult}×`,
color: '#22c55e',
},
].map((m) => (
<div
key={m.label}
style={{
background: 'rgba(255,255,255,0.03)',
borderRadius: 6,
padding: '5px 8px',
}}
>
<div
style={{
fontSize: 9,
color: 'var(--ink-3)',
marginBottom: 2,
textTransform: 'uppercase',
letterSpacing: '0.04em',
}}
>
{m.label}
</div>
<div
style={{
fontSize: 13,
fontFamily: 'var(--mono)',
fontWeight: 600,
color: m.color,
}}
>
{m.value}
</div>
</div>
))}
</div>
{/* Footer */}
<div style={{ fontSize: 10, color: 'var(--ink-3)', marginTop: 8 }}>
{isZh ? `BB squeeze 处于第 ${s.bb_pct} 分位` : `BB squeeze ${s.bb_pct}th pct`}{' '}
&nbsp;·&nbsp; {s.btc_trend}
</div>
</div>
))}
</div>
)}
</div>
)
}