'use client'; import { Text, View, XStack } from '@hanzo/gui'; import * as React from 'react'; import type { StrategyLeg } from './strategy-builder'; // --------------------------------------------------------------------------- // Types // --------------------------------------------------------------------------- export type { StrategyLeg }; export interface PnlDiagramProps extends React.HTMLAttributes { readonly legs: StrategyLeg[]; readonly spotPrice: number; readonly multiplier?: number; } // --------------------------------------------------------------------------- // P/L calculation // --------------------------------------------------------------------------- function calcLegPnl(leg: StrategyLeg, price: number, multiplier: number): number { const premium = leg.premium ?? 0; let intrinsic: number; if (leg.type === 'call') { intrinsic = Math.max(price - leg.strike, 0); } else { intrinsic = Math.max(leg.strike - price, 0); } const sign = leg.action === 'buy' ? 1 : -1; return sign * (intrinsic - premium) * leg.quantity * multiplier; } function calcTotalPnl(legs: StrategyLeg[], price: number, multiplier: number): number { return legs.reduce((sum, leg) => sum + calcLegPnl(leg, price, multiplier), 0); } // --------------------------------------------------------------------------- // SVG helpers // --------------------------------------------------------------------------- interface ViewBox { xMin: number; xMax: number; yMin: number; yMax: number; } function buildPath(points: Array<{ x: number; y: number }>, vb: ViewBox, width: number, height: number): string { if (points.length === 0) return ''; const scaleX = (x: number) => ((x - vb.xMin) / (vb.xMax - vb.xMin)) * width; const scaleY = (y: number) => height - ((y - vb.yMin) / (vb.yMax - vb.yMin)) * height; const parts = points.map((p, i) => { const sx = scaleX(p.x); const sy = scaleY(p.y); return i === 0 ? `M${sx},${sy}` : `L${sx},${sy}`; }); return parts.join(' '); } // --------------------------------------------------------------------------- // Leg colors // --------------------------------------------------------------------------- // Legs are told apart by position on the achromatic chart ramp, not by hue — // and they resolve through tokens.css, so a host reskin moves them too. const LEG_COLORS = ['var(--chart-1)', 'var(--chart-2)', 'var(--chart-3)', 'var(--chart-4)']; // Breakeven markers ride the same ramp; the ring is the page ground. const BREAKEVEN_COLOR = 'var(--chart-1)'; const BREAKEVEN_RING = 'var(--background)'; // --------------------------------------------------------------------------- // PnlDiagram // --------------------------------------------------------------------------- export const PnlDiagram = React.forwardRef( function PnlDiagram(props, ref) { const { legs, spotPrice, multiplier = 100, className, ...rest } = props; const containerRef = React.useRef(null); const [hoverX, setHoverX] = React.useState(null); const [dims, setDims] = React.useState({ width: 600, height: 240 }); // Observe container size React.useEffect(() => { const el = containerRef.current; if (!el) return; const observer = new ResizeObserver((entries) => { const entry = entries[0]; if (entry) { setDims({ width: Math.max(entry.contentRect.width, 200), height: Math.max(entry.contentRect.height, 120), }); } }); observer.observe(el); return () => observer.disconnect(); }, []); // Compute price range: strikes +/- 20% const allStrikes = legs.map((l) => l.strike); const minStrike = Math.min(...allStrikes, spotPrice); const maxStrike = Math.max(...allStrikes, spotPrice); const range = maxStrike - minStrike || spotPrice * 0.1; const xMin = minStrike - range * 0.3; const xMax = maxStrike + range * 0.3; // Sample points const SAMPLES = 200; const step = (xMax - xMin) / SAMPLES; const combinedPoints = React.useMemo(() => { const pts: Array<{ x: number; y: number }> = []; for (let i = 0; i <= SAMPLES; i++) { const price = xMin + i * step; pts.push({ x: price, y: calcTotalPnl(legs, price, multiplier) }); } return pts; }, [legs, multiplier, xMin, step]); const legPointSets = React.useMemo(() => { return legs.map((leg) => { const pts: Array<{ x: number; y: number }> = []; for (let i = 0; i <= SAMPLES; i++) { const price = xMin + i * step; pts.push({ x: price, y: calcLegPnl(leg, price, multiplier) }); } return pts; }); }, [legs, multiplier, xMin, step]); // Y-axis range const allY = combinedPoints.map((p) => p.y); const rawYMin = Math.min(...allY); const rawYMax = Math.max(...allY); const yPad = Math.max((rawYMax - rawYMin) * 0.15, 10); const vb: ViewBox = { xMin, xMax, yMin: rawYMin - yPad, yMax: rawYMax + yPad }; const { width, height } = dims; const PADDING = { top: 20, bottom: 28, left: 56, right: 16 }; const chartW = width - PADDING.left - PADDING.right; const chartH = height - PADDING.top - PADDING.bottom; const scaleX = (x: number) => PADDING.left + ((x - vb.xMin) / (vb.xMax - vb.xMin)) * chartW; const scaleY = (y: number) => PADDING.top + chartH - ((y - vb.yMin) / (vb.yMax - vb.yMin)) * chartH; // Breakeven points (where combined PnL crosses zero) const breakevens = React.useMemo(() => { const pts: number[] = []; for (let i = 1; i < combinedPoints.length; i++) { const prev = combinedPoints[i - 1]!; const curr = combinedPoints[i]!; if ((prev.y <= 0 && curr.y >= 0) || (prev.y >= 0 && curr.y <= 0)) { // Linear interpolation const ratio = Math.abs(prev.y) / (Math.abs(prev.y) + Math.abs(curr.y)); pts.push(prev.x + ratio * (curr.x - prev.x)); } } return pts; }, [combinedPoints]); // Max gain / max loss const maxGain = Math.max(...allY); const maxLoss = Math.min(...allY); const maxGainPoint = combinedPoints.find((p) => p.y === maxGain); const maxLossPoint = combinedPoints.find((p) => p.y === maxLoss); // Zero line const zeroY = scaleY(0); // Hover const handleMouseMove = React.useCallback( (e: React.MouseEvent) => { const rect = e.currentTarget.getBoundingClientRect(); const mouseX = e.clientX - rect.left; const price = vb.xMin + ((mouseX - PADDING.left) / chartW) * (vb.xMax - vb.xMin); if (price >= vb.xMin && price <= vb.xMax) { setHoverX(price); } else { setHoverX(null); } }, [vb.xMin, vb.xMax, chartW], ); const handleMouseLeave = React.useCallback(() => setHoverX(null), []); const hoverPnl = hoverX !== null ? calcTotalPnl(legs, hoverX, multiplier) : null; // Combined path with fill const combinedPath = buildPath( combinedPoints.map((p) => ({ x: scaleX(p.x), y: scaleY(p.y) })).map((p) => ({ x: p.x - PADDING.left, y: p.y - PADDING.top })), { xMin: 0, xMax: chartW, yMin: 0, yMax: chartH }, chartW, chartH, ); return ( {/* This and everything inside it is the chart itself — left exactly as it was: every fill/stroke/d/viewBox below is an SVG presentation attribute, not Tailwind, and out of scope for a className→prop conversion. The one change is `select-none`, a real Tailwind utility (not a presentation attribute), moved to an equivalent inline style with no visual effect. */} {/* Background */} {/* Grid lines */} {Array.from({ length: 5 }).map((_, i) => { const y = PADDING.top + (chartH / 4) * i; const val = vb.yMax - ((vb.yMax - vb.yMin) / 4) * i; return ( {val >= 0 ? '+' : ''}{val.toFixed(0)} ); })} {/* Zero line */} {zeroY >= PADDING.top && zeroY <= PADDING.top + chartH && ( )} {/* Individual leg lines (dashed) */} {legPointSets.map((pts, i) => { const path = pts.map((p, j) => { const sx = scaleX(p.x); const sy = scaleY(p.y); return j === 0 ? `M${sx},${sy}` : `L${sx},${sy}`; }).join(' '); return ( ); })} {/* Combined P/L fill (green above zero, red below) */} {combinedPoints.length > 0 && (() => { const path = combinedPoints.map((p, i) => { const sx = scaleX(p.x); const sy = scaleY(p.y); return i === 0 ? `M${sx},${sy}` : `L${sx},${sy}`; }).join(' '); const lastX = scaleX(combinedPoints[combinedPoints.length - 1]!.x); const firstX = scaleX(combinedPoints[0]!.x); const clampedZeroY = Math.max(PADDING.top, Math.min(PADDING.top + chartH, zeroY)); const fillPath = `${path} L${lastX},${clampedZeroY} L${firstX},${clampedZeroY} Z`; return ( <> ); })()} {/* Combined P/L line */} {combinedPoints.length > 0 && ( { const sx = scaleX(p.x); const sy = scaleY(p.y); return i === 0 ? `M${sx},${sy}` : `L${sx},${sy}`; }).join(' ')} fill="none" stroke="#e4e4e7" strokeWidth="1.5" /> )} {/* Current price vertical line */} {spotPrice.toFixed(2)} {/* Breakeven markers */} {breakevens.map((be, i) => ( {be.toFixed(1)} ))} {/* Max gain marker */} {maxGainPoint && maxGain > 0 && ( )} {/* Max loss marker */} {maxLossPoint && maxLoss < 0 && ( )} {/* Hover crosshair */} {hoverX !== null && hoverPnl !== null && ( = 0 ? '#22c55e' : '#ef4444'} stroke={BREAKEVEN_RING} strokeWidth="1" /> {/* Tooltip */} ${hoverX.toFixed(2)} = 0 ? '#22c55e' : '#ef4444'} fontSize="9" fontFamily="monospace" fontWeight="600" > {hoverPnl >= 0 ? '+' : ''}{hoverPnl.toFixed(2)} )} {/* X-axis labels */} {Array.from({ length: 5 }).map((_, i) => { const x = vb.xMin + ((vb.xMax - vb.xMin) / 4) * i; return ( {x.toFixed(0)} ); })} {/* Legend */} Combined {legs.map((leg, i) => ( {leg.action === 'buy' ? 'B' : 'S'} {leg.quantity} {leg.strike} {leg.type === 'call' ? 'C' : 'P'} ))} {breakevens.length > 0 && ( BE: {breakevens.map((b) => b.toFixed(1)).join(', ')} )} ); }, );