import { EventDetail, Ledger, num } from './api'; export type Point = [number, number]; const seconds = (at: string) => { const t = Date.parse(at.replace(' ', 'T')); return Number.isNaN(t) ? 0 : t / 1000; }; const now = () => Date.now() / 1000; const clock = (t: number) => new Date(t * 1000).toTimeString().slice(0, 8); export function priceSeries(detail: EventDetail): Point[] { const first = detail.summary.optionNames[0]; const current = num(detail.state.markets[0]?.price) || 0.5; const trades = [...detail.history].reverse(); if (trades.length === 0) { return [ [now() - 60, current], [now(), current], ]; } const start = seconds(trades[0].at) || now(); const points: Point[] = [[start - 60, 0.5]]; for (const t of trades) { const quantity = num(t.quantity); const unit = quantity > 0 ? num(t.pricePaid) / quantity : current; const price = t.optionName === first ? unit : 1 - unit; points.push([seconds(t.at) || start, Math.max(0, Math.min(1, price))]); } return points; } export function balanceSeries(ledger: Ledger): Point[] { const rows = ledger.entries; const balance = num(ledger.balance); if (rows.length === 0) { return [ [now() - 60, balance], [now(), balance], ]; } const start = seconds(rows[0].at) || now(); const points: Point[] = [[start - 60, Math.max(0, num(rows[0].balanceAfter) - num(rows[0].amount))]]; for (const row of rows) { points.push([seconds(row.at) || start, num(row.balanceAfter)]); } return points; } const TICKS = [0, 1, 2, 3, 4]; export function LineChart(props: { series: { points: Point[]; tone: 'accent' | 'yes' | 'no' }[]; range?: [number, number]; height?: number; }) { const all = props.series.flatMap((s) => s.points); const t0 = Math.min(...all.map((p) => p[0])); const t1 = Math.max(...all.map((p) => p[0]), t0 + 60); let [lo, hi] = props.range ?? [Math.min(...all.map((p) => p[1]), 0), Math.max(...all.map((p) => p[1]))]; if (hi <= lo) hi = lo + 1; if (!props.range) hi = lo + Math.ceil(((hi - lo) * 1.1) / 4) * 4; // headroom, in four whole steps const x = (t: number) => ((t - t0) / (t1 - t0)) * 100; const y = (v: number) => 100 - ((v - lo) / (hi - lo)) * 100; const label = (v: number) => (hi - lo <= 1 ? v.toFixed(2).replace(/\.?0+$/, '') || '0' : Math.round(v).toLocaleString()); return (