aboutsummaryrefslogtreecommitdiffstats
path: root/ui-web/src/Chart.tsx
blob: 4caf3a52299f339c83a4cccdc5d936c9fbbfecfd (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
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 (
    <div className="chart card2">
      <div className="yaxis">
        {TICKS.map((i) => (
          <span key={i}>{label(hi - ((hi - lo) * i) / 4)}</span>
        ))}
      </div>
      <svg viewBox="0 0 100 100" preserveAspectRatio="none" style={{ height: props.height ?? 150 }}>
        {TICKS.map((i) => (
          <line key={i} className="grid" x1="0" x2="100" y1={i * 25} y2={i * 25} />
        ))}
        {props.series.map((s, i) => (
          <path
            key={i}
            className={'stroke-' + s.tone}
            d={s.points.map((p, j) => `${j ? 'L' : 'M'}${x(p[0]).toFixed(2)} ${y(p[1]).toFixed(2)}`).join(' ')}
          />
        ))}
      </svg>
      <div className="xaxis">
        {TICKS.map((i) => (
          <span key={i}>{clock(t0 + ((t1 - t0) * i) / 4)}</span>
        ))}
      </div>
    </div>
  );
}