Files
OpenFin/frontend/src/components/InstrumentChart.tsx
OpenSquared f71e3be3ff feat: market events filters, no-auto-bootstrap, star label deoverlap
- MarketEvents: date presets (7j/30j/3m/6m/1an/Tout/Perso), instrument
  impact filter (ticker + min score + direction → auto-sort by inst score),
  sort controls (date/score/nom + asc/desc), clear-all button, count bar
- Market events list endpoint: full SQL JOIN rewrite supporting instrument
  filter, date range, origin, sort_by=instrument_score
- Disable auto-bootstrap on startup (macro/eco/categories) — manual only
- CycleActions: bootstrap group (Macro/Eco/Categories) with force checkbox,
  grouped layout (detection / bootstrap / data / ai / portfolio)
- cycle_actions router: /bootstrap-macro, /bootstrap-eco, /bootstrap-categories
  endpoints + group field on all action catalogue entries
- InstrumentChart: greedy row placement for star labels (4 rows × 20px)
  to eliminate horizontal overlap; labels now inline (★ + text)

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-06-25 21:27:21 +02:00

314 lines
10 KiB
TypeScript

import { useRef, useEffect } from 'react'
interface PriceCandle {
time: string
open: number
high: number
low: number
close: number
volume: number
}
interface LinePoint {
time: string
value: number
}
interface ChartEvent {
date: string
title: string
level: string
category?: string
impact_score?: number
end_date?: string | null
description?: string
}
interface Props {
priceData: PriceCandle[]
indicators: Record<string, LinePoint[]>
events?: ChartEvent[]
height?: number
onDateHover?: (date: string | null) => void
}
const MA_COLORS: Record<string, string> = {
ma20: '#f59e0b',
ma50: '#3b82f6',
ma100: '#22d3ee',
ma200: '#a855f7',
}
const CAT_COLORS: Record<string, string> = {
event_calendar: '#f59e0b',
geopolitical: '#ef4444',
fundamental: '#10b981',
report: '#3b82f6',
sentiment: '#8b5cf6',
technical: '#06b6d4',
}
const CAT_LABELS: Record<string, string> = {
event_calendar: 'Cal.',
geopolitical: 'Géo.',
fundamental: 'Fund.',
report: 'Report',
sentiment: 'Sent.',
technical: 'Tech.',
}
export default function InstrumentChart({ priceData, indicators, events = [], height = 420, onDateHover }: Props) {
const containerRef = useRef<HTMLDivElement>(null)
const cleanupRef = useRef<(() => void) | null>(null)
const onHoverRef = useRef(onDateHover)
// Keep callback ref fresh without triggering chart rebuild
useEffect(() => { onHoverRef.current = onDateHover }, [onDateHover])
useEffect(() => {
cleanupRef.current?.()
cleanupRef.current = null
if (!containerRef.current || !priceData.length) return
let active = true
import('lightweight-charts').then((lc: any) => {
if (!active || !containerRef.current) return
const { createChart, CrosshairMode, ColorType, LineStyle } = lc
const chart = createChart(containerRef.current, {
width: containerRef.current.clientWidth,
height,
layout: {
background: { type: ColorType.Solid, color: 'transparent' },
textColor: '#64748b',
fontSize: 11,
},
grid: {
vertLines: { color: 'rgba(255,255,255,0.04)' },
horzLines: { color: 'rgba(255,255,255,0.04)' },
},
crosshair: { mode: CrosshairMode.Normal },
rightPriceScale: { borderColor: 'rgba(255,255,255,0.1)' },
timeScale: {
borderColor: 'rgba(255,255,255,0.1)',
timeVisible: true,
secondsVisible: false,
fixLeftEdge: true,
fixRightEdge: true,
},
handleScroll: true,
handleScale: true,
})
// Volume (bottom 18%)
const totalVol = priceData.reduce((s, d) => s + (d.volume || 0), 0)
if (totalVol > 0) {
const volSeries = chart.addHistogramSeries({
color: 'rgba(148,163,184,0.2)',
priceFormat: { type: 'volume' },
priceScaleId: 'volume',
})
chart.priceScale('volume').applyOptions({ scaleMargins: { top: 0.82, bottom: 0 } })
volSeries.setData(priceData.map(d => ({
time: d.time,
value: d.volume,
color: d.close >= d.open ? 'rgba(16,185,129,0.25)' : 'rgba(239,68,68,0.25)',
})))
}
// Candlesticks
const candleSeries = chart.addCandlestickSeries({
upColor: '#10b981',
downColor: '#ef4444',
borderUpColor: '#10b981',
borderDownColor: '#ef4444',
wickUpColor: '#6ee7b7',
wickDownColor: '#fca5a5',
})
candleSeries.setData(priceData)
// MA lines
for (const [key, color] of Object.entries(MA_COLORS)) {
const data = indicators[key]
if (data?.length) {
chart.addLineSeries({
color,
lineWidth: key === 'ma200' ? 1.5 : 1,
priceLineVisible: false,
lastValueVisible: true,
crosshairMarkerVisible: false,
}).setData(data)
}
}
// Bollinger Bands
if (indicators.bb_upper?.length && indicators.bb_lower?.length) {
const bbOpts = {
color: 'rgba(148,163,184,0.32)',
lineWidth: 1,
lineStyle: LineStyle.Dashed,
priceLineVisible: false,
lastValueVisible: false,
crosshairMarkerVisible: false,
}
chart.addLineSeries(bbOpts).setData(indicators.bb_upper)
chart.addLineSeries(bbOpts).setData(indicators.bb_lower)
}
chart.timeScale().fitContent()
// ── Star overlay — ★ icons positioned via chart coordinate API ────────
const candleMap: Record<string, number> = {}
for (const c of priceData) candleMap[c.time] = c.high
const starsOverlay = document.createElement('div')
starsOverlay.style.cssText = [
'position:absolute', 'top:0', 'left:0', 'width:100%', 'height:100%',
'pointer-events:none', 'overflow:hidden', 'z-index:10',
].join(';')
containerRef.current!.appendChild(starsOverlay)
const renderStars = () => {
if (!active) return
starsOverlay.innerHTML = ''
const cw = containerRef.current?.clientWidth ?? 0
// ── Collect visible events with their x coords ──────────────────────
type Placed = { xCoord: number; halfW: number; ev: typeof events[0] }
const visible: Placed[] = []
for (const ev of events) {
const xCoord = chart.timeScale().timeToCoordinate(ev.date as any)
if (xCoord === null || xCoord < 0 || xCoord > cw) continue
const title = ev.title.slice(0, 20)
const halfW = Math.max(30, title.length * 6 + 12) // approx px half-width
visible.push({ xCoord, halfW, ev })
}
// ── Greedy row placement (up to 4 rows, 20px apart) ─────────────────
const ROW_H = 20 // pixels between rows
const MAX_ROWS = 4
// rowEnds[r] = rightmost x already occupied in row r
const rowEnds: number[] = Array(MAX_ROWS).fill(-Infinity)
// Sort by x so greedy works left-to-right
visible.sort((a, b) => a.xCoord - b.xCoord)
for (const { xCoord, halfW, ev } of visible) {
const left = xCoord - halfW
const right = xCoord + halfW + 4
// Find first row where the label fits (no overlap)
let row = 0
for (let r = 0; r < MAX_ROWS; r++) {
if (rowEnds[r] <= left) { row = r; break }
if (r === MAX_ROWS - 1) row = r // last resort: use bottom row
}
rowEnds[row] = right
const yBase = 6 + row * ROW_H
const cat = ev.category ?? 'fundamental'
const color = CAT_COLORS[cat] ?? '#94a3b8'
const score = ev.impact_score ?? 0.5
const sz = score >= 0.8 ? 16 : score >= 0.6 ? 13 : 11
const wrap = document.createElement('div')
wrap.style.cssText = [
`position:absolute`, `left:${xCoord}px`, `top:${yBase}px`,
`transform:translateX(-50%)`,
`display:flex`, `align-items:center`, `gap:3px`,
`pointer-events:auto`, `cursor:default`,
].join(';')
wrap.title = `${ev.title}\n${ev.date}${ev.end_date ? ' → ' + ev.end_date : ''}`
const star = document.createElement('span')
star.style.cssText = [
`font-size:${sz}px`, `color:${color}`, `line-height:1`,
`filter:drop-shadow(0 0 3px ${color}80)`,
].join(';')
star.textContent = '★'
const lbl = document.createElement('span')
lbl.style.cssText = [
`font-size:10px`, `font-family:ui-monospace,monospace`,
`color:${color}`, `white-space:nowrap`,
`text-shadow:0 1px 4px #000,0 0 6px #000`,
`line-height:1`, `max-width:100px`,
`overflow:hidden`, `text-overflow:ellipsis`,
`font-weight:600`,
].join(';')
lbl.textContent = ev.title.slice(0, 20)
wrap.appendChild(star)
wrap.appendChild(lbl)
starsOverlay.appendChild(wrap)
}
}
renderStars()
chart.timeScale().subscribeVisibleLogicalRangeChange(renderStars)
// Crosshair → date callback
chart.subscribeCrosshairMove((param: any) => {
if (param?.time && typeof param.time === 'string') {
onHoverRef.current?.(param.time)
} else if (!param?.point) {
onHoverRef.current?.(null) // mouse left chart
}
})
const ro = new ResizeObserver(() => {
if (containerRef.current) chart.applyOptions({ width: containerRef.current.clientWidth })
})
ro.observe(containerRef.current)
cleanupRef.current = () => {
ro.disconnect()
chart.timeScale().unsubscribeVisibleLogicalRangeChange(renderStars)
if (starsOverlay.parentNode) starsOverlay.parentNode.removeChild(starsOverlay)
chart.remove()
}
})
return () => {
active = false
cleanupRef.current?.()
cleanupRef.current = null
}
}, [priceData, indicators, events, height])
return (
<div className="bg-dark-900/60 rounded-xl border border-slate-700/40 overflow-hidden">
<div className="flex items-center gap-5 px-4 py-2 border-b border-slate-700/30 text-xs text-slate-500">
{Object.entries(MA_COLORS).map(([k, c]) => (
<span key={k} className="flex items-center gap-1.5">
<span className="inline-block w-5 h-0.5 rounded" style={{ background: c }} />
{k.toUpperCase()}
</span>
))}
<span className="flex items-center gap-1.5 opacity-40">
<span className="inline-block w-5 border-t border-dashed border-slate-400" />BB(20,2)
</span>
<span className="ml-auto flex items-center gap-2.5">
{Object.entries(CAT_COLORS).map(([cat, c]) => (
<span key={cat} className="flex items-center gap-0.5" style={{ color: c }}>
<span style={{ fontSize: 10 }}></span>
<span style={{ fontSize: 9 }}>{CAT_LABELS[cat]}</span>
</span>
))}
</span>
</div>
{!priceData.length ? (
<div className="flex items-center justify-center" style={{ height }}>
<span className="text-slate-500 text-sm">Chargement...</span>
</div>
) : (
<div ref={containerRef} style={{ height: `${height}px`, width: '100%', position: 'relative' }} />
)}
</div>
)
}