{
  "$schema": "https://ui.shadcn.com/schema/registry-item.json",
  "name": "trading-chart",
  "title": "Trading Chart",
  "description": "Candlestick chart with trade markers, clustering, and live Binance updates.",
  "dependencies": [
    "lightweight-charts",
    "next-themes"
  ],
  "registryDependencies": [
    "utils"
  ],
  "files": [
    {
      "path": "registry/voraui/trading-chart/index.ts",
      "content": "export { TradingChart } from \"./trading-chart\";\nexport { TradingChartSkeleton } from \"./components/skeleton\";\nexport type {\n  TradingChartProps,\n  OhlcvCandle,\n  TradeSignal,\n  TradeSide,\n  Timeframe,\n} from \"./types\";\n",
      "type": "registry:lib",
      "target": "components/voraui/trading-chart/index.ts"
    },
    {
      "path": "registry/voraui/trading-chart/trading-chart.tsx",
      "content": "\"use client\";\n\nimport { cn } from \"@/lib/utils\";\nimport { TradingChartSkeleton } from \"./components/skeleton\";\nimport type { TradingChartProps } from \"./types\";\nimport { useKlines } from \"./hooks/use-klines\";\nimport { useChartInstance } from \"./hooks/use-chart-instance\";\nimport { useChartTheme } from \"./hooks/use-chart-theme\";\nimport { useChartData } from \"./hooks/use-chart-data\";\nimport { useLiveCandles } from \"./hooks/use-live-candles\";\nimport { useBoundaryNotification } from \"./hooks/use-boundary-notification\";\n\nfunction TradingChart({\n  symbol = \"BTCUSDT\",\n  timeframe = \"1h\",\n  trades = [],\n  candles: candlesProp,\n  live = true,\n  height = 500,\n  limit = 500,\n  showTooltips = true,\n  className,\n}: TradingChartProps) {\n  const hasOverrideCandles = candlesProp !== undefined;\n\n  const { candles, setCandles, loading, error, fetchMore, hasMoreHistory } = useKlines(\n    symbol,\n    timeframe,\n    { limit, enabled: !hasOverrideCandles },\n  );\n\n  const effectiveCandles = candlesProp ?? candles;\n\n  const { containerRef, stateRef, chartEpoch } = useChartInstance({\n    symbol,\n    height,\n    candles: effectiveCandles,\n    trades,\n    timeframe,\n    showTooltips,\n    loading,\n    hasOverrideCandles,\n    // With prop-supplied candles there is no more history to fetch.\n    hasMoreHistory: hasOverrideCandles ? false : hasMoreHistory,\n    fetchMore,\n  });\n\n  useChartTheme(stateRef);\n\n  useChartData({ stateRef, chartEpoch, candles: effectiveCandles, trades, symbol, timeframe });\n\n  useLiveCandles({\n    stateRef,\n    symbol,\n    timeframe,\n    enabled: live && !hasOverrideCandles,\n    setCandles,\n  });\n\n  const showNoMoreData = useBoundaryNotification({\n    hasMoreHistory,\n    loading,\n    candlesCount: candles.length,\n    hasOverrideCandles,\n    symbol,\n    timeframe,\n  });\n\n  return (\n    <div className={cn(\"relative w-full overflow-hidden rounded-xl bg-card\", className)}>\n      {loading && effectiveCandles.length === 0 && (\n        <TradingChartSkeleton height={height} className=\"absolute inset-0 z-50\" />\n      )}\n\n      {error && effectiveCandles.length === 0 && !loading && (\n        <div role=\"alert\" className=\"absolute inset-0 z-50 flex items-center justify-center\">\n          <p className=\"text-xs text-muted-foreground\">Market data is unavailable ({error}).</p>\n        </div>\n      )}\n\n      {showNoMoreData && (\n        <div className=\"absolute left-3 top-3 z-40 duration-300 animate-in fade-in slide-in-from-left-2\">\n          <div className=\"flex items-center gap-2 rounded-lg border border-border bg-card/90 px-3 py-1.5 shadow-lg backdrop-blur-sm\">\n            <div className=\"h-1.5 w-1.5 shrink-0 rounded-full bg-amber-400\" />\n            <span className=\"whitespace-nowrap text-xs font-medium text-muted-foreground\">\n              No more historical data\n            </span>\n          </div>\n        </div>\n      )}\n\n      <div ref={containerRef} className=\"relative w-full\" style={{ height }} />\n    </div>\n  );\n}\n\nexport { TradingChart };\n",
      "type": "registry:component",
      "target": "components/voraui/trading-chart/trading-chart.tsx"
    },
    {
      "path": "registry/voraui/trading-chart/types.ts",
      "content": "export type Timeframe = \"1m\" | \"5m\" | \"15m\" | \"1h\" | \"4h\" | \"8h\" | \"1d\" | \"1w\" | \"1M\";\n\nexport interface OhlcvCandle {\n  /** Unix seconds (candle open time). */\n  time: number;\n  open: number;\n  high: number;\n  low: number;\n  close: number;\n  volume: number;\n  /** True while the candle is still open (live updates). */\n  isForming?: boolean;\n}\n\nexport type TradeSide = \"BUY\" | \"SELL\";\n\nexport interface TradeSignal {\n  id: string;\n  /** Execution time in epoch milliseconds. */\n  ts: number;\n  side: TradeSide;\n  /** Execution price; with quantity set, tooltips show price * quantity as position size. */\n  price: number;\n  quantity?: number;\n  note?: string;\n  category?: \"trade\" | \"indicator\";\n  indicator?: string;\n  value?: number;\n  /** Links buy/sell pairs, e.g. for PnL grouping. */\n  tradeId?: string;\n}\n\nexport interface TradingChartProps {\n  /** Binance spot symbol, e.g. \"BTCUSDT\". */\n  symbol?: string;\n  timeframe?: Timeframe;\n  /** Trade/indicator markers to draw on the chart. Always the user's own data. */\n  trades?: TradeSignal[];\n  /** Provide your own candles to bypass the bundled Binance fetcher. */\n  candles?: OhlcvCandle[];\n  /** Poll Binance for live candle updates. Ignored when candles is set. */\n  live?: boolean;\n  height?: number;\n  /** Number of candles for the initial load (Binance max 1000). */\n  limit?: number;\n  showTooltips?: boolean;\n  className?: string;\n}\n",
      "type": "registry:lib",
      "target": "components/voraui/trading-chart/types.ts"
    },
    {
      "path": "registry/voraui/trading-chart/components/skeleton.tsx",
      "content": "\"use client\";\n\nimport { useMemo } from \"react\";\nimport { cn } from \"@/lib/utils\";\n\nexport interface TradingChartSkeletonProps {\n  className?: string;\n  /** Matches TradingChartProps[\"height\"]. */\n  height?: number;\n}\n\nexport interface GhostCandle {\n  up: boolean;\n  bodyHeightPct: number;\n  wickHeightPct: number;\n}\n\nconst GHOST_CANDLE_COUNT = 48;\n\n// Two decimals: Safari rewrites longer style percentages, which then mismatch on hydration.\nconst roundPct = (value: number) => Math.round(value * 100) / 100;\n\n/** Deterministic heights; Math.random would cause a hydration mismatch. */\nexport function generateGhostCandles(count: number): GhostCandle[] {\n  return Array.from({ length: count }, (_, i) => {\n    const bodyHeightPct = roundPct(25 + 35 * Math.abs(Math.sin(i * 0.7)));\n    const wickHeightPct = roundPct(Math.min(bodyHeightPct + 12 + (i % 3) * 4, 100));\n    return { up: i % 2 === 0, bodyHeightPct, wickHeightPct };\n  });\n}\n\nexport function TradingChartSkeleton({ className, height = 500 }: TradingChartSkeletonProps) {\n  const candles = useMemo(() => generateGhostCandles(GHOST_CANDLE_COUNT), []);\n\n  return (\n    <div\n      role=\"status\"\n      className={cn(\"voraui-trading-chart-skeleton-shimmer relative w-full overflow-hidden rounded-xl bg-card\", className)}\n      style={{ height }}\n    >\n      <style href=\"voraui-trading-chart-skeleton\" precedence=\"low\">{`\n        @keyframes voraui-trading-chart-skeleton-shimmer {\n          from { transform: translateX(-100%); }\n          to { transform: translateX(100%); }\n        }\n        .voraui-trading-chart-skeleton-shimmer::after {\n          content: \"\";\n          position: absolute;\n          inset: 0;\n          background: linear-gradient(90deg, transparent, rgba(255, 255, 255, 0.15), transparent);\n          animation: voraui-trading-chart-skeleton-shimmer 1.8s ease-in-out infinite;\n        }\n        @media (prefers-reduced-motion: reduce) {\n          .voraui-trading-chart-skeleton-shimmer::after {\n            animation: none;\n          }\n        }\n      `}</style>\n      {/* pr-14 keeps the candles clear of the price-axis placeholder column. */}\n      <div className=\"absolute inset-0 flex items-end gap-[2px] pb-8 pl-3 pr-14 pt-4\">\n        {candles.map((candle, i) => (\n          <div key={i} className=\"relative flex-1\" style={{ height: `${candle.wickHeightPct}%` }}>\n            <div className=\"absolute left-1/2 top-0 h-full w-px -translate-x-1/2 bg-muted-foreground/20\" />\n            <div\n              className={cn(\n                \"absolute left-1/2 w-full max-w-[6px] -translate-x-1/2 rounded-[1px]\",\n                candle.up ? \"bg-emerald-500/15\" : \"bg-rose-500/15\",\n              )}\n              style={{\n                height: `${candle.bodyHeightPct}%`,\n                top: `${roundPct((candle.wickHeightPct - candle.bodyHeightPct) / 2)}%`,\n              }}\n            />\n          </div>\n        ))}\n      </div>\n      <div className=\"absolute right-0 top-0 flex h-full w-12 flex-col justify-between gap-2 bg-background/30 py-4 pr-2\">\n        {Array.from({ length: 5 }, (_, i) => (\n          <div key={i} className=\"h-2 w-8 self-end rounded bg-muted-foreground/15\" />\n        ))}\n      </div>\n      <span className=\"sr-only\">Loading market data</span>\n    </div>\n  );\n}\n",
      "type": "registry:component",
      "target": "components/voraui/trading-chart/components/skeleton.tsx"
    },
    {
      "path": "registry/voraui/trading-chart/hooks/use-chart-instance.ts",
      "content": "\"use client\";\n\nimport { useEffect, useRef, useState } from \"react\";\nimport type { RefObject } from \"react\";\nimport { useTheme } from \"next-themes\";\nimport type {\n  IChartApi,\n  ISeriesApi,\n  ISeriesMarkersPluginApi,\n  LogicalRange,\n  Time,\n} from \"lightweight-charts\";\nimport type { OhlcvCandle, Timeframe, TradeSignal } from \"../types\";\nimport { CANDLE_SERIES_OPTIONS, getChartOptions } from \"../lib/chart-options\";\nimport { createSignalTooltip, type SignalTooltip } from \"../lib/signal-tooltip\";\n\n/** Props snapshot for the imperative chart handlers, so they never see stale closures. */\nexport interface LatestChartProps {\n  candles: OhlcvCandle[];\n  trades: TradeSignal[];\n  timeframe: Timeframe;\n  showTooltips: boolean;\n  loading: boolean;\n  hasOverrideCandles: boolean;\n  hasMoreHistory: boolean;\n  fetchMore: (beforeSec: number) => Promise<OhlcvCandle[]>;\n}\n\n/** Mutable chart runtime shared by the trading chart hooks. */\nexport interface ChartState {\n  chart: IChartApi | null;\n  series: ISeriesApi<\"Candlestick\"> | null;\n  markers: ISeriesMarkersPluginApi<Time> | null;\n  latest: LatestChartProps;\n  /** True once the initial fitContent ran for the current chart instance. */\n  autoFitDone: boolean;\n  lastCandlesLength: number;\n  /** Last seen `${symbol}-${timeframe}`, to detect dataset resets. */\n  lastKey: string;\n  /** Open time of the newest closed bar merged from live polling. */\n  lastClosedTime: number;\n  /** True between a symbol/timeframe reset and the next full setData. */\n  isResetting: boolean;\n  /** Set by pagination, consumed by the next data-sync run (survives until read). */\n  isPrependingHistory: boolean;\n  oldestTimestamp: number | null;\n}\n\nexport interface UseChartInstanceOptions extends LatestChartProps {\n  symbol: string;\n  height: number;\n}\n\n/** Owns the chart lifecycle: lazy init, tooltip, pagination, resize, disposal. */\nexport function useChartInstance(options: UseChartInstanceOptions): {\n  containerRef: RefObject<HTMLDivElement | null>;\n  stateRef: RefObject<ChartState>;\n  /** Bumped when a freshly initialized chart instance is ready for data. */\n  chartEpoch: number;\n} {\n  const { symbol, height, ...latest } = options;\n  const { resolvedTheme } = useTheme();\n  const containerRef = useRef<HTMLDivElement | null>(null);\n  const tooltipRef = useRef<SignalTooltip | null>(null);\n  const [chartEpoch, setChartEpoch] = useState(0);\n\n  const stateRef = useRef<ChartState>({\n    chart: null,\n    series: null,\n    markers: null,\n    latest,\n    autoFitDone: false,\n    lastCandlesLength: 0,\n    lastKey: `${symbol}-${latest.timeframe}`,\n    lastClosedTime: 0,\n    isResetting: false,\n    isPrependingHistory: false,\n    oldestTimestamp: null,\n  });\n\n  useEffect(() => {\n    stateRef.current.latest = latest;\n  });\n\n  useEffect(() => {\n    if (!latest.showTooltips) tooltipRef.current?.hide();\n  }, [latest.showTooltips]);\n\n  useEffect(() => {\n    const state = stateRef.current;\n    let disposed = false;\n    let resizeObserver: ResizeObserver | null = null;\n    let chartInitialized = false;\n    let isLoadingMore = false;\n\n    const handleVisibleRangeChange = async (range: LogicalRange | null) => {\n      if (!range || isLoadingMore || !state.oldestTimestamp || !state.latest.hasMoreHistory) {\n        return;\n      }\n\n      // A full-dataset range is the initial fitContent or a zoom-out, not a\n      // scroll toward history; only paginate on a real move to the left edge.\n      if (range.to >= state.latest.candles.length - 2) return;\n      if (range.from >= 50) return;\n\n      isLoadingMore = true;\n      try {\n        const older = await state.latest.fetchMore(state.oldestTimestamp);\n        // Only flag a prepend when candles were actually fetched.\n        state.isPrependingHistory = older.length > 0;\n      } finally {\n        isLoadingMore = false;\n      }\n    };\n\n    const initChart = async (container: HTMLDivElement) => {\n      const { createChart, CandlestickSeries, createSeriesMarkers } = await import(\n        \"lightweight-charts\"\n      );\n      if (disposed) return;\n\n      const chart = createChart(container, {\n        width: container.clientWidth,\n        ...getChartOptions(resolvedTheme, height),\n      });\n      const series = chart.addSeries(CandlestickSeries, CANDLE_SERIES_OPTIONS);\n\n      state.chart = chart;\n      state.series = series;\n      state.markers = createSeriesMarkers(series, []);\n\n      const tooltip = createSignalTooltip({\n        container,\n        getCandles: () => state.latest.candles,\n        getTrades: () => state.latest.trades,\n        getTimeframe: () => state.latest.timeframe,\n        isEnabled: () => state.latest.showTooltips,\n      });\n      tooltipRef.current = tooltip;\n      chart.subscribeCrosshairMove(tooltip.onCrosshairMove);\n\n      chart.timeScale().fitContent();\n      chart.timeScale().subscribeVisibleLogicalRangeChange(handleVisibleRangeChange);\n\n      setChartEpoch((epoch) => epoch + 1);\n    };\n\n    if (containerRef.current) {\n      resizeObserver = new ResizeObserver((entries) => {\n        const { width, height: rectHeight } = entries[0].contentRect;\n        if (width > 0 && rectHeight > 0 && !chartInitialized) {\n          chartInitialized = true;\n          initChart(containerRef.current!);\n        } else if (width > 0 && chartInitialized && state.chart) {\n          state.chart.applyOptions({ width });\n        }\n      });\n      resizeObserver.observe(containerRef.current);\n    }\n\n    return () => {\n      disposed = true;\n      resizeObserver?.disconnect();\n      tooltipRef.current?.dispose();\n      tooltipRef.current = null;\n      state.chart?.remove();\n      state.chart = null;\n      state.series = null;\n      state.markers = null;\n      // Forces the next data-sync run to setData + fitContent the new instance.\n      state.lastCandlesLength = 0;\n      state.autoFitDone = false;\n    };\n    // Only reinitialize if height changes.\n    // eslint-disable-next-line react-hooks/exhaustive-deps\n  }, [height]);\n\n  return { containerRef, stateRef, chartEpoch };\n}\n",
      "type": "registry:hook",
      "target": "components/voraui/trading-chart/hooks/use-chart-instance.ts"
    },
    {
      "path": "registry/voraui/trading-chart/hooks/use-chart-theme.ts",
      "content": "\"use client\";\n\nimport { useEffect } from \"react\";\nimport type { RefObject } from \"react\";\nimport { useTheme } from \"next-themes\";\nimport { getThemeOptions } from \"../lib/chart-options\";\nimport type { ChartState } from \"./use-chart-instance\";\n\n/** Restyle the chart when the next-themes theme changes. */\nexport function useChartTheme(stateRef: RefObject<ChartState>) {\n  const { resolvedTheme } = useTheme();\n\n  useEffect(() => {\n    stateRef.current.chart?.applyOptions(getThemeOptions(resolvedTheme));\n  }, [stateRef, resolvedTheme]);\n}\n",
      "type": "registry:hook",
      "target": "components/voraui/trading-chart/hooks/use-chart-theme.ts"
    },
    {
      "path": "registry/voraui/trading-chart/hooks/use-chart-data.ts",
      "content": "\"use client\";\n\nimport { useEffect } from \"react\";\nimport type { RefObject } from \"react\";\nimport type { LogicalRange } from \"lightweight-charts\";\nimport type { OhlcvCandle, Timeframe, TradeSignal } from \"../types\";\nimport { sanitizeCandles } from \"../lib/candle-validation\";\nimport { toChartTime } from \"../lib/chart-time\";\nimport { alignSignalsToBars, buildSeriesMarkers } from \"../lib/markers\";\nimport type { ChartState } from \"./use-chart-instance\";\n\nexport interface UseChartDataOptions {\n  stateRef: RefObject<ChartState>;\n  /** Bumped by useChartInstance when a fresh chart instance is ready for data. */\n  chartEpoch: number;\n  candles: OhlcvCandle[];\n  trades: TradeSignal[];\n  symbol: string;\n  timeframe: Timeframe;\n}\n\n/** Push candles and trade markers into the chart whenever they change. */\nexport function useChartData({\n  stateRef,\n  chartEpoch,\n  candles,\n  trades,\n  symbol,\n  timeframe,\n}: UseChartDataOptions) {\n  // Sync candle data.\n  useEffect(() => {\n    const state = stateRef.current;\n    if (!state.series || !state.chart) return;\n\n    const key = `${symbol}-${timeframe}`;\n    const keyChanged = state.lastKey !== key;\n    state.lastKey = key;\n\n    if (candles.length === 0) {\n      if (keyChanged) {\n        state.series.setData([]);\n        state.chart.timeScale().resetTimeScale();\n        state.autoFitDone = false;\n        state.lastCandlesLength = 0;\n        state.lastClosedTime = 0;\n        state.isResetting = true;\n      }\n      return;\n    }\n\n    const sanitized = sanitizeCandles(candles);\n    if (sanitized.length === 0) return;\n\n    // setData only on resets/history injection; streaming goes through series.update().\n    const numCandlesAdded = sanitized.length - state.lastCandlesLength;\n    const isMajorChange =\n      keyChanged || state.lastCandlesLength === 0 || Math.abs(numCandlesAdded) > 2;\n\n    if (isMajorChange) {\n      state.isResetting = false;\n      const timeScale = state.chart.timeScale();\n      const prevLogicalRange: LogicalRange | null = state.autoFitDone\n        ? timeScale.getVisibleLogicalRange()\n        : null;\n\n      const mapped = sanitized.map((c) => ({\n        time: toChartTime(c.time, timeframe),\n        open: c.open,\n        high: c.high,\n        low: c.low,\n        close: c.close,\n      }));\n      const deduped = mapped.filter((c, i, arr) => i === 0 || c.time !== arr[i - 1].time);\n      state.series.setData(deduped);\n\n      if (!state.autoFitDone) {\n        timeScale.fitContent();\n        state.autoFitDone = true;\n      }\n\n      const isHistoryPrepend = state.isPrependingHistory;\n      state.isPrependingHistory = false;\n      if (prevLogicalRange && isHistoryPrepend) {\n        // Shift the view by the prepended count so the visible bars stay put.\n        const prependedCount = state.oldestTimestamp\n          ? sanitized.findIndex((c) => c.time === state.oldestTimestamp)\n          : 0;\n        const shift = prependedCount > 0 ? prependedCount : 0;\n        timeScale.setVisibleLogicalRange({\n          from: prevLogicalRange.from + shift,\n          to: prevLogicalRange.to + shift,\n        });\n      }\n    }\n\n    state.lastCandlesLength = sanitized.length;\n    state.oldestTimestamp = sanitized[0].time;\n  }, [stateRef, candles, symbol, timeframe, chartEpoch]);\n\n  // Sync trade/indicator markers.\n  useEffect(() => {\n    const markers = stateRef.current.markers;\n    if (!markers) return;\n    const aligned = alignSignalsToBars(trades, candles, timeframe);\n    markers.setMarkers(buildSeriesMarkers(aligned));\n  }, [stateRef, candles, trades, timeframe, chartEpoch]);\n}\n",
      "type": "registry:hook",
      "target": "components/voraui/trading-chart/hooks/use-chart-data.ts"
    },
    {
      "path": "registry/voraui/trading-chart/hooks/use-live-candles.ts",
      "content": "\"use client\";\n\nimport { useCallback } from \"react\";\nimport type { Dispatch, RefObject, SetStateAction } from \"react\";\nimport type { OhlcvCandle, Timeframe } from \"../types\";\nimport { isValidCandle } from \"../lib/candle-validation\";\nimport { normalizeToSeconds, toChartTime } from \"../lib/chart-time\";\nimport { useLatestCandlePolling } from \"./use-klines\";\nimport type { ChartState } from \"./use-chart-instance\";\n\nexport interface UseLiveCandlesOptions {\n  stateRef: RefObject<ChartState>;\n  symbol: string;\n  timeframe: Timeframe;\n  enabled: boolean;\n  setCandles: Dispatch<SetStateAction<OhlcvCandle[]>>;\n}\n\n/** Merge polled live candles into the chart series and the candle state. */\nexport function useLiveCandles({\n  stateRef,\n  symbol,\n  timeframe,\n  enabled,\n  setCandles,\n}: UseLiveCandlesOptions) {\n  const handleNewCandle = useCallback(\n    (candle: OhlcvCandle) => {\n      const state = stateRef.current;\n      if (!state.series || !state.chart) return;\n      if (state.isResetting) return;\n\n      // Never mix live candles into a static prop-supplied dataset.\n      if (state.latest.hasOverrideCandles) return;\n\n      // Wait for the initial history, or fitContent would zoom into a 1-2 candle stub.\n      if (state.latest.loading) return;\n\n      if (!isValidCandle(candle)) return;\n\n      const normalizedTime = normalizeToSeconds(Number(candle.time));\n      if (!Number.isFinite(normalizedTime) || normalizedTime <= 0) return;\n\n      const isForming = candle.isForming === true;\n\n      // Skip closed bars we already saw.\n      if (!isForming && normalizedTime <= state.lastClosedTime) return;\n\n      try {\n        state.series.update({\n          time: toChartTime(normalizedTime, state.latest.timeframe),\n          open: candle.open,\n          high: candle.high,\n          low: candle.low,\n          close: candle.close,\n        });\n      } catch {\n        // Thrown for updates older than the earliest bar (timeframe transitions).\n        return;\n      }\n\n      if (!isForming) state.lastClosedTime = normalizedTime;\n\n      setCandles((prev) => {\n        if (prev.length === 0) return [candle];\n        const last = prev[prev.length - 1];\n        const lastTime = Number(last.time);\n\n        if (normalizedTime === lastTime) {\n          const copy = [...prev];\n          copy[copy.length - 1] = candle;\n          return copy;\n        } else if (normalizedTime > lastTime) {\n          return [...prev, candle];\n        }\n        return prev;\n      });\n    },\n    [stateRef, setCandles],\n  );\n\n  useLatestCandlePolling(symbol, timeframe, enabled, handleNewCandle);\n}\n",
      "type": "registry:hook",
      "target": "components/voraui/trading-chart/hooks/use-live-candles.ts"
    },
    {
      "path": "registry/voraui/trading-chart/hooks/use-boundary-notification.ts",
      "content": "\"use client\";\n\nimport { useEffect, useState } from \"react\";\nimport type { Timeframe } from \"../types\";\n\nexport interface UseBoundaryNotificationOptions {\n  hasMoreHistory: boolean;\n  loading: boolean;\n  candlesCount: number;\n  hasOverrideCandles: boolean;\n  symbol: string;\n  timeframe: Timeframe;\n}\n\n/** \"No more historical data\" toast: auto-dismisses after 4s, re-arms on key change. */\nexport function useBoundaryNotification({\n  hasMoreHistory,\n  loading,\n  candlesCount,\n  hasOverrideCandles,\n  symbol,\n  timeframe,\n}: UseBoundaryNotificationOptions): boolean {\n  const atHistoryBoundary = !hasMoreHistory && !loading && candlesCount > 0 && !hasOverrideCandles;\n  const [dismissedKey, setDismissedKey] = useState<string | null>(null);\n\n  useEffect(() => {\n    if (!atHistoryBoundary) return;\n    const timer = setTimeout(() => setDismissedKey(`${symbol}-${timeframe}`), 4000);\n    return () => clearTimeout(timer);\n  }, [atHistoryBoundary, symbol, timeframe]);\n\n  return atHistoryBoundary && dismissedKey !== `${symbol}-${timeframe}`;\n}\n",
      "type": "registry:hook",
      "target": "components/voraui/trading-chart/hooks/use-boundary-notification.ts"
    },
    {
      "path": "registry/voraui/trading-chart/hooks/use-klines.ts",
      "content": "\"use client\";\n\nimport { useCallback, useEffect, useRef, useState } from \"react\";\nimport type { OhlcvCandle, Timeframe } from \"../types\";\nimport { sanitizeCandles } from \"../lib/candle-validation\";\n\n// Binance public spot klines. No API key, CORS-enabled, ~1200 weight/min/IP.\nconst BINANCE_KLINES_URL = \"https://api.binance.com/api/v3/klines\";\n\n/** Binance kline row: [openTimeMs, open, high, low, close, volume, closeTimeMs, ...]. */\nexport type RawKline = [number, string, string, string, string, string, number, ...unknown[]];\n\nexport function normalizeKlines(raw: RawKline[], nowMs: number = Date.now()): OhlcvCandle[] {\n  const out: OhlcvCandle[] = [];\n  for (const k of raw ?? []) {\n    const openMs = Number(k[0]);\n    const open = Number(k[1]);\n    const high = Number(k[2]);\n    const low = Number(k[3]);\n    const close = Number(k[4]);\n    const volume = Number(k[5]);\n    const closeMs = Number(k[6]);\n    if (![openMs, open, high, low, close, volume, closeMs].every(Number.isFinite)) continue;\n    out.push({\n      time: Math.floor(openMs / 1000),\n      open,\n      high,\n      low,\n      close,\n      volume,\n      isForming: closeMs > nowMs,\n    });\n  }\n  return out;\n}\n\nexport async function fetchKlines(\n  symbol: string,\n  interval: Timeframe,\n  options: { limit?: number; startTime?: number; endTime?: number; signal?: AbortSignal } = {},\n): Promise<OhlcvCandle[]> {\n  const params = new URLSearchParams({\n    symbol: symbol.toUpperCase(),\n    interval,\n    limit: String(options.limit ?? 500),\n  });\n  if (options.startTime !== undefined) params.set(\"startTime\", String(options.startTime));\n  if (options.endTime !== undefined) params.set(\"endTime\", String(options.endTime));\n  const res = await fetch(`${BINANCE_KLINES_URL}?${params}`, { signal: options.signal });\n  if (!res.ok) throw new Error(`Binance klines request failed: ${res.status}`);\n  const raw = (await res.json()) as RawKline[];\n  return normalizeKlines(raw);\n}\n\n/** Fetch historical candles with backward pagination support. */\nexport function useKlines(\n  symbol: string,\n  timeframe: Timeframe,\n  options: { limit?: number; enabled?: boolean } = {},\n) {\n  const { limit = 500, enabled = true } = options;\n  const [candles, setCandles] = useState<OhlcvCandle[]>([]);\n  const [loading, setLoading] = useState(enabled);\n  const [error, setError] = useState<string | null>(null);\n  const [hasMoreHistory, setHasMoreHistory] = useState(true);\n  const lastOldestRef = useRef<number | null>(null);\n\n  const fetchMore = useCallback(\n    async (beforeSec: number) => {\n      try {\n        const older = await fetchKlines(symbol, timeframe, {\n          limit: 500,\n          endTime: beforeSec * 1000 - 1,\n        });\n        if (older.length === 0) {\n          setHasMoreHistory(false);\n          return [];\n        }\n        const newOldest = older[0].time;\n        // Oldest timestamp didn't advance: we hit the listing boundary.\n        if (lastOldestRef.current !== null && newOldest >= lastOldestRef.current) {\n          setHasMoreHistory(false);\n          return [];\n        }\n        lastOldestRef.current = newOldest;\n        setCandles((prev) => sanitizeCandles([...older, ...prev]));\n        return older;\n      } catch {\n        setHasMoreHistory(false);\n        return [];\n      }\n    },\n    [symbol, timeframe],\n  );\n\n  useEffect(() => {\n    if (!enabled) return;\n\n    const controller = new AbortController();\n\n    const load = async () => {\n      // Reset state on key param change.\n      setCandles([]);\n      setHasMoreHistory(true);\n      setError(null);\n      setLoading(true);\n      lastOldestRef.current = null;\n\n      try {\n        const initial = await fetchKlines(symbol, timeframe, { limit, signal: controller.signal });\n        if (controller.signal.aborted) return;\n        setCandles(sanitizeCandles(initial));\n        setLoading(false);\n      } catch (err: unknown) {\n        if (controller.signal.aborted || (err as Error).name === \"AbortError\") return;\n        setError((err as Error).message);\n        setLoading(false);\n      }\n    };\n\n    load();\n\n    return () => controller.abort();\n  }, [symbol, timeframe, limit, enabled]);\n\n  // Forced false while disabled so a mid-fetch toggle can't leave loading stuck.\n  return { candles, setCandles, loading: enabled ? loading : false, error, fetchMore, hasMoreHistory };\n}\n\n/** Poll Binance for the latest (closed + forming) candles and push them to the chart. */\nexport function useLatestCandlePolling(\n  symbol: string,\n  timeframe: Timeframe,\n  enabled: boolean,\n  onUpdate: (candle: OhlcvCandle) => void,\n) {\n  const timerRef = useRef<ReturnType<typeof setTimeout> | null>(null);\n\n  useEffect(() => {\n    if (!enabled || !symbol) return;\n    let active = true;\n\n    const intervalFor = (tf: Timeframe): number => {\n      switch (tf) {\n        case \"1m\":\n          return 4_000;\n        case \"5m\":\n        case \"15m\":\n          return 12_000;\n        case \"1h\":\n        case \"4h\":\n        case \"8h\":\n          return 25_000;\n        case \"1d\":\n        case \"1w\":\n        case \"1M\":\n          return 60_000;\n        default:\n          return 30_000;\n      }\n    };\n\n    const poll = async () => {\n      try {\n        const latest = await fetchKlines(symbol, timeframe, { limit: 2 });\n        if (!active) return;\n        for (const candle of latest) onUpdate(candle);\n      } catch {\n        // Retried on the next tick.\n      }\n      if (active) timerRef.current = setTimeout(poll, intervalFor(timeframe));\n    };\n\n    poll();\n\n    return () => {\n      active = false;\n      if (timerRef.current) clearTimeout(timerRef.current);\n    };\n  }, [symbol, timeframe, enabled, onUpdate]);\n}\n",
      "type": "registry:hook",
      "target": "components/voraui/trading-chart/hooks/use-klines.ts"
    },
    {
      "path": "registry/voraui/trading-chart/lib/chart-options.ts",
      "content": "import type { ChartOptions, ColorType, DeepPartial } from \"lightweight-charts\";\nimport { BUY_COLOR, SELL_COLOR } from \"./markers\";\n\nconst WICK_COLOR = \"#838ca1\";\n\nexport const CANDLE_SERIES_OPTIONS = {\n  upColor: BUY_COLOR,\n  downColor: SELL_COLOR,\n  borderUpColor: BUY_COLOR,\n  borderDownColor: SELL_COLOR,\n  wickUpColor: WICK_COLOR,\n  wickDownColor: WICK_COLOR,\n};\n\n/** Theme-dependent chart options, applied at creation and on theme changes. */\nexport function getThemeOptions(resolvedTheme: string | undefined): DeepPartial<ChartOptions> {\n  const isDark = resolvedTheme === \"dark\";\n  const gridColor = isDark ? \"rgba(148,163,184,0.12)\" : \"rgba(0,0,0,0.05)\";\n\n  return {\n    layout: {\n      // \"solid\" = ColorType.Solid; importing the enum would eagerly bundle the library.\n      background: { type: \"solid\" as ColorType.Solid, color: \"rgba(0,0,0,0)\" },\n      textColor: isDark ? \"#9CA3AF\" : \"#374151\",\n    },\n    grid: {\n      vertLines: { color: gridColor },\n      horzLines: { color: gridColor },\n    },\n  };\n}\n\n/** Full options for createChart. */\nexport function getChartOptions(\n  resolvedTheme: string | undefined,\n  height: number,\n): DeepPartial<ChartOptions> {\n  return {\n    height,\n    ...getThemeOptions(resolvedTheme),\n    rightPriceScale: { borderVisible: false },\n    timeScale: {\n      borderVisible: false,\n      timeVisible: true,\n      fixLeftEdge: true,\n      fixRightEdge: true,\n    },\n    crosshair: { mode: 0 },\n  };\n}\n",
      "type": "registry:lib",
      "target": "components/voraui/trading-chart/lib/chart-options.ts"
    },
    {
      "path": "registry/voraui/trading-chart/lib/markers.ts",
      "content": "import type { SeriesMarker, UTCTimestamp } from \"lightweight-charts\";\nimport type { OhlcvCandle, TradeSignal } from \"../types\";\n\nexport const BUY_COLOR = \"#00c176\";\nexport const SELL_COLOR = \"#cf304a\";\nexport const INDICATOR_COLOR = \"#8b5cf6\";\n\nexport type AlignedSignal = TradeSignal & { alignedTime: UTCTimestamp };\n\nexport function floorToIntervalSeconds(tsMs: number, interval: string): number {\n  const d = new Date(tsMs);\n  const ms = d.getTime();\n  const oneMinute = 60 * 1000;\n  const Y = d.getUTCFullYear(),\n    M = d.getUTCMonth(),\n    D = d.getUTCDate(),\n    h = d.getUTCHours();\n  switch (interval) {\n    case \"1m\":\n      return Math.floor(ms / oneMinute) * 60;\n    case \"5m\":\n      return Math.floor(ms / (5 * oneMinute)) * 5 * 60;\n    case \"15m\":\n      return Math.floor(ms / (15 * oneMinute)) * 15 * 60;\n    case \"1h\":\n      return Date.UTC(Y, M, D, h, 0, 0) / 1000;\n    case \"4h\":\n      return Date.UTC(Y, M, D, Math.floor(h / 4) * 4, 0, 0) / 1000;\n    case \"8h\":\n      return Date.UTC(Y, M, D, Math.floor(h / 8) * 8, 0, 0) / 1000;\n    case \"1d\":\n      return Date.UTC(Y, M, D, 0, 0, 0) / 1000;\n    case \"1w\": {\n      // Floor to start of the week (Monday).\n      const dayOfWeek = d.getUTCDay(); // 0=Sun, 1=Mon, ...\n      const daysToMonday = dayOfWeek === 0 ? 6 : dayOfWeek - 1;\n      return Date.UTC(Y, M, D - daysToMonday, 0, 0, 0) / 1000;\n    }\n    case \"1M\":\n      return Date.UTC(Y, M, 1, 0, 0, 0) / 1000;\n    default:\n      return Math.floor(ms / 1000);\n  }\n}\n\nexport function findClosestBarTime(target: number, orderedTimes: number[]): number {\n  if (!orderedTimes.length) return target;\n  let closest = orderedTimes[0];\n  let diff = Math.abs(target - closest);\n  for (let i = 1; i < orderedTimes.length; i++) {\n    const cand = orderedTimes[i];\n    const candDiff = Math.abs(target - cand);\n    if (candDiff < diff) {\n      closest = cand;\n      diff = candDiff;\n    } else if (cand > target && candDiff > diff) {\n      break;\n    }\n  }\n  return closest;\n}\n\n/** Approximate seconds per interval, for the out-of-range tolerance below. */\nconst INTERVAL_SECONDS: Record<string, number> = {\n  \"1m\": 60,\n  \"5m\": 300,\n  \"15m\": 900,\n  \"1h\": 3_600,\n  \"4h\": 14_400,\n  \"8h\": 28_800,\n  \"1d\": 86_400,\n  \"1w\": 604_800,\n  \"1M\": 2_678_400,\n};\n\nexport function alignSignalsToBars(\n  signals: TradeSignal[],\n  candles: OhlcvCandle[],\n  interval: string,\n): AlignedSignal[] {\n  if (!signals?.length || !candles?.length) return [];\n\n  const barTimes = candles.map((c) => c.time);\n  const barSet = new Set(barTimes);\n  // Drop signals whose bar isn't loaded yet; they'd pile up on the edge bar.\n  const tolerance = (INTERVAL_SECONDS[interval] ?? 3_600) * 2;\n\n  return signals.flatMap((signal) => {\n    const snapped = floorToIntervalSeconds(signal.ts, interval);\n    const aligned = barSet.has(snapped) ? snapped : findClosestBarTime(snapped, barTimes);\n    if (Math.abs(aligned - snapped) > tolerance) return [];\n\n    return [\n      {\n        ...signal,\n        alignedTime: aligned as UTCTimestamp,\n      },\n    ];\n  });\n}\n\nexport function buildSeriesMarkers(aligned: AlignedSignal[]): SeriesMarker<UTCTimestamp>[] {\n  const tradeGrouped = new Map<string, AlignedSignal[]>();\n  const indicatorGrouped = new Map<string, AlignedSignal[]>();\n\n  for (const signal of aligned) {\n    if (signal.category === \"indicator\") {\n      const indicatorKey = `${signal.alignedTime}`;\n      if (!indicatorGrouped.has(indicatorKey)) indicatorGrouped.set(indicatorKey, []);\n      indicatorGrouped.get(indicatorKey)!.push(signal);\n      continue;\n    }\n\n    const tradeKey = `${signal.alignedTime}_${signal.side}`;\n    if (!tradeGrouped.has(tradeKey)) tradeGrouped.set(tradeKey, []);\n    tradeGrouped.get(tradeKey)!.push(signal);\n  }\n\n  const markers: SeriesMarker<UTCTimestamp>[] = [];\n\n  for (const [, signals] of tradeGrouped.entries()) {\n    const isBuy = signals[0].side === \"BUY\";\n    const count = signals.length;\n\n    markers.push({\n      time: signals[0].alignedTime,\n      position: isBuy ? \"belowBar\" : \"aboveBar\",\n      color: isBuy ? BUY_COLOR : SELL_COLOR,\n      shape: isBuy ? \"arrowUp\" : \"arrowDown\",\n      size: count >= 3 ? 2 : 1.5,\n      text: count > 1 ? `${count}${isBuy ? \"B\" : \"S\"}` : isBuy ? \"B\" : \"S\",\n    });\n  }\n\n  for (const [, signals] of indicatorGrouped.entries()) {\n    markers.push({\n      time: signals[0].alignedTime,\n      position: \"inBar\",\n      color: INDICATOR_COLOR,\n      shape: \"circle\",\n      size: 1.6,\n      text: \"I\",\n    });\n  }\n\n  return markers.sort((a, b) => (a.time as number) - (b.time as number));\n}\n",
      "type": "registry:lib",
      "target": "components/voraui/trading-chart/lib/markers.ts"
    },
    {
      "path": "registry/voraui/trading-chart/lib/candle-validation.ts",
      "content": "export function isValidCandle(candle: {\n  open: number;\n  high: number;\n  low: number;\n  close: number;\n  time: number;\n}): boolean {\n  const { open, high, low, close, time } = candle;\n\n  if (!isFinite(open) || !isFinite(high) || !isFinite(low) || !isFinite(close)) {\n    return false;\n  }\n  if (open <= 0 || high <= 0 || low <= 0 || close <= 0) {\n    return false;\n  }\n\n  // OHLC consistency: high must be the highest, low the lowest.\n  if (high < Math.max(open, close)) return false;\n  if (low > Math.min(open, close)) return false;\n  if (high < low) return false;\n\n  // Reject candles whose range exceeds 90% of the close price.\n  if ((high - low) / close > 0.9) {\n    return false;\n  }\n\n  // Timestamp must be in seconds, not milliseconds.\n  const MAX_REASONABLE_TS = 9_999_999_999;\n  if (time > MAX_REASONABLE_TS) {\n    return false;\n  }\n\n  return true;\n}\n\nexport function sanitizeCandles<\n  T extends { time: number; open: number; high: number; low: number; close: number },\n>(candles: T[]): T[] {\n  return candles\n    .filter(isValidCandle)\n    .sort((a, b) => a.time - b.time)\n    .filter((c, i, arr) => i === 0 || c.time !== arr[i - 1].time);\n}\n",
      "type": "registry:lib",
      "target": "components/voraui/trading-chart/lib/candle-validation.ts"
    },
    {
      "path": "registry/voraui/trading-chart/lib/chart-time.ts",
      "content": "import type { Time, UTCTimestamp } from \"lightweight-charts\";\n\n/** Timeframes lightweight-charts renders as business days rather than timestamps. */\nconst DAILY_PLUS: ReadonlySet<string> = new Set([\"1d\", \"1w\", \"1M\"]);\n\nexport function isDailyOrHigher(timeframe: string): boolean {\n  return DAILY_PLUS.has(timeframe);\n}\n\n/** Accepts epoch seconds or milliseconds and returns epoch seconds. */\nexport function normalizeToSeconds(ts: number): number {\n  return ts > 9_999_999_999 ? Math.floor(ts / 1000) : ts;\n}\n\n/** Unix seconds to a chart Time: \"YYYY-MM-DD\" for daily+, raw number for intraday. */\nexport function toChartTime(timeSec: number, timeframe: string): Time {\n  return isDailyOrHigher(timeframe)\n    ? new Date(timeSec * 1000).toISOString().split(\"T\")[0]\n    : (timeSec as UTCTimestamp);\n}\n\n/** A chart event time (number, \"YYYY-MM-DD\", or BusinessDay) back to unix seconds. */\nexport function normalizeParamTime(t: unknown): number | undefined {\n  if (t == null) return undefined;\n  if (typeof t === \"number\") return t;\n  if (typeof t === \"string\") return Math.floor(new Date(t + \"T00:00:00Z\").getTime() / 1000);\n  if (typeof t === \"object\" && \"year\" in t) {\n    const bd = t as { year: number; month: number; day: number };\n    return Math.floor(Date.UTC(bd.year, bd.month - 1, bd.day) / 1000);\n  }\n  return undefined;\n}\n",
      "type": "registry:lib",
      "target": "components/voraui/trading-chart/lib/chart-time.ts"
    },
    {
      "path": "registry/voraui/trading-chart/lib/signal-tooltip.ts",
      "content": "import type { MouseEventParams } from \"lightweight-charts\";\nimport type { OhlcvCandle, TradeSignal } from \"../types\";\nimport {\n  alignSignalsToBars,\n  BUY_COLOR,\n  SELL_COLOR,\n  INDICATOR_COLOR,\n  type AlignedSignal,\n} from \"./markers\";\nimport { normalizeParamTime } from \"./chart-time\";\n\nexport interface SignalTooltipDeps {\n  container: HTMLElement;\n  getCandles: () => OhlcvCandle[];\n  getTrades: () => TradeSignal[];\n  getTimeframe: () => string;\n  isEnabled: () => boolean;\n}\n\nexport interface SignalTooltip {\n  /** Pass to chart.subscribeCrosshairMove. */\n  onCrosshairMove: (param: MouseEventParams) => void;\n  hide: () => void;\n  dispose: () => void;\n}\n\nconst STYLE_ID = \"voraui-tooltip-styles\";\nconst TOOLTIP_EDGE_INSET = 8;\nconst TOOLTIP_OFFSET = 12;\n\ninterface TooltipPoint {\n  x: number;\n  y: number;\n}\n\ninterface TooltipPosition {\n  left: number;\n  top: number;\n}\n\ninterface TooltipBox {\n  width: number;\n  height: number;\n}\n\nfunction clamp(value: number, min: number, max: number): number {\n  if (max < min) return min;\n  return Math.min(Math.max(value, min), max);\n}\n\n/** Keeps the tooltip inside the chart while preferring the familiar above-cursor placement. */\nexport function getSignalTooltipPosition(\n  point: TooltipPoint,\n  tooltip: TooltipBox,\n  container: TooltipBox,\n): TooltipPosition {\n  const maxLeft = Math.max(TOOLTIP_EDGE_INSET, container.width - tooltip.width - TOOLTIP_EDGE_INSET);\n  const maxTop = Math.max(TOOLTIP_EDGE_INSET, container.height - tooltip.height - TOOLTIP_EDGE_INSET);\n  const preferredTop = point.y - tooltip.height - TOOLTIP_OFFSET;\n  const belowTop = point.y + TOOLTIP_OFFSET;\n  const top =\n    preferredTop >= TOOLTIP_EDGE_INSET\n      ? preferredTop\n      : belowTop + tooltip.height <= container.height - TOOLTIP_EDGE_INSET\n        ? belowTop\n        : preferredTop;\n\n  return {\n    left: clamp(point.x - tooltip.width / 2, TOOLTIP_EDGE_INSET, maxLeft),\n    top: clamp(top, TOOLTIP_EDGE_INSET, maxTop),\n  };\n}\n\nfunction escapeHtml(value: string): string {\n  return value.replace(/&/g, \"&amp;\").replace(/</g, \"&lt;\").replace(/>/g, \"&gt;\").replace(/\"/g, \"&quot;\");\n}\n\nfunction renderSignalHtml(s: AlignedSignal): string {\n  if (s.category === \"indicator\") {\n    const indicatorLabel = escapeHtml(s.indicator || \"Indicator\");\n    const indicatorValue =\n      typeof s.value === \"number\" && Number.isFinite(s.value) ? ` (${s.value.toFixed(2)})` : \"\";\n    const note = s.note ? `<div style=\"font-size:10px;opacity:0.7;\">${escapeHtml(s.note)}</div>` : \"\";\n    return `\n      <div style=\"display:flex;flex-direction:column;margin-top:4px;gap:2px;\">\n        <div style=\"display:flex;justify-content:space-between;gap:12px;font-size:11px;\">\n          <b style=\"color:${s.side === \"BUY\" ? BUY_COLOR : SELL_COLOR}\">${indicatorLabel} ${s.side}${indicatorValue}</b>\n        </div>\n        ${note}\n      </div>\n    `;\n  }\n\n  const price = Number(s.price);\n  const qty = Number(s.quantity || 0);\n  const amount = qty > 0 ? price * qty : price;\n  const qtySuffix = qty > 0 ? ` (${qty} @ ${price.toLocaleString()})` : \"\";\n  const note = s.note ? `<div style=\"font-size:10px;opacity:0.7;\">${escapeHtml(s.note)}</div>` : \"\";\n\n  return `\n    <div style=\"display:flex;flex-direction:column;margin-top:4px;gap:1px;\">\n      <div style=\"display:flex;justify-content:space-between;gap:12px;font-size:11px;\">\n        <b style=\"color:${s.side === \"BUY\" ? BUY_COLOR : SELL_COLOR}\">${amount.toLocaleString(\"en-US\", { minimumFractionDigits: 0, maximumFractionDigits: 0 })} usd${qtySuffix}</b>\n      </div>\n      ${note}\n    </div>\n  `;\n}\n\n/** Pure renderer for the tooltip body; exported for tests. */\nexport function renderTooltipHtml(list: AlignedSignal[]): string {\n  const signal = list[0];\n  const count = list.length;\n  const indicatorSignals = list.filter((s) => s.category === \"indicator\");\n  const tradeSignals = list.filter((s) => s.category !== \"indicator\");\n  const buys = tradeSignals.filter((s) => s.side === \"BUY\");\n  const sells = tradeSignals.filter((s) => s.side === \"SELL\");\n\n  return `\n    <div style=\"margin-bottom:8px;padding-bottom:6px;border-bottom:1px solid rgba(255,255,255,0.1);display:flex;justify-content:space-between;align-items:center;\">\n      <span style=\"font-weight:600;font-size:13px;\">${new Date(signal.ts).toLocaleDateString(\"en-US\", { month: \"short\", day: \"2-digit\", year: \"numeric\" })}</span>\n      <span style=\"font-size:10px;opacity:0.6;background:rgba(255,255,255,0.1);padding:1px 4px;border-radius:4px;\">${count} Signals</span>\n    </div>\n\n    ${indicatorSignals.length > 0 ? `\n      <div style=\"margin-top:6px\">\n        <div style=\"color:${INDICATOR_COLOR};font-size:10px;text-transform:uppercase;font-weight:bold;margin-bottom:2px\">Indicator Signals</div>\n        ${indicatorSignals.slice(0, 8).map(renderSignalHtml).join(\"\")}\n      </div>\n    ` : \"\"}\n    ${buys.length > 0 ? `\n      <div style=\"margin-top:6px\">\n        <div style=\"color:${BUY_COLOR};font-size:10px;text-transform:uppercase;font-weight:bold;margin-bottom:2px\">Buy Signals</div>\n        ${buys.slice(0, 5).map(renderSignalHtml).join(\"\")}\n      </div>\n    ` : \"\"}\n    ${sells.length > 0 ? `\n      <div style=\"margin-top:8px\">\n        <div style=\"color:${SELL_COLOR};font-size:10px;text-transform:uppercase;font-weight:bold;margin-bottom:2px\">Sell Signals</div>\n        ${sells.slice(0, 5).map(renderSignalHtml).join(\"\")}\n      </div>\n    ` : \"\"}\n  `;\n}\n\nexport function createSignalTooltip({\n  container,\n  getCandles,\n  getTrades,\n  getTimeframe,\n  isEnabled,\n}: SignalTooltipDeps): SignalTooltip {\n  if (!document.getElementById(STYLE_ID)) {\n    const style = document.createElement(\"style\");\n    style.id = STYLE_ID;\n    style.textContent = `\n      @keyframes vorauiTooltipIn {\n        from { opacity: 0; transform: translateY(-4px) scale(0.98); }\n        to   { opacity: 1; transform: translateY(0) scale(1); }\n      }\n    `;\n    document.head.appendChild(style);\n  }\n\n  const el = document.createElement(\"div\");\n  Object.assign(el.style, {\n    position: \"absolute\",\n    pointerEvents: \"none\",\n    zIndex: \"50\",\n    padding: \"12px\",\n    borderRadius: \"12px\",\n    background: \"rgba(17,17,20,0.95)\",\n    color: \"#fff\",\n    fontSize: \"12px\",\n    boxShadow: \"0 8px 32px rgba(0,0,0,0.5)\",\n    border: \"1px solid rgba(255,255,255,0.1)\",\n    backdropFilter: \"blur(8px)\",\n    boxSizing: \"border-box\",\n    display: \"none\",\n    minWidth: \"160px\",\n    maxWidth: `calc(100% - ${TOOLTIP_EDGE_INSET * 2}px)`,\n    maxHeight: `calc(100% - ${TOOLTIP_EDGE_INSET * 2}px)`,\n    overflow: \"hidden\",\n    transition: \"opacity 0.2s ease-in-out\",\n  } as unknown as CSSStyleDeclaration);\n  container.appendChild(el);\n\n  const hide = () => {\n    el.style.display = \"none\";\n  };\n\n  const show = (list: AlignedSignal[], pt: { x: number; y: number }) => {\n    const wasHidden = el.style.display !== \"block\";\n    el.innerHTML = renderTooltipHtml(list);\n    el.style.display = \"block\";\n    const position = getSignalTooltipPosition(\n      pt,\n      { width: el.offsetWidth || 180, height: el.offsetHeight || 80 },\n      { width: container.clientWidth, height: container.clientHeight },\n    );\n    el.style.left = `${position.left}px`;\n    el.style.top = `${position.top}px`;\n\n    // Animate only on hidden -> shown; re-animating on every move would flicker.\n    if (wasHidden && !window.matchMedia(\"(prefers-reduced-motion: reduce)\").matches) {\n      el.style.animation = \"none\";\n      void el.offsetWidth;\n      el.style.animation = \"vorauiTooltipIn 0.16s ease-out\";\n    }\n  };\n\n  const onCrosshairMove = (param: MouseEventParams) => {\n    if (!isEnabled()) {\n      hide();\n      return;\n    }\n    const pt = param.point;\n    const t = normalizeParamTime(param.time);\n    if (!pt || t == null) {\n      hide();\n      return;\n    }\n    if (\n      pt.x < 0 ||\n      pt.y < 0 ||\n      pt.x > container.clientWidth ||\n      pt.y > container.clientHeight\n    ) {\n      hide();\n      return;\n    }\n\n    const aligned = alignSignalsToBars(getTrades(), getCandles(), getTimeframe());\n    const found = aligned.filter((s) => s.alignedTime === t);\n    if (found.length > 0) {\n      show(found, pt);\n    } else {\n      hide();\n    }\n  };\n\n  return {\n    onCrosshairMove,\n    hide,\n    dispose: () => el.remove(),\n  };\n}\n",
      "type": "registry:lib",
      "target": "components/voraui/trading-chart/lib/signal-tooltip.ts"
    }
  ],
  "type": "registry:block"
}