@stocksharp/trading-controls 1.3.0 → 1.4.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (62) hide show
  1. package/README.md +113 -5
  2. package/dist/esm/chart-engine.js +15 -0
  3. package/dist/esm/chart-engine.js.map +1 -0
  4. package/dist/esm/control-types.js +4 -0
  5. package/dist/esm/control-types.js.map +1 -1
  6. package/dist/esm/equity-widget.js +261 -0
  7. package/dist/esm/equity-widget.js.map +1 -0
  8. package/dist/esm/heatmap-grid.js +271 -0
  9. package/dist/esm/heatmap-grid.js.map +1 -0
  10. package/dist/esm/index.js +19 -0
  11. package/dist/esm/index.js.map +1 -1
  12. package/dist/esm/optimization-heatmap-widget.js +303 -0
  13. package/dist/esm/optimization-heatmap-widget.js.map +1 -0
  14. package/dist/esm/option-smile-widget.js +252 -0
  15. package/dist/esm/option-smile-widget.js.map +1 -0
  16. package/dist/esm/pnl-curve.js +5 -1
  17. package/dist/esm/pnl-curve.js.map +1 -1
  18. package/dist/esm/surface-grid.js +282 -0
  19. package/dist/esm/surface-grid.js.map +1 -0
  20. package/dist/esm/surface-widget.js +379 -0
  21. package/dist/esm/surface-widget.js.map +1 -0
  22. package/dist/sstradingcontrols.js +1595 -168
  23. package/dist/sstradingcontrols.js.map +4 -4
  24. package/dist/types/chart-engine.d.ts +3 -0
  25. package/dist/types/chart-engine.d.ts.map +1 -0
  26. package/dist/types/control-types.d.ts +4 -0
  27. package/dist/types/control-types.d.ts.map +1 -1
  28. package/dist/types/equity-widget.d.ts +34 -0
  29. package/dist/types/equity-widget.d.ts.map +1 -0
  30. package/dist/types/heatmap-grid.d.ts +88 -0
  31. package/dist/types/heatmap-grid.d.ts.map +1 -0
  32. package/dist/types/index.d.ts +15 -0
  33. package/dist/types/index.d.ts.map +1 -1
  34. package/dist/types/optimization-heatmap-widget.d.ts +45 -0
  35. package/dist/types/optimization-heatmap-widget.d.ts.map +1 -0
  36. package/dist/types/option-smile-widget.d.ts +39 -0
  37. package/dist/types/option-smile-widget.d.ts.map +1 -0
  38. package/dist/types/pnl-curve.d.ts +3 -0
  39. package/dist/types/pnl-curve.d.ts.map +1 -1
  40. package/dist/types/surface-grid.d.ts +64 -0
  41. package/dist/types/surface-grid.d.ts.map +1 -0
  42. package/dist/types/surface-widget.d.ts +64 -0
  43. package/dist/types/surface-widget.d.ts.map +1 -0
  44. package/package.json +28 -2
  45. package/screenshots/equity.png +0 -0
  46. package/screenshots/optimization-surface.png +0 -0
  47. package/screenshots/optimization.png +0 -0
  48. package/screenshots/option-smile.png +0 -0
  49. package/screenshots/panels.jpg +0 -0
  50. package/src/chart-engine.global.ts +64 -0
  51. package/src/chart-engine.ts +29 -0
  52. package/src/control-types.ts +4 -0
  53. package/src/equity-widget.ts +289 -0
  54. package/src/heatmap-grid.ts +405 -0
  55. package/src/index.ts +46 -0
  56. package/src/optimization-heatmap-widget.ts +347 -0
  57. package/src/option-smile-widget.ts +281 -0
  58. package/src/pnl-curve.ts +13 -1
  59. package/src/surface-grid.ts +410 -0
  60. package/src/surface-widget.ts +457 -0
  61. package/styles/trading-controls.css +281 -0
  62. package/translation-keys.json +14 -1
