@stocksharp/trading-controls 1.2.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 (99) hide show
  1. package/README.md +204 -17
  2. package/dist/esm/black-scholes.js +147 -0
  3. package/dist/esm/black-scholes.js.map +1 -0
  4. package/dist/esm/chart-engine.js +15 -0
  5. package/dist/esm/chart-engine.js.map +1 -0
  6. package/dist/esm/control-types.js +8 -0
  7. package/dist/esm/control-types.js.map +1 -1
  8. package/dist/esm/equity-widget.js +261 -0
  9. package/dist/esm/equity-widget.js.map +1 -0
  10. package/dist/esm/heatmap-grid.js +271 -0
  11. package/dist/esm/heatmap-grid.js.map +1 -0
  12. package/dist/esm/index.js +37 -0
  13. package/dist/esm/index.js.map +1 -1
  14. package/dist/esm/log-monitor-widget.js +265 -0
  15. package/dist/esm/log-monitor-widget.js.map +1 -0
  16. package/dist/esm/log-tree.js +96 -0
  17. package/dist/esm/log-tree.js.map +1 -0
  18. package/dist/esm/optimization-heatmap-widget.js +303 -0
  19. package/dist/esm/optimization-heatmap-widget.js.map +1 -0
  20. package/dist/esm/option-desk-widget.js +322 -0
  21. package/dist/esm/option-desk-widget.js.map +1 -0
  22. package/dist/esm/option-smile-widget.js +252 -0
  23. package/dist/esm/option-smile-widget.js.map +1 -0
  24. package/dist/esm/pnl-curve.js +133 -0
  25. package/dist/esm/pnl-curve.js.map +1 -0
  26. package/dist/esm/statistics-widget.js +194 -0
  27. package/dist/esm/statistics-widget.js.map +1 -0
  28. package/dist/esm/strategies-widget.js +348 -0
  29. package/dist/esm/strategies-widget.js.map +1 -0
  30. package/dist/esm/surface-grid.js +282 -0
  31. package/dist/esm/surface-grid.js.map +1 -0
  32. package/dist/esm/surface-widget.js +379 -0
  33. package/dist/esm/surface-widget.js.map +1 -0
  34. package/dist/sstradingcontrols.js +2982 -295
  35. package/dist/sstradingcontrols.js.map +4 -4
  36. package/dist/types/black-scholes.d.ts +28 -0
  37. package/dist/types/black-scholes.d.ts.map +1 -0
  38. package/dist/types/chart-engine.d.ts +3 -0
  39. package/dist/types/chart-engine.d.ts.map +1 -0
  40. package/dist/types/control-types.d.ts +8 -0
  41. package/dist/types/control-types.d.ts.map +1 -1
  42. package/dist/types/equity-widget.d.ts +34 -0
  43. package/dist/types/equity-widget.d.ts.map +1 -0
  44. package/dist/types/heatmap-grid.d.ts +88 -0
  45. package/dist/types/heatmap-grid.d.ts.map +1 -0
  46. package/dist/types/index.d.ts +31 -1
  47. package/dist/types/index.d.ts.map +1 -1
  48. package/dist/types/log-monitor-widget.d.ts +42 -0
  49. package/dist/types/log-monitor-widget.d.ts.map +1 -0
  50. package/dist/types/log-tree.d.ts +34 -0
  51. package/dist/types/log-tree.d.ts.map +1 -0
  52. package/dist/types/optimization-heatmap-widget.d.ts +45 -0
  53. package/dist/types/optimization-heatmap-widget.d.ts.map +1 -0
  54. package/dist/types/option-desk-widget.d.ts +68 -0
  55. package/dist/types/option-desk-widget.d.ts.map +1 -0
  56. package/dist/types/option-smile-widget.d.ts +39 -0
  57. package/dist/types/option-smile-widget.d.ts.map +1 -0
  58. package/dist/types/pnl-curve.d.ts +46 -0
  59. package/dist/types/pnl-curve.d.ts.map +1 -0
  60. package/dist/types/statistics-widget.d.ts +29 -0
  61. package/dist/types/statistics-widget.d.ts.map +1 -0
  62. package/dist/types/strategies-widget.d.ts +63 -0
  63. package/dist/types/strategies-widget.d.ts.map +1 -0
  64. package/dist/types/surface-grid.d.ts +64 -0
  65. package/dist/types/surface-grid.d.ts.map +1 -0
  66. package/dist/types/surface-widget.d.ts +64 -0
  67. package/dist/types/surface-widget.d.ts.map +1 -0
  68. package/dist/types/trading-data.d.ts +9 -0
  69. package/dist/types/trading-data.d.ts.map +1 -1
  70. package/package.json +54 -3
  71. package/screenshots/equity.png +0 -0
  72. package/screenshots/log-monitor.png +0 -0
  73. package/screenshots/optimization-surface.png +0 -0
  74. package/screenshots/optimization.png +0 -0
  75. package/screenshots/option-desk.png +0 -0
  76. package/screenshots/option-smile.png +0 -0
  77. package/screenshots/panels.jpg +0 -0
  78. package/screenshots/statistics.png +0 -0
  79. package/screenshots/strategies.png +0 -0
  80. package/src/black-scholes.ts +199 -0
  81. package/src/chart-engine.global.ts +64 -0
  82. package/src/chart-engine.ts +29 -0
  83. package/src/control-types.ts +8 -0
  84. package/src/equity-widget.ts +289 -0
  85. package/src/heatmap-grid.ts +405 -0
  86. package/src/index.ts +87 -0
  87. package/src/log-monitor-widget.ts +312 -0
  88. package/src/log-tree.ts +131 -0
  89. package/src/optimization-heatmap-widget.ts +347 -0
  90. package/src/option-desk-widget.ts +422 -0
  91. package/src/option-smile-widget.ts +281 -0
  92. package/src/pnl-curve.ts +216 -0
  93. package/src/statistics-widget.ts +226 -0
  94. package/src/strategies-widget.ts +435 -0
  95. package/src/surface-grid.ts +410 -0
  96. package/src/surface-widget.ts +457 -0
  97. package/src/trading-data.ts +22 -0
  98. package/styles/trading-controls.css +637 -0
  99. package/translation-keys.json +83 -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
+ }