@@ -0,0 +1,347 @@
1
+ // Optimisation heatmap - multi-instance.
2
+ //
3
+ // One metric over two parameters: an axis of discrete values across, another up, a cell per pair
4
+ // of them, coloured by what that pair measured. The panel does not know what an optimisation is -
5
+ // a heatmap of a metric over two parameters is the same object whatever produced it - so the
6
+ // pairs are handed in and the two axis names come with them.
7
+ //
8
+ // The map is a <canvas>, the one surface a class name cannot reach: its geometry comes out of
9
+ // `heatmap-grid.ts` as numbers and its colours out of the host's `canvasPalette()`, so nothing
10
+ // here is painted from a palette this package chose. The tooltip is DOM, because it is text.
11
+ //
12
+ // Two things are drawn rather than tabulated and are worth stating. A cell carries no printed
13
+ // number: at the size a forty by forty sweep leaves a cell, digits are unreadable, and reading
14
+ // colour at that size is the entire reason to draw the map. And a pair nobody ran is struck
15
+ // through rather than left blank, because an unrun pair and a pair that measured zero are
16
+ // different facts that a scale with zero at its neutral point would otherwise paint the same.
17
+ import { formatStatistic } from './statistics-widget.js';
18
+ import { makeElement, makeIconButton, makePanelId, makePanelRoot } from './dom.js';
19
+ import { ControlTypes } from './control-types.js';
20
+ import { TradingHost, assertHost } from './trading-host.js';
21
+ import { hitHeatmap, layoutHeatmap } from './heatmap-grid.js';
22
+ import type { HeatCell, HeatCellShape, HeatDirection, HeatLayout, HeatRect } from './heatmap-grid.js';
23
+
24
+ /// One map: the pairs, what they measured, and the three names a reader needs to know what is
25
+ /// on the screen. The labels arrive worded - they are the consumer's own vocabulary for its
26
+ /// parameters and its metric, the way a statistic reaches the statistics panel already named.
27
+ export interface HeatmapData {
28
+ xLabel: string;
29
+ yLabel: string;
30
+ metricLabel: string;
31
+ /// Which way is better. Required, and required for a reason: without it the same map of
32
+ /// drawdowns would paint its worst corner in the winning colour.
33
+ betterWhen: HeatDirection;
34
+ cells: HeatCell[];
35
+ }
36
+
37
+ /// The panel needs nothing beyond the host port. There is nothing on a map to act on: a cell is
38
+ /// the mean of the runs at one pair rather than a run, so there is no run for a click to open.
39
+ export interface OptimizationHeatmapDeps {
40
+ host: TradingHost;
41
+ }
42
+
43
+ // Opacity, not colour. Every hue below is the host's `canvasPalette`; how solid a thing is drawn
44
+ // is the map's own business, and keeping the two apart is what lets one palette serve a light
45
+ // theme and a dark one without the package knowing which it is in.
46
+ //
47
+ // The ground is drawn under every measured cell so that a cell sitting exactly on the anchor -
48
+ // which takes no tint at all - is still visibly a cell. That is also what lets the tint itself
49
+ // go all the way down to nothing without a floor: neutral reads as the ground, and a pair that
50
+ // was never run has no ground under it.
51
+ const GROUND_ALPHA = 0.1;
52
+ const GAP_ALPHA = 0.25;
53
+ const LABEL_ALPHA = 0.65;
54
+ const BEST_WIDTH = 2;
55
+ // Gap between the cursor and the tooltip, and between the tooltip and the edge it is clamped
56
+ // against.
57
+ const TOOLTIP_OFFSET = 12;
58
+ const TOOLTIP_MARGIN = 4;
59
+
60
+ export class OptimizationHeatmapWidget {
61
+ static TYPE = ControlTypes.OptimizationHeatmap;
62
+
63
+ rootEl: HTMLElement;
64
+ canvasEl: HTMLCanvasElement | null;
65
+ // `//` rather than `///` from here down - see the note in positions-widget.
66
+ _host: TradingHost;
67
+ _metricEl: HTMLElement | null;
68
+ _emptyEl: HTMLElement | null;
69
+ _tooltipEl: HTMLElement | null;
70
+ _closeBtn: HTMLElement | null;
71
+ _ctx: CanvasRenderingContext2D | null;
72
+ _data: HeatmapData | null;
73
+ // Rebuilt on every paint: where each cell landed and what it stands for. Hover reads it
74
+ // rather than the data, so a cursor and a pixel agree about which pair is under it.
75
+ _layout: HeatLayout | null;
76
+ _size: { width: number; height: number } | null;
77
+ _resizeObserver: ResizeObserver | null;
78
+
79
+ static create(hostEl: HTMLElement, state: Record<string, unknown>, deps: OptimizationHeatmapDeps): OptimizationHeatmapWidget {
80
+ // Assert before building: the markup below is localized through the host, so a missing
81
+ // host has to fail here rather than render a panel captioned with raw English keys.
82
+ const host = assertHost(deps?.host, 'OptimizationHeatmapWidget');
83
+ const root = OptimizationHeatmapWidget._buildRoot(host);
84
+ root.id = makePanelId(OptimizationHeatmapWidget.TYPE);
85
+ hostEl.appendChild(root);
86
+ return new OptimizationHeatmapWidget(root, state || {}, deps);
87
+ }
88
+
89
+ // The panel's markup. The metric's name sits in the header rather than on the canvas: it is
90
+ // the caption the drawn legend is read against, and putting it in the chrome costs the map
91
+ // no pixels and leaves the text selectable and sized by the stylesheet.
92
+ static _buildRoot(host: TradingHost): HTMLElement {
93
+ const title = host.t('OptimizationHeatmap');
94
+ return makePanelRoot('optimization-heatmap-panel', title, [
95
+ makeElement('div', 'panel-header', {}, [
96
+ makeElement('span', '', {}, [title]),
97
+ makeElement('span', 'heatmap-metric', {}, []),
98
+ makeIconButton('bt-icon-btn bt-icon-cancel panel-close-btn', host.t('ClosePanel'), 'bi-x', { type: 'button' }),
99
+ ]),
100
+ makeElement('div', 'panel-body', {}, [
101
+ makeElement('canvas', 'heatmap-canvas', { role: 'img', 'aria-label': host.t('OptimizationHeatmapChart') }, []),
102
+ makeElement('div', 'heatmap-empty', { hidden: '' }, [host.t('NoOptimizationResults')]),
103
+ makeElement('div', 'heatmap-tooltip', { role: 'tooltip', hidden: '' }, []),
104
+ ]),
105
+ ]);
106
+ }
107
+
108
+ constructor(rootEl: HTMLElement, _state: Record<string, unknown>, deps: OptimizationHeatmapDeps) {
109
+ this._host = assertHost(deps?.host, 'OptimizationHeatmapWidget');
110
+
111
+ this.rootEl = rootEl;
112
+ this.canvasEl = this.rootEl.querySelector('.heatmap-canvas');
113
+ this._metricEl = this.rootEl.querySelector('.heatmap-metric');
114
+ this._emptyEl = this.rootEl.querySelector('.heatmap-empty');
115
+ this._tooltipEl = this.rootEl.querySelector('.heatmap-tooltip');
116
+ this._closeBtn = this.rootEl.querySelector('.panel-close-btn');
117
+ this._ctx = this.canvasEl?.getContext('2d') ?? null;
118
+ this._data = null;
119
+ this._layout = null;
120
+ this._size = null;
121
+ this._resizeObserver = null;
122
+
123
+ this._closeBtn?.addEventListener('click', (e) => { e.preventDefault(); this._host.close(); });
124
+ this._bindHover();
125
+ this._setEmpty(true);
126
+
127
+ if (this.canvasEl && typeof ResizeObserver === 'function') {
128
+ this._resizeObserver = new ResizeObserver(() => this._render());
129
+ this._resizeObserver.observe(this.canvasEl);
130
+ }
131
+
132
+ this._host.register(this);
133
+ }
134
+
135
+ dispose(): void {
136
+ try { this._resizeObserver?.disconnect(); } catch { /* already torn down */ }
137
+ this._host.unregister(this);
138
+ try { this.rootEl.remove(); } catch { /* already detached */ }
139
+ }
140
+
141
+ /// Show this map. The whole of it at once: a pair that has dropped out of the set has stopped
142
+ /// existing, and leaving its cell behind would report a run that is no longer in the report.
143
+ update(data: HeatmapData): void {
144
+ this._data = data;
145
+ if (this._metricEl !== null) this._metricEl.textContent = data.metricLabel;
146
+ this._hideTooltip();
147
+ this._render();
148
+ }
149
+
150
+ // The canvas in CSS pixels, and its backing store in device pixels. Without the second the
151
+ // map is drawn at a third of the resolution the screen has, and a lattice of hairlines is
152
+ // exactly the drawing that shows it.
153
+ _sizeCanvas(): void {
154
+ const canvas = this.canvasEl;
155
+ if (!canvas) return;
156
+ const rect = canvas.getBoundingClientRect();
157
+ const ratio = typeof devicePixelRatio === 'number' && devicePixelRatio > 0 ? devicePixelRatio : 1;
158
+ const width = Math.max(1, Math.floor(rect.width));
159
+ const height = Math.max(1, Math.floor(rect.height));
160
+ if (canvas.width !== width * ratio || canvas.height !== height * ratio) {
161
+ canvas.width = width * ratio;
162
+ canvas.height = height * ratio;
163
+ // Everything below draws in CSS pixels, which is also the space a mouse event
164
+ // arrives in - so the hit test needs no conversion of its own.
165
+ this._ctx?.setTransform(ratio, 0, 0, ratio, 0, 0);
166
+ }
167
+ this._size = { width, height };
168
+ }
169
+
170
+ _render(): void {
171
+ const ctx = this._ctx;
172
+ if (ctx === null) return;
173
+ this._sizeCanvas();
174
+ const size = this._size;
175
+ if (size === null) return;
176
+
177
+ ctx.clearRect(0, 0, size.width, size.height);
178
+ this._layout = null;
179
+
180
+ const data = this._data;
181
+ if (data === null) { this._setEmpty(true); return; }
182
+
183
+ const layout = layoutHeatmap({
184
+ width: size.width,
185
+ height: size.height,
186
+ cells: data.cells,
187
+ betterWhen: data.betterWhen,
188
+ xLabel: data.xLabel,
189
+ yLabel: data.yLabel,
190
+ });
191
+ this._setEmpty(layout === null);
192
+ if (layout === null) return;
193
+ this._layout = layout;
194
+
195
+ const palette = this._host.presentation.canvasPalette();
196
+ ctx.font = palette.font;
197
+ ctx.lineWidth = 1;
198
+
199
+ for (const shape of layout.cells) this._paintTint(ctx, shape.rect, shape.tint, palette.grid, palette.up, palette.down);
200
+
201
+ // A pair nobody ran, struck through. One diagonal rather than a fill of any kind: no
202
+ // amount of colour can say "not measured" on a map whose colours are all measurements.
203
+ ctx.globalAlpha = GAP_ALPHA;
204
+ ctx.strokeStyle = palette.grid;
205
+ for (const gap of layout.gaps) {
206
+ ctx.beginPath();
207
+ ctx.moveTo(gap.rect.x, gap.rect.y + gap.rect.height);
208
+ ctx.lineTo(gap.rect.x + gap.rect.width, gap.rect.y);
209
+ ctx.stroke();
210
+ }
211
+
212
+ // Last, so it sits over its own fill. In the grid colour because that is the only
213
+ // non-directional colour the palette carries, and an outline in either direction colour
214
+ // would vanish on half the cells it might land on.
215
+ const best = layout.cells.find(shape => shape.best);
216
+ if (best !== undefined) {
217
+ ctx.globalAlpha = 1;
218
+ ctx.strokeStyle = palette.grid;
219
+ ctx.lineWidth = BEST_WIDTH;
220
+ OptimizationHeatmapWidget._outline(ctx, best.rect, BEST_WIDTH / 2);
221
+ ctx.lineWidth = 1;
222
+ }
223
+
224
+ // The key, drawn out of the same two colours the map is: a legend in CSS would read the
225
+ // page's own tokens, and a host whose canvas palette comes from anywhere else would then
226
+ // explain its map in colours the map does not use.
227
+ for (const step of layout.legend.steps)
228
+ this._paintTint(ctx, step.rect, step.tint, palette.grid, palette.up, palette.down);
229
+
230
+ ctx.globalAlpha = LABEL_ALPHA;
231
+ ctx.fillStyle = palette.grid;
232
+
233
+ ctx.textBaseline = 'top';
234
+ ctx.textAlign = 'center';
235
+ for (const tick of layout.xTicks) ctx.fillText(tick.text, tick.x, tick.y);
236
+ ctx.fillText(layout.xTitle.text, layout.xTitle.x, layout.xTitle.y);
237
+ ctx.fillText(formatStatistic(layout.legend.anchor.value), layout.legend.anchor.x, layout.legend.anchor.y);
238
+
239
+ ctx.textAlign = 'left';
240
+ ctx.fillText(layout.yTitle.text, layout.yTitle.x, layout.yTitle.y);
241
+ ctx.fillText(formatStatistic(layout.legend.low.value), layout.legend.low.x, layout.legend.low.y);
242
+
243
+ ctx.textAlign = 'right';
244
+ ctx.fillText(formatStatistic(layout.legend.high.value), layout.legend.high.x, layout.legend.high.y);
245
+
246
+ ctx.textBaseline = 'middle';
247
+ for (const tick of layout.yTicks) ctx.fillText(tick.text, tick.x, tick.y);
248
+
249
+ ctx.globalAlpha = 1;
250
+ }
251
+
252
+ // The ground, then as much of the direction colour as the cell earned. Two fills rather than
253
+ // one blended colour: blending would need a background this control is not allowed to know.
254
+ _paintTint(ctx: CanvasRenderingContext2D, rect: HeatRect, tint: number, ground: string, up: string, down: string): void {
255
+ ctx.globalAlpha = GROUND_ALPHA;
256
+ ctx.fillStyle = ground;
257
+ ctx.fillRect(rect.x, rect.y, rect.width, rect.height);
258
+ if (tint === 0) return;
259
+
260
+ ctx.globalAlpha = Math.abs(tint);
261
+ ctx.fillStyle = tint > 0 ? up : down;
262
+ ctx.fillRect(rect.x, rect.y, rect.width, rect.height);
263
+ }
264
+
265
+ static _outline(ctx: CanvasRenderingContext2D, rect: HeatRect, inset: number): void {
266
+ const left = rect.x + inset;
267
+ const top = rect.y + inset;
268
+ const right = rect.x + rect.width - inset;
269
+ const bottom = rect.y + rect.height - inset;
270
+ ctx.beginPath();
271
+ ctx.moveTo(left, top);
272
+ ctx.lineTo(right, top);
273
+ ctx.lineTo(right, bottom);
274
+ ctx.lineTo(left, bottom);
275
+ ctx.closePath();
276
+ ctx.stroke();
277
+ }
278
+
279
+ _setEmpty(empty: boolean): void {
280
+ if (this._emptyEl === null) return;
281
+ if (empty) this._emptyEl.removeAttribute('hidden');
282
+ else this._emptyEl.setAttribute('hidden', '');
283
+ }
284
+
285
+ _bindHover(): void {
286
+ const canvas = this.canvasEl;
287
+ if (!canvas) return;
288
+ canvas.addEventListener('mousemove', (e: MouseEvent) => {
289
+ const layout = this._layout;
290
+ if (layout === null) { this._hideTooltip(); return; }
291
+ const rect = canvas.getBoundingClientRect();
292
+ const x = e.clientX - rect.left;
293
+ const y = e.clientY - rect.top;
294
+ const hit = hitHeatmap(layout, x, y);
295
+ // A pair nobody ran says nothing, so it says nothing: a tooltip reading "no data"
296
+ // over a cell that is visibly struck through is the same statement twice.
297
+ if (hit !== null) this._showTooltip(hit, x, y);
298
+ else this._hideTooltip();
299
+ });
300
+ canvas.addEventListener('mouseleave', () => this._hideTooltip());
301
+ }
302
+
303
+ _showTooltip(shape: HeatCellShape, x: number, y: number): void {
304
+ const tooltip = this._tooltipEl;
305
+ const canvas = this.canvasEl;
306
+ const data = this._data;
307
+ if (!tooltip || !canvas || data === null) return;
308
+
309
+ const lines: HTMLElement[] = [
310
+ this._tooltipLine(data.xLabel, shape.bucket.x),
311
+ this._tooltipLine(data.yLabel, shape.bucket.y),
312
+ this._tooltipLine(data.metricLabel, formatStatistic(shape.bucket.value)),
313
+ ];
314
+ // How many runs the figure is the mean of, and only when it is a mean of more than one.
315
+ // A count of 1 on every cell is a column of noise; a count of 5 on one of them is the
316
+ // difference between a result and a coincidence.
317
+ if (shape.bucket.count > 1)
318
+ lines.push(this._tooltipLine(this._host.t('Runs'), String(shape.bucket.count)));
319
+ if (shape.best)
320
+ lines.push(makeElement('div', 'heatmap-tt-row heatmap-tt-best', {}, [this._host.t('Best')]));
321
+ tooltip.replaceChildren(...lines);
322
+
323
+ // Measured, then placed: the size is only known once it is showing, and it is clamped
324
+ // inside the canvas so a cell near the right or bottom edge does not push its own
325
+ // tooltip out of view.
326
+ tooltip.removeAttribute('hidden');
327
+ const canvasRect = canvas.getBoundingClientRect();
328
+ const parentRect = tooltip.offsetParent?.getBoundingClientRect() ?? canvasRect;
329
+ const originX = canvasRect.left - parentRect.left;
330
+ const originY = canvasRect.top - parentRect.top;
331
+ const maxX = originX + canvasRect.width - tooltip.offsetWidth - TOOLTIP_MARGIN;
332
+ const maxY = originY + canvasRect.height - tooltip.offsetHeight - TOOLTIP_MARGIN;
333
+ tooltip.style.left = `${Math.max(0, Math.min(originX + x + TOOLTIP_OFFSET, maxX))}px`;
334
+ tooltip.style.top = `${Math.max(0, Math.min(originY + y + TOOLTIP_OFFSET, maxY))}px`;
335
+ }
336
+
337
+ _tooltipLine(label: string, value: string): HTMLElement {
338
+ return makeElement('div', 'heatmap-tt-row', {}, [
339
+ makeElement('span', 'heatmap-tt-label', {}, [label]),
340
+ makeElement('span', 'heatmap-tt-value', {}, [value]),
341
+ ]);
342
+ }
343
+
344
+ _hideTooltip(): void {
345
+ this._tooltipEl?.setAttribute('hidden', '');
346
+ }
347
+ }
@@ -0,0 +1,281 @@
1
+ // Option smile — multi-instance.
2
+ //
3
+ // One expiry's implied volatility against strike, call side and put side as two curves on one
4
+ // scale, drawn by @stocksharp/chart.
5
+ //
6
+ // The engine is a time-series engine and this axis is a ladder of strikes, which looked at first
7
+ // like a reason to draw the chart by hand. It is not: the axis carries numbers, and what turns
8
+ // them into dates is `timeScale.formatter` - one function shared by the tick labels and the
9
+ // crosshair label. Given a formatter that words a number as a strike, the axis is a strike axis,
10
+ // and the crosshair, the legend readout, the zoom and the pan come with it rather than being
11
+ // written again here.
12
+ //
13
+ // `mode: 'ordinal'` on top of that, because a listed chain is evenly spaced by listing rather
14
+ // than by the gaps between its numbers: a venue that lists 67000, 67250 and then 68000 means
15
+ // three rungs, not a hole.
16
+ import { formatPrice } from './formatters.js';
17
+ import { makeElement, makeIconButton, makePanelId, makePanelRoot } from './dom.js';
18
+ import { ControlTypes } from './control-types.js';
19
+ import { TradingHost, assertHost } from './trading-host.js';
20
+ import type { OptionChainContext, OptionSide, OptionStrike } from './option-desk-widget.js';
21
+ import {
22
+ CrosshairMode, LineSeries, createChart,
23
+ type CrosshairEvent, type IChartApi, type ISeriesApi, type LineData, type Time,
24
+ } from './chart-engine.js';
25
+
26
+ /// What the panel needs beyond the host port. Nothing: a smile is read, not acted on.
27
+ export interface OptionSmileDeps {
28
+ host: TradingHost;
29
+ }
30
+
31
+ const LINE_WIDTH = 2;
32
+
33
+ /// The volatility a side is drawn at: what it last traded at, or the middle of its quote when it
34
+ /// has not traded. Null when neither is known - a strike nobody has quoted is a gap in the curve,
35
+ /// and a line drawn through it invents a quote nobody made.
36
+ export function sideVolatility(side: OptionSide | undefined): number | null {
37
+ if (side === undefined || side === null) return null;
38
+
39
+ const last = side.ivLast;
40
+ if (typeof last === 'number' && isFinite(last) && last > 0) return last;
41
+
42
+ const bid = side.ivBid;
43
+ const ask = side.ivAsk;
44
+ const quoted = [bid, ask].filter((v): v is number => typeof v === 'number' && isFinite(v) && v > 0);
45
+ if (quoted.length === 0) return null;
46
+ return quoted.reduce((sum, v) => sum + v, 0) / quoted.length;
47
+ }
48
+
49
+ /// The chain in the order it is drawn: by strike, lowest first, whatever order it arrived in.
50
+ export function sortedChain(strikes: readonly OptionStrike[]): OptionStrike[] {
51
+ return [...strikes]
52
+ .filter(row => row !== null && row !== undefined && isFinite(row.strike))
53
+ .sort((a, b) => a.strike - b.strike);
54
+ }
55
+
56
+ /// One side as a series, and the strikes it was drawn at.
57
+ ///
58
+ /// The x value is the strike itself rather than an index: the axis words it back through the
59
+ /// formatter, so the number on the wire and the number on the label are the same one and no
60
+ /// lookup can put them out of step.
61
+ export function toSmileSeries(chain: readonly OptionStrike[], put: boolean): LineData[] {
62
+ const out: LineData[] = [];
63
+ for (const row of chain) {
64
+ const volatility = sideVolatility(put ? row.put : row.call);
65
+ // Whitespace rather than a point: the engine keeps the rung on the axis and leaves the
66
+ // line broken across it, which is what a strike quoted on one side only looks like.
67
+ if (volatility === null) out.push({ time: row.strike as Time } as LineData);
68
+ else out.push({ time: row.strike as Time, value: volatility * 100 });
69
+ }
70
+ return out;
71
+ }
72
+
73
+ export class OptionSmileWidget {
74
+ static TYPE = ControlTypes.OptionSmile;
75
+
76
+ rootEl: HTMLElement;
77
+ // `//` rather than `///` from here down — see the note in positions-widget.
78
+ _host: TradingHost;
79
+ _closeBtn: HTMLElement | null;
80
+ _resetBtn: HTMLElement | null;
81
+ _emptyEl: HTMLElement | null;
82
+ _chartEl: HTMLElement | null;
83
+ _spotEl: HTMLElement | null;
84
+ _hoverEl: HTMLElement | null;
85
+ _chart: IChartApi | null;
86
+ _call: ISeriesApi<LineData> | null;
87
+ _put: ISeriesApi<LineData> | null;
88
+ _strikes: OptionStrike[];
89
+ _context: OptionChainContext;
90
+ _resizeObserver: ResizeObserver | null;
91
+
92
+ static create(hostEl: HTMLElement, state: Record<string, unknown>, deps: OptionSmileDeps): OptionSmileWidget {
93
+ const host = assertHost(deps?.host, 'OptionSmileWidget');
94
+ const root = OptionSmileWidget._buildRoot(host);
95
+ root.id = makePanelId(OptionSmileWidget.TYPE);
96
+ hostEl.appendChild(root);
97
+ return new OptionSmileWidget(root, state || {}, deps);
98
+ }
99
+
100
+ static _buildRoot(host: TradingHost): HTMLElement {
101
+ const title = host.t('OptionSmile');
102
+ return makePanelRoot('option-smile-panel', title, [
103
+ makeElement('div', 'panel-header', {}, [
104
+ makeElement('span', '', {}, [title]),
105
+ makeIconButton('bt-icon-btn option-smile-reset-btn', host.t('ResetView'), 'bi-arrow-clockwise', { type: 'button' }),
106
+ makeIconButton('bt-icon-btn bt-icon-cancel panel-close-btn', host.t('ClosePanel'), 'bi-x', { type: 'button' }),
107
+ ]),
108
+ makeElement('div', 'panel-body', {}, [
109
+ makeElement('div', 'option-smile-legend', {}, [
110
+ makeElement('span', 'option-smile-axis', {}, [host.t('ImpliedVolatility')]),
111
+ makeElement('span', 'option-smile-key', {}, [
112
+ makeElement('span', 'option-smile-dot option-smile-dot-call', {}, []),
113
+ host.t('Call'),
114
+ ]),
115
+ makeElement('span', 'option-smile-key', {}, [
116
+ makeElement('span', 'option-smile-dot option-smile-dot-put', {}, []),
117
+ host.t('Put'),
118
+ ]),
119
+ makeElement('span', 'option-smile-spot', {}, []),
120
+ ]),
121
+ makeElement('div', 'option-smile-chart', { role: 'img', 'aria-label': host.t('OptionChain') }, [
122
+ // Over the chart, not in the panel header: a reading about the point under the
123
+ // pointer belongs beside that point, and a host that lifts panel headers into a
124
+ // tab strip would otherwise write it into a tab title.
125
+ makeElement('div', 'option-smile-hover', {}, []),
126
+ makeElement('div', 'option-smile-empty', {}, [host.t('NoOptions')]),
127
+ ]),
128
+ ]),
129
+ ]);
130
+ }
131
+
132
+ constructor(rootEl: HTMLElement, _state: Record<string, unknown>, deps: OptionSmileDeps) {
133
+ this._host = assertHost(deps?.host, 'OptionSmileWidget');
134
+
135
+ this.rootEl = rootEl;
136
+ this._closeBtn = this.rootEl.querySelector('.panel-close-btn');
137
+ this._resetBtn = this.rootEl.querySelector('.option-smile-reset-btn');
138
+ this._emptyEl = this.rootEl.querySelector('.option-smile-empty');
139
+ this._chartEl = this.rootEl.querySelector('.option-smile-chart');
140
+ this._spotEl = this.rootEl.querySelector('.option-smile-spot');
141
+ this._hoverEl = this.rootEl.querySelector('.option-smile-hover');
142
+ this._chart = null;
143
+ this._call = null;
144
+ this._put = null;
145
+ this._strikes = [];
146
+ this._context = {};
147
+ this._resizeObserver = null;
148
+
149
+ this._closeBtn?.addEventListener('click', (e) => { e.preventDefault(); this._host.close(); });
150
+ this._resetBtn?.addEventListener('click', (e) => { e.preventDefault(); this.resetZoom(); });
151
+
152
+ if (this._chartEl !== null && typeof ResizeObserver !== 'undefined') {
153
+ this._resizeObserver = new ResizeObserver(() => this._fit());
154
+ this._resizeObserver.observe(this._chartEl);
155
+ }
156
+
157
+ this._render();
158
+ this._host.register(this);
159
+ }
160
+
161
+ dispose(): void {
162
+ try { this._resizeObserver?.disconnect(); } catch { /* already torn down */ }
163
+ this._resizeObserver = null;
164
+ try { this._chart?.remove(); } catch { /* already gone */ }
165
+ this._chart = null;
166
+ this._call = null;
167
+ this._put = null;
168
+ this._host.unregister(this);
169
+ try { this.rootEl.remove(); } catch { /* already detached */ }
170
+ }
171
+
172
+ /// Show this chain, priced against this context.
173
+ ///
174
+ /// The desk's two arguments unchanged, and for the same reason it takes them together: they
175
+ /// are one observation. A smile marked with a spot the curves never saw is two moments.
176
+ update(strikes: OptionStrike[], context: OptionChainContext = {}): void {
177
+ this._strikes = strikes || [];
178
+ this._context = context || {};
179
+ this._render();
180
+ }
181
+
182
+ /// Show the whole chain again, after a zoom.
183
+ resetZoom(): void {
184
+ try { this._chart?.timeScale().fitContent(); } catch { /* no chart yet */ }
185
+ }
186
+
187
+ /// The engine, for a host that wants to add to this chart - a second expiry, a marker.
188
+ chart(): IChartApi | null {
189
+ return this._chart;
190
+ }
191
+
192
+ _ensureChart(): boolean {
193
+ if (this._chart !== null) return true;
194
+ if (this._chartEl === null) return false;
195
+
196
+ const palette = this._host.presentation.canvasPalette();
197
+ this._chart = createChart(this._chartEl, {
198
+ layout: {
199
+ background: { type: 'solid', color: 'transparent' },
200
+ textColor: palette.grid,
201
+ fontFamily: palette.font,
202
+ fontSize: 11,
203
+ attributionLogo: false,
204
+ },
205
+ grid: { vertLines: { color: palette.grid }, horzLines: { color: palette.grid } },
206
+ crosshair: { mode: CrosshairMode.Normal },
207
+ rightPriceScale: { borderColor: palette.grid },
208
+ timeScale: {
209
+ borderColor: palette.grid,
210
+ // Evenly spaced by listing, and worded as strikes: the axis carries the strike
211
+ // itself, so the label and the value can never drift apart.
212
+ mode: 'ordinal',
213
+ formatter: (value: Time) => formatPrice(Number(value)),
214
+ },
215
+ });
216
+
217
+ this._call = this._chart.addSeries(LineSeries, { lineWidth: LINE_WIDTH, color: palette.up });
218
+ this._put = this._chart.addSeries(LineSeries, { lineWidth: LINE_WIDTH, color: palette.down });
219
+ this._chart.subscribeCrosshairMove((param) => this._renderHover(param));
220
+ return true;
221
+ }
222
+
223
+ _render(): void {
224
+ const chain = sortedChain(this._strikes);
225
+ const quoted = chain.some(row =>
226
+ sideVolatility(row.call) !== null || sideVolatility(row.put) !== null);
227
+
228
+ if (this._emptyEl !== null) this._emptyEl.hidden = quoted;
229
+ this._renderSpot();
230
+ if (!quoted) return;
231
+ if (!this._ensureChart() || this._call === null || this._put === null) return;
232
+
233
+ this._call.setData(toSmileSeries(chain, false));
234
+ this._put.setData(toSmileSeries(chain, true));
235
+ this._fit();
236
+ }
237
+
238
+ _fit(): void {
239
+ if (this._chart === null || this._chartEl === null) return;
240
+ const rect = this._chartEl.getBoundingClientRect();
241
+ if (rect.width <= 0 || rect.height <= 0) return;
242
+ try {
243
+ this._chart.resize(rect.width, rect.height);
244
+ } catch { /* the engine is between frames */ }
245
+ }
246
+
247
+ // Where the money is. Not a line on the chart: an ordinal axis has a rung per listed strike
248
+ // and the spot is between two of them, so it is stated rather than drawn at a place the
249
+ // ladder does not have.
250
+ _renderSpot(): void {
251
+ const el = this._spotEl;
252
+ if (el === null) return;
253
+
254
+ const spot = this._context.assetPrice;
255
+ if (typeof spot !== 'number' || !isFinite(spot)) {
256
+ el.textContent = '';
257
+ return;
258
+ }
259
+ el.textContent = `${this._host.t('Underlying')} ${formatPrice(spot)}`;
260
+ }
261
+
262
+ // What the pointer is over: the strike and both sides at it. Both, because a smile is read by
263
+ // the distance between the two curves - a readout naming one of them answers half of it.
264
+ _renderHover(param: CrosshairEvent): void {
265
+ const el = this._hoverEl;
266
+ if (el === null) return;
267
+
268
+ if (param.time === null) {
269
+ el.textContent = '';
270
+ return;
271
+ }
272
+
273
+ const at = (series: ISeriesApi<LineData> | null): string => {
274
+ const point = series === null ? undefined : param.seriesData.get(series);
275
+ const value = (point as { value?: number } | undefined)?.value;
276
+ return typeof value === 'number' && isFinite(value) ? `${value.toFixed(2)}%` : '--';
277
+ };
278
+
279
+ el.textContent = `${formatPrice(Number(param.time))} ${at(this._call)} / ${at(this._put)}`;
280
+ }
281
+ }
package/src/pnl-curve.ts CHANGED
@@ -32,6 +32,14 @@ export interface PnlCurve {
32
32
  /// The value range the box covers, zero included.
33
33
  min: number;
34
34
  max: number;
35
+ /// The stretch of time the box covers. Compression keeps the run's first and last samples
36
+ /// exactly, so these are where it started and where it stands - which is what lets a panel
37
+ /// wide enough for a time axis date both ends without laying the run out a second time.
38
+ from: number;
39
+ to: number;
40
+ /// The value the run ended at. `positive` is this figure's sign; a panel with room to print
41
+ /// a number wants the figure.
42
+ last: number;
35
43
  /// Whether the run ended at or above where it started. What the curve is coloured by - and
36
44
  /// the last value, not the highest: a run that peaked and gave it all back is a loss.
37
45
  positive: boolean;
@@ -127,6 +135,7 @@ export function pnlCurve(points: readonly PnlPoint[], box: PnlBox): PnlCurve | n
127
135
 
128
136
  const curve = shown.map(p => [x(p.time), y(p.value)] as [number, number]);
129
137
  const zeroY = y(0);
138
+ const last = shown[shown.length - 1].value;
130
139
 
131
140
  return {
132
141
  points: curve,
@@ -136,7 +145,10 @@ export function pnlCurve(points: readonly PnlPoint[], box: PnlBox): PnlCurve | n
136
145
  zeroY,
137
146
  min,
138
147
  max,
139
- positive: shown[shown.length - 1].value >= 0,
148
+ from: firstTime,
149
+ to: lastTime,
150
+ last,
151
+ positive: last >= 0,
140
152
  };
141
153
  }
142
154