@stocksharp/trading-controls 1.1.1 → 1.3.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 (77) hide show
  1. package/README.md +95 -16
  2. package/dist/esm/active-orders-widget.js +38 -25
  3. package/dist/esm/active-orders-widget.js.map +1 -1
  4. package/dist/esm/black-scholes.js +147 -0
  5. package/dist/esm/black-scholes.js.map +1 -0
  6. package/dist/esm/control-types.js +4 -0
  7. package/dist/esm/control-types.js.map +1 -1
  8. package/dist/esm/index.js +18 -0
  9. package/dist/esm/index.js.map +1 -1
  10. package/dist/esm/log-monitor-widget.js +265 -0
  11. package/dist/esm/log-monitor-widget.js.map +1 -0
  12. package/dist/esm/log-tree.js +96 -0
  13. package/dist/esm/log-tree.js.map +1 -0
  14. package/dist/esm/option-desk-widget.js +322 -0
  15. package/dist/esm/option-desk-widget.js.map +1 -0
  16. package/dist/esm/pnl-curve.js +129 -0
  17. package/dist/esm/pnl-curve.js.map +1 -0
  18. package/dist/esm/statistics-widget.js +194 -0
  19. package/dist/esm/statistics-widget.js.map +1 -0
  20. package/dist/esm/strategies-widget.js +348 -0
  21. package/dist/esm/strategies-widget.js.map +1 -0
  22. package/dist/esm/trade-history-widget.js +14 -6
  23. package/dist/esm/trade-history-widget.js.map +1 -1
  24. package/dist/esm/tradefeed-widget.js +3 -3
  25. package/dist/esm/tradefeed-widget.js.map +1 -1
  26. package/dist/esm/trading-host.js +1 -0
  27. package/dist/esm/trading-host.js.map +1 -1
  28. package/dist/sstradingcontrols.js +1358 -78
  29. package/dist/sstradingcontrols.js.map +4 -4
  30. package/dist/types/active-orders-widget.d.ts +11 -3
  31. package/dist/types/active-orders-widget.d.ts.map +1 -1
  32. package/dist/types/black-scholes.d.ts +28 -0
  33. package/dist/types/black-scholes.d.ts.map +1 -0
  34. package/dist/types/control-types.d.ts +4 -0
  35. package/dist/types/control-types.d.ts.map +1 -1
  36. package/dist/types/index.d.ts +16 -1
  37. package/dist/types/index.d.ts.map +1 -1
  38. package/dist/types/log-monitor-widget.d.ts +42 -0
  39. package/dist/types/log-monitor-widget.d.ts.map +1 -0
  40. package/dist/types/log-tree.d.ts +34 -0
  41. package/dist/types/log-tree.d.ts.map +1 -0
  42. package/dist/types/option-desk-widget.d.ts +68 -0
  43. package/dist/types/option-desk-widget.d.ts.map +1 -0
  44. package/dist/types/pnl-curve.d.ts +43 -0
  45. package/dist/types/pnl-curve.d.ts.map +1 -0
  46. package/dist/types/statistics-widget.d.ts +29 -0
  47. package/dist/types/statistics-widget.d.ts.map +1 -0
  48. package/dist/types/strategies-widget.d.ts +63 -0
  49. package/dist/types/strategies-widget.d.ts.map +1 -0
  50. package/dist/types/trade-history-widget.d.ts +3 -1
  51. package/dist/types/trade-history-widget.d.ts.map +1 -1
  52. package/dist/types/trading-data.d.ts +9 -0
  53. package/dist/types/trading-data.d.ts.map +1 -1
  54. package/dist/types/trading-host.d.ts +1 -0
  55. package/dist/types/trading-host.d.ts.map +1 -1
  56. package/package.json +27 -2
  57. package/screenshots/log-monitor.png +0 -0
  58. package/screenshots/option-desk.png +0 -0
  59. package/screenshots/panels.jpg +0 -0
  60. package/screenshots/statistics.png +0 -0
  61. package/screenshots/strategies.png +0 -0
  62. package/src/active-orders-widget.ts +49 -25
  63. package/src/black-scholes.ts +199 -0
  64. package/src/control-types.ts +4 -0
  65. package/src/index.ts +41 -0
  66. package/src/log-monitor-widget.ts +312 -0
  67. package/src/log-tree.ts +131 -0
  68. package/src/option-desk-widget.ts +422 -0
  69. package/src/pnl-curve.ts +204 -0
  70. package/src/statistics-widget.ts +226 -0
  71. package/src/strategies-widget.ts +435 -0
  72. package/src/trade-history-widget.ts +19 -6
  73. package/src/tradefeed-widget.ts +3 -3
  74. package/src/trading-data.ts +22 -0
  75. package/src/trading-host.ts +8 -0
  76. package/styles/trading-controls.css +356 -0
  77. package/translation-keys.json +70 -1
@@ -0,0 +1,422 @@
1
+ // Option desk — multi-instance.
2
+ //
3
+ // One expiry of a chain, strike by strike: the call's side on the left, the put's mirrored on
4
+ // the right, and the strike between them. Every figure a trader compares across the strip -
5
+ // volume, open interest, volatility - carries a bar as well as a number, because a chain is
6
+ // read by shape first and by value second.
7
+ //
8
+ // Two scales, and the difference matters. Volume and open interest are scaled per side, since
9
+ // calls and puts trade in different sizes and comparing a call's volume against the busiest put
10
+ // says nothing. Volatility is scaled across BOTH sides at once - a skew is exactly the
11
+ // comparison between them, and two independent scales would flatten it.
12
+ //
13
+ // Greeks arrive one of two ways. A host that computes them sends them and the desk shows what
14
+ // it was given; a host that sends volatility instead has them computed here, from the same
15
+ // Black-Scholes the desktop uses. Neither is a fallback for the other going wrong - they are
16
+ // two shapes of host, and which one a row came from is not the desk's business.
17
+ import { formatPrice, formatQty } from './formatters.js';
18
+ import { makeElement, makeIconButton, makePanelId, makePanelRoot } from './dom.js';
19
+ import { ControlTypes } from './control-types.js';
20
+ import { makeGridMenu } from './grid-menu.js';
21
+ import { TradingHost, assertHost } from './trading-host.js';
22
+ import { OptionTypes, greeks as computeGreeks, type Greeks } from './black-scholes.js';
23
+ import { DataGrid, GridColumn } from '@stocksharp/grids/source/data-grid';
24
+
25
+ /// One contract's side of a strike.
26
+ export interface OptionSide {
27
+ symbol?: string;
28
+ bid?: number | null;
29
+ ask?: number | null;
30
+ last?: number | null;
31
+ /// What the venue says it is worth, when it says.
32
+ theoretical?: number | null;
33
+ volume?: number | null;
34
+ openInterest?: number | null;
35
+ /// Implied volatility as a fraction, by the price it was solved from.
36
+ ivBid?: number | null;
37
+ ivAsk?: number | null;
38
+ ivLast?: number | null;
39
+ historicalVolatility?: number | null;
40
+ /// Sent by a host that computes them. Left out, they are computed from `iv` below.
41
+ greeks?: Greeks;
42
+ }
43
+
44
+ /// One strike, both sides of it.
45
+ export interface OptionStrike {
46
+ strike: number;
47
+ call: OptionSide;
48
+ put: OptionSide;
49
+ }
50
+
51
+ /// What the chain is priced against. Without it the desk still shows quotes, and shows no
52
+ /// greeks: they are not a property of the option alone.
53
+ export interface OptionChainContext {
54
+ /// The underlying's price.
55
+ assetPrice?: number | null;
56
+ /// Years to expiry.
57
+ timeToExpiry?: number | null;
58
+ riskFree?: number;
59
+ dividend?: number;
60
+ }
61
+
62
+ export interface OptionDeskDeps {
63
+ host: TradingHost;
64
+ }
65
+
66
+ interface DeskRow extends OptionStrike {
67
+ /// Bar scales, resolved once per refresh over the whole chain rather than per row.
68
+ maxCallVolume: number;
69
+ maxPutVolume: number;
70
+ maxCallOpenInterest: number;
71
+ maxPutOpenInterest: number;
72
+ maxVolatility: number;
73
+ /// What the option is worth if exercised now. Zero for a strike out of the money.
74
+ callIntrinsic: number;
75
+ putIntrinsic: number;
76
+ }
77
+
78
+ export class OptionDeskWidget {
79
+ static TYPE = ControlTypes.OptionDesk;
80
+
81
+ rootEl: HTMLElement;
82
+ el: HTMLElement | null;
83
+ // `//` rather than `///` from here down — see the note in positions-widget.
84
+ _host: TradingHost;
85
+ _closeBtn: HTMLElement | null;
86
+ _exportBtn: HTMLElement | null;
87
+ _rows: DeskRow[];
88
+ _context: OptionChainContext;
89
+ _places: Record<keyof Greeks, number>;
90
+ _grid: DataGrid<DeskRow> | null;
91
+
92
+ static create(hostEl: HTMLElement, state: Record<string, unknown>, deps: OptionDeskDeps): OptionDeskWidget {
93
+ const host = assertHost(deps?.host, 'OptionDeskWidget');
94
+ const root = OptionDeskWidget._buildRoot(host);
95
+ root.id = makePanelId(OptionDeskWidget.TYPE);
96
+ hostEl.appendChild(root);
97
+ return new OptionDeskWidget(root, state || {}, deps);
98
+ }
99
+
100
+ static _buildRoot(host: TradingHost): HTMLElement {
101
+ const title = host.t('OptionDesk');
102
+ return makePanelRoot('option-desk-panel', title, [
103
+ makeElement('div', 'panel-header', {}, [
104
+ makeElement('span', '', {}, [title]),
105
+ makeIconButton('bt-icon-btn bt-icon-cancel panel-close-btn', host.t('ClosePanel'), 'bi-x', { type: 'button' }),
106
+ ]),
107
+ makeElement('div', 'panel-body panel-body-with-rail', {}, [
108
+ makeElement('div', 'panel-body-content', {}, [
109
+ makeElement('table', 'terminal-table option-desk-table', { role: 'table', 'aria-label': host.t('OptionChain') }, [
110
+ makeElement('thead', '', {}, []),
111
+ makeElement('tbody', 'option-desk-body', {}, []),
112
+ ]),
113
+ ]),
114
+ makeElement('div', 'panel-rail', { role: 'toolbar', 'aria-label': host.t('OptionDeskActions') }, [
115
+ makeIconButton('bt-icon-btn panel-export-btn', host.t('ExportToExcel'), 'bi-file-earmark-spreadsheet', {}),
116
+ ]),
117
+ ]),
118
+ ]);
119
+ }
120
+
121
+ constructor(rootEl: HTMLElement, _state: Record<string, unknown>, deps: OptionDeskDeps) {
122
+ this._host = assertHost(deps?.host, 'OptionDeskWidget');
123
+
124
+ this.rootEl = rootEl;
125
+ this.el = this.rootEl.querySelector('.option-desk-body');
126
+ this._closeBtn = this.rootEl.querySelector('.panel-close-btn');
127
+ this._exportBtn = this.rootEl.querySelector('.panel-export-btn');
128
+ this._rows = [];
129
+ this._context = {};
130
+ this._places = greekScales([], {});
131
+
132
+ this._closeBtn?.addEventListener('click', (e) => { e.preventDefault(); this._host.close(); });
133
+ this._exportBtn?.addEventListener('click', (e) => { e.preventDefault(); this._export(); });
134
+
135
+ const head = this.rootEl.querySelector('.option-desk-table thead');
136
+ this._grid = head && this.el
137
+ ? new DataGrid<DeskRow>({
138
+ head: head as HTMLElement,
139
+ body: this.el,
140
+ columns: this._columns(),
141
+ // By strike, ascending. A chain has exactly one order and it is not negotiable:
142
+ // the strip is read as a ladder, and re-sorting it by any column destroys that.
143
+ defaultSort: { col: 'strike', dir: 'asc' },
144
+ rowKey: (r) => String(r.strike),
145
+ emptyText: this._host.t('NoOptions'),
146
+ rowClass: (r) => this._rowClass(r),
147
+ contextMenu: makeGridMenu(this._host),
148
+ selection: 'multi',
149
+ })
150
+ : null;
151
+
152
+ // The greeks and the far volatilities are there when wanted and out of the way when not:
153
+ // a desk is read across, and thirty-six columns at once cannot be.
154
+ this._grid?.setState({
155
+ hidden: [
156
+ 'callRho', 'callTheta', 'callHv', 'callTheor',
157
+ 'putRho', 'putTheta', 'putHv', 'putTheor',
158
+ ],
159
+ });
160
+
161
+ this._host.register(this);
162
+ }
163
+
164
+ dispose(): void {
165
+ this._grid?.destroy();
166
+ this._host.unregister(this);
167
+ try { this.rootEl.remove(); } catch { /* already detached */ }
168
+ }
169
+
170
+ /// Show this chain, priced against this context.
171
+ ///
172
+ /// Both together, always: a chain and the underlying it is priced off are one observation,
173
+ /// and refreshing them separately shows greeks computed from a price that has moved.
174
+ update(strikes: OptionStrike[], context: OptionChainContext = {}): void {
175
+ this._context = context ?? {};
176
+ this._rows = scaleChain(strikes ?? [], this._context);
177
+ this._places = greekScales(this._rows, this._context);
178
+ this._grid?.setRows(this._rows);
179
+ }
180
+
181
+ /// The rows as the desk holds them, scales and intrinsic values resolved.
182
+ rows(): readonly DeskRow[] {
183
+ return this._rows;
184
+ }
185
+
186
+ _export(): void {
187
+ this._grid?.download('option-chain', this._host.t('OptionDesk'));
188
+ }
189
+
190
+ // Which side of the money this strike is on. A chain is read from the money outwards, and
191
+ // the line between the two halves is what a reader finds first.
192
+ _rowClass(row: DeskRow): string {
193
+ const asset = this._context.assetPrice;
194
+ if (asset === null || asset === undefined) return 'option-row';
195
+ return `option-row ${row.strike < asset ? 'option-itm-call' : 'option-itm-put'}`;
196
+ }
197
+
198
+ _columns(): GridColumn<DeskRow>[] {
199
+ const label = (key: string) => this._host.t(key);
200
+
201
+ const side = (which: 'call' | 'put'): GridColumn<DeskRow>[] => {
202
+ const prefix = which;
203
+ const at = (r: DeskRow): OptionSide => r[which];
204
+ const g = (r: DeskRow): Greeks | null => sideGreeks(r, which, this._context);
205
+
206
+ return [
207
+ { key: `${prefix}Rho`, header: label('Rho'), exportable: true, value: (r) => g(r)?.rho ?? null, render: (r) => decimals(g(r)?.rho, this._places.rho) },
208
+ { key: `${prefix}Theta`, header: label('Theta'), exportable: true, value: (r) => g(r)?.theta ?? null, render: (r) => decimals(g(r)?.theta, this._places.theta) },
209
+ { key: `${prefix}Vega`, header: label('Vega'), exportable: true, value: (r) => g(r)?.vega ?? null, render: (r) => decimals(g(r)?.vega, this._places.vega) },
210
+ { key: `${prefix}Gamma`, header: label('Gamma'), exportable: true, value: (r) => g(r)?.gamma ?? null, render: (r) => decimals(g(r)?.gamma, this._places.gamma) },
211
+ { key: `${prefix}Delta`, header: label('Delta'), exportable: true, value: (r) => g(r)?.delta ?? null, render: (r) => decimals(g(r)?.delta, this._places.delta) },
212
+ { key: `${prefix}Bid`, header: label('Bid'), exportable: true, cellClass: () => 'option-bid', value: (r) => at(r).bid ?? null, render: (r) => price(at(r).bid) },
213
+ { key: `${prefix}Ask`, header: label('Ask'), exportable: true, cellClass: () => 'option-ask', value: (r) => at(r).ask ?? null, render: (r) => price(at(r).ask) },
214
+ { key: `${prefix}Theor`, header: label('TheorPrice'), exportable: true, value: (r) => at(r).theoretical ?? null, render: (r) => price(at(r).theoretical) },
215
+ {
216
+ key: `${prefix}Volume`, header: label('Volume'), exportable: true,
217
+ value: (r) => at(r).volume ?? 0,
218
+ render: (r) => this._bar(at(r).volume, which === 'call' ? r.maxCallVolume : r.maxPutVolume, which, formatQty(at(r).volume ?? 0)),
219
+ exportValue: (r) => at(r).volume ?? 0,
220
+ },
221
+ {
222
+ key: `${prefix}Oi`, header: label('OI'), exportable: true,
223
+ value: (r) => at(r).openInterest ?? 0,
224
+ render: (r) => this._bar(at(r).openInterest, which === 'call' ? r.maxCallOpenInterest : r.maxPutOpenInterest, which, formatQty(at(r).openInterest ?? 0)),
225
+ exportValue: (r) => at(r).openInterest ?? 0,
226
+ },
227
+ { key: `${prefix}Symbol`, header: which === 'call' ? label('Call') : label('Put'), exportable: true, value: (r) => at(r).symbol ?? '' },
228
+ {
229
+ key: `${prefix}IvBid`, header: label('IVBid'), exportable: true,
230
+ value: (r) => at(r).ivBid ?? null,
231
+ render: (r) => this._bar(at(r).ivBid, r.maxVolatility, 'iv', percent(at(r).ivBid)),
232
+ exportValue: (r) => at(r).ivBid ?? '',
233
+ },
234
+ {
235
+ key: `${prefix}IvAsk`, header: label('IVAsk'), exportable: true,
236
+ value: (r) => at(r).ivAsk ?? null,
237
+ render: (r) => this._bar(at(r).ivAsk, r.maxVolatility, 'iv', percent(at(r).ivAsk)),
238
+ exportValue: (r) => at(r).ivAsk ?? '',
239
+ },
240
+ {
241
+ key: `${prefix}IvLast`, header: label('IVLast'), exportable: true,
242
+ value: (r) => at(r).ivLast ?? null,
243
+ render: (r) => this._bar(at(r).ivLast, r.maxVolatility, 'iv', percent(at(r).ivLast)),
244
+ exportValue: (r) => at(r).ivLast ?? '',
245
+ },
246
+ {
247
+ key: `${prefix}Hv`, header: label('HV'), exportable: true,
248
+ value: (r) => at(r).historicalVolatility ?? null,
249
+ render: (r) => this._bar(at(r).historicalVolatility, r.maxVolatility, 'iv', percent(at(r).historicalVolatility)),
250
+ exportValue: (r) => at(r).historicalVolatility ?? '',
251
+ },
252
+ ];
253
+ };
254
+
255
+ // Declared outward from the strike: volatilities and quotes against the middle, where
256
+ // the two sides are compared, and the greeks out at the edges. The put side is that
257
+ // same order reflected, which is what makes the chain a mirror rather than a repeat.
258
+ const puts = side('put').slice().reverse();
259
+
260
+ return [
261
+ ...side('call'),
262
+ {
263
+ key: 'strike',
264
+ header: label('Strike'),
265
+ exportable: true,
266
+ cellClass: () => 'option-strike',
267
+ value: (r) => r.strike,
268
+ render: (r) => price(r.strike),
269
+ },
270
+ {
271
+ key: 'intrinsic',
272
+ header: label('IntrinsicValue'),
273
+ exportable: true,
274
+ cellClass: () => 'option-intrinsic',
275
+ // Whichever side is in the money at this strike; the other is worth nothing to
276
+ // exercise, and showing both would be one number and one zero on every row.
277
+ value: (r) => Math.max(r.callIntrinsic, r.putIntrinsic),
278
+ render: (r) => price(Math.max(r.callIntrinsic, r.putIntrinsic)),
279
+ },
280
+ ...puts,
281
+ ];
282
+ }
283
+
284
+ // A figure with its share of the strip behind it. The bar is a width, not a drawing: it
285
+ // scales with the cell, it prints, and it needs no canvas per row.
286
+ _bar(value: number | null | undefined, max: number, kind: 'call' | 'put' | 'iv', text: string): string | Node {
287
+ if (value === null || value === undefined || !isFinite(value) || value <= 0) return text;
288
+
289
+ const cell = document.createElement('span');
290
+ cell.className = 'option-bar-cell';
291
+
292
+ const bar = document.createElement('span');
293
+ bar.className = `option-bar option-bar-${kind}`;
294
+ bar.style.width = `${Math.min(100, (value / (max || 1)) * 100).toFixed(1)}%`;
295
+ cell.appendChild(bar);
296
+
297
+ const label = document.createElement('span');
298
+ label.className = 'option-bar-text';
299
+ label.textContent = text;
300
+ cell.appendChild(label);
301
+
302
+ return cell;
303
+ }
304
+ }
305
+
306
+ /// Resolve the bar scales and the intrinsic values over a whole chain.
307
+ ///
308
+ /// One pass over every strike, not one per row: a bar means "this much of the busiest strike",
309
+ /// and a scale computed per row would make every row its own maximum.
310
+ export function scaleChain(strikes: readonly OptionStrike[], context: OptionChainContext): DeskRow[] {
311
+ const asset = context.assetPrice ?? null;
312
+
313
+ const maxOf = (pick: (s: OptionSide) => number | null | undefined, sides: (r: OptionStrike) => OptionSide[]): number =>
314
+ Math.max(0, ...strikes.flatMap(r => sides(r).map(s => pick(s) ?? 0)).filter(v => isFinite(v)));
315
+
316
+ const maxCallVolume = maxOf(s => s.volume, r => [r.call]);
317
+ const maxPutVolume = maxOf(s => s.volume, r => [r.put]);
318
+ const maxCallOpenInterest = maxOf(s => s.openInterest, r => [r.call]);
319
+ const maxPutOpenInterest = maxOf(s => s.openInterest, r => [r.put]);
320
+
321
+ // One scale across both sides: the comparison a skew IS, is the one between them.
322
+ const maxVolatility = Math.max(
323
+ maxOf(s => s.ivBid, r => [r.call, r.put]),
324
+ maxOf(s => s.ivAsk, r => [r.call, r.put]),
325
+ maxOf(s => s.ivLast, r => [r.call, r.put]),
326
+ maxOf(s => s.historicalVolatility, r => [r.call, r.put]),
327
+ );
328
+
329
+ return strikes.map(row => ({
330
+ ...row,
331
+ maxCallVolume,
332
+ maxPutVolume,
333
+ maxCallOpenInterest,
334
+ maxPutOpenInterest,
335
+ maxVolatility,
336
+ callIntrinsic: asset === null ? 0 : Math.max(0, asset - row.strike),
337
+ putIntrinsic: asset === null ? 0 : Math.max(0, row.strike - asset),
338
+ }));
339
+ }
340
+
341
+ /// The greeks for one side: the host's if it sent them, otherwise computed from its volatility.
342
+ ///
343
+ /// Null when neither is possible - no volatility, or nothing to price against. A blank is the
344
+ /// honest answer there; a zero would read as a measured delta of nothing.
345
+ export function sideGreeks(row: OptionStrike, which: 'call' | 'put', context: OptionChainContext): Greeks | null {
346
+ const side = row[which];
347
+ if (side.greeks !== undefined) return side.greeks;
348
+
349
+ const deviation = side.ivLast ?? side.ivBid ?? side.ivAsk ?? side.historicalVolatility ?? null;
350
+ const assetPrice = context.assetPrice ?? null;
351
+ const timeToExpiry = context.timeToExpiry ?? null;
352
+
353
+ if (deviation === null || assetPrice === null || timeToExpiry === null) return null;
354
+
355
+ return computeGreeks(which === 'call' ? OptionTypes.Call : OptionTypes.Put, {
356
+ assetPrice,
357
+ strike: row.strike,
358
+ timeToExpiry,
359
+ riskFree: context.riskFree ?? 0,
360
+ dividend: context.dividend ?? 0,
361
+ deviation,
362
+ });
363
+ }
364
+
365
+ /// Every greek this desk can show. Order is the order a chain is read in, outwards from delta.
366
+ const GREEK_KEYS = ['delta', 'gamma', 'vega', 'theta', 'rho'] as const;
367
+
368
+ /// Three significant digits for the smallest figure in a column, within bounds a column can hold.
369
+ const GREEK_DIGITS = 4;
370
+ const GREEK_MIN_PLACES = 2;
371
+ const GREEK_MAX_PLACES = 8;
372
+
373
+ /// How many decimal places a column of greeks needs.
374
+ ///
375
+ /// One count cannot serve every greek: a delta is about one, while a gamma on an underlying at
376
+ /// 60000 is about 0.00003, and the four places that suit the first show every strike of the
377
+ /// second as 0.0000 - a column that is present, aligned, and says nothing. So the count comes
378
+ /// from the numbers, sized to the smallest of them.
379
+ ///
380
+ /// One count for the whole column, not per cell: a column of figures is read down its decimal
381
+ /// point, and a ragged one is read a cell at a time.
382
+ export function greekPlaces(values: readonly (number | null | undefined)[]): number {
383
+ const scale = Math.min(...values
384
+ .filter((v): v is number => typeof v === 'number' && isFinite(v) && v !== 0)
385
+ .map(Math.abs));
386
+
387
+ // Nothing measurable: a zero column is a zero column at any width.
388
+ if (!isFinite(scale)) return GREEK_MIN_PLACES;
389
+
390
+ const places = GREEK_DIGITS - 1 - Math.floor(Math.log10(scale));
391
+ return Math.min(GREEK_MAX_PLACES, Math.max(GREEK_MIN_PLACES, places));
392
+ }
393
+
394
+ /// The places for each greek, measured across both sides of the chain at once.
395
+ ///
396
+ /// Across both sides deliberately: the desk mirrors, and a gamma written to eight places on the
397
+ /// left and five on the right stops being a mirror.
398
+ export function greekScales(rows: readonly OptionStrike[], context: OptionChainContext): Record<keyof Greeks, number> {
399
+ const all = rows
400
+ .flatMap(r => [sideGreeks(r, OptionTypes.Call, context), sideGreeks(r, OptionTypes.Put, context)])
401
+ .filter((g): g is Greeks => g !== null);
402
+
403
+ const places = {} as Record<keyof Greeks, number>;
404
+ for (const key of GREEK_KEYS) places[key] = greekPlaces(all.map(g => g[key]));
405
+ return places;
406
+ }
407
+
408
+ function decimals(value: number | null | undefined, places: number): string {
409
+ if (value === null || value === undefined || !isFinite(value)) return '';
410
+ return value.toFixed(places);
411
+ }
412
+
413
+ function price(value: number | null | undefined): string {
414
+ if (value === null || value === undefined || !isFinite(value)) return '';
415
+ return formatPrice(value);
416
+ }
417
+
418
+ /// A volatility, as the points a desk quotes it in rather than the fraction it is held as.
419
+ function percent(value: number | null | undefined): string {
420
+ if (value === null || value === undefined || !isFinite(value)) return '';
421
+ return `${(value * 100).toFixed(2)}%`;
422
+ }
@@ -0,0 +1,204 @@
1
+ // The geometry of a cumulative P&L curve, as pure functions over numbers.
2
+ //
3
+ // The same curve is read in three places and drawn at three sizes: a strategy row's sparkline,
4
+ // a statistics card, and a backtest's own chart. Only the last of those is a price chart - it
5
+ // shares the price axis and belongs to the chart engine. The other two are a curve in a box,
6
+ // and this is that curve: where each point lands, where the baseline sits, and which way the
7
+ // run ended. No canvas, so it can be checked against arithmetic rather than against pixels.
8
+
9
+ /// One sample of a run's cumulative P&L. Time is whatever the caller counts in - seconds, unix
10
+ /// milliseconds - because only the spacing between samples is used, never the absolute value.
11
+ export interface PnlPoint {
12
+ time: number;
13
+ value: number;
14
+ }
15
+
16
+ /// The box one curve fills, in device pixels. The padding keeps a curve at its extreme off the
17
+ /// edge, where a stroke would be clipped in half.
18
+ export interface PnlBox {
19
+ width: number;
20
+ height: number;
21
+ padX: number;
22
+ padY: number;
23
+ }
24
+
25
+ export interface PnlCurve {
26
+ /// The curve, in draw order.
27
+ points: [number, number][];
28
+ /// The curve closed down to the baseline, ready to fill.
29
+ area: [number, number][];
30
+ /// Y of zero P&L. Always inside the box: the range is widened to include it.
31
+ zeroY: number;
32
+ /// The value range the box covers, zero included.
33
+ min: number;
34
+ max: number;
35
+ /// Whether the run ended at or above where it started. What the curve is coloured by - and
36
+ /// the last value, not the highest: a run that peaked and gave it all back is a loss.
37
+ positive: boolean;
38
+ }
39
+
40
+ /// A run reduced to at most `count` samples, spanning the same stretch of time.
41
+ ///
42
+ /// A sparkline that keeps only the newest N samples marches sideways: each new sample pushes the
43
+ /// oldest off the left edge, so the shape slides and the run's beginning is lost. Compressing
44
+ /// instead keeps the whole run in the box and re-buckets it, so a new sample changes the curve's
45
+ /// shape rather than its position - which is what makes two readings of the same strategy
46
+ /// comparable.
47
+ ///
48
+ /// A bucket is summarised by its LAST sample, not by an average. This is a cumulative figure:
49
+ /// the last value in a bucket is where the run actually stood at that moment, while an average
50
+ /// would draw a rising run below the line it was on. Every point returned is therefore a real
51
+ /// sample, never a computed one, and the first and last are kept exactly - they are where the
52
+ /// run started and where it stands now.
53
+ export function compressPnl(points: readonly PnlPoint[], count: number): PnlPoint[] {
54
+ if (points.length <= count || count < 2) return points.slice();
55
+
56
+ const first = points[0];
57
+ const last = points[points.length - 1];
58
+ const span = last.time - first.time;
59
+
60
+ // Every sample at the same instant: there is no time to bucket by, so fall back to position.
61
+ if (!(span > 0)) {
62
+ const step = (points.length - 1) / (count - 1);
63
+ return Array.from({ length: count }, (_, i) => points[Math.round(i * step)]);
64
+ }
65
+
66
+ // One bucket per output point, the last sample in each standing for it. Buckets that caught
67
+ // nothing are skipped rather than repeated, so a quiet stretch reads as a long flat segment
68
+ // instead of as a row of identical points.
69
+ // `count - 1` buckets, not `count`: the first sample is seeded and the last is appended, so
70
+ // the buckets between them may contribute at most `count - 2` points. Sized any wider the
71
+ // result can overrun `count`, and trimming it afterwards would drop the run's start - the
72
+ // one point this function exists to keep.
73
+ const buckets = count - 1;
74
+ const out: PnlPoint[] = [first];
75
+ let bucket = 0;
76
+ for (let i = 1; i < points.length; i++) {
77
+ const index = Math.min(buckets - 1, Math.floor(((points[i].time - first.time) / span) * buckets));
78
+ if (index > bucket) {
79
+ out.push(points[i - 1]);
80
+ bucket = index;
81
+ }
82
+ }
83
+ if (out[out.length - 1] !== last) out.push(last);
84
+
85
+ return out;
86
+ }
87
+
88
+ /// Lay a run out in a box, or null when there is no curve to draw.
89
+ ///
90
+ /// Two rules that are not arbitrary. Zero is always in the range, so a run that only ever won
91
+ /// still shows the line it started from and the height of the curve means something. And the
92
+ /// horizontal axis is time, not sample index: a strategy that traded twice in the morning and
93
+ /// forty times after lunch should look like that, not like a curve with evenly spaced steps.
94
+ export function pnlCurve(points: readonly PnlPoint[], box: PnlBox): PnlCurve | null {
95
+ const clean = points
96
+ .filter(p => p !== null && p !== undefined && Number.isFinite(p.time) && Number.isFinite(p.value))
97
+ .slice()
98
+ .sort((a, b) => a.time - b.time);
99
+
100
+ if (clean.length < 2) return null;
101
+
102
+ // One sample per drawable pixel is as much as a box can show; past that the extra points are
103
+ // strokes on top of strokes. Compressing here rather than asking the caller to do it is what
104
+ // lets a host keep the whole run and still get a curve that does not slide.
105
+ const drawable = Math.max(2, Math.round(box.width - box.padX * 2));
106
+ const shown = compressPnl(clean, drawable);
107
+
108
+ const values = shown.map(p => p.value);
109
+ const min = Math.min(0, ...values);
110
+ const max = Math.max(0, ...values);
111
+
112
+ const left = box.padX;
113
+ const right = box.width - box.padX;
114
+ const top = box.padY;
115
+ const bottom = box.height - box.padY;
116
+
117
+ const firstTime = shown[0].time;
118
+ const lastTime = shown[shown.length - 1].time;
119
+ const timeSpan = lastTime - firstTime;
120
+ const valueSpan = max - min;
121
+
122
+ // A run with no spread in one axis collapses onto a line rather than dividing by nothing:
123
+ // every sample at the same instant stacks at the left edge, every sample at the same value
124
+ // rests on the top edge, which for a flat run is also its baseline.
125
+ const x = (time: number): number => (timeSpan === 0 ? left : left + ((time - firstTime) / timeSpan) * (right - left));
126
+ const y = (value: number): number => (valueSpan === 0 ? top : bottom - ((value - min) / valueSpan) * (bottom - top));
127
+
128
+ const curve = shown.map(p => [x(p.time), y(p.value)] as [number, number]);
129
+ const zeroY = y(0);
130
+
131
+ return {
132
+ points: curve,
133
+ // Closed along the baseline rather than along the foot of the box: a run entirely above
134
+ // water fills the gap between itself and zero, and nothing below it.
135
+ area: [...curve, [curve[curve.length - 1][0], zeroY], [curve[0][0], zeroY]],
136
+ zeroY,
137
+ min,
138
+ max,
139
+ positive: shown[shown.length - 1].value >= 0,
140
+ };
141
+ }
142
+
143
+ /// What a curve is drawn with. Colours come from the caller because the page owns its palette;
144
+ /// the two directions are the same pair every other control uses for up and down.
145
+ export interface PnlCurveStyle {
146
+ up: string;
147
+ down: string;
148
+ /// The zero line. A curve is read against it, so it is drawn even when nothing crosses it.
149
+ baseline: string;
150
+ lineWidth: number;
151
+ /// How much of the direction colour the filled area keeps, 0 to 1.
152
+ fillOpacity: number;
153
+ }
154
+
155
+ /// The 2D calls one paint makes. Narrow on purpose: a test supplies a recorder, and a control
156
+ /// that started reaching for something else shows up here rather than in a screenshot.
157
+ export interface PnlCurveContext {
158
+ clearRect(x: number, y: number, w: number, h: number): void;
159
+ beginPath(): void;
160
+ moveTo(x: number, y: number): void;
161
+ lineTo(x: number, y: number): void;
162
+ closePath(): void;
163
+ stroke(): void;
164
+ fill(): void;
165
+ setLineDash(segments: number[]): void;
166
+ globalAlpha: number;
167
+ // The browser's own type for these, so a real 2D context satisfies this contract as
168
+ // it stands: it accepts a gradient or a pattern where this only ever writes a colour.
169
+ strokeStyle: string | CanvasGradient | CanvasPattern;
170
+ fillStyle: string | CanvasGradient | CanvasPattern;
171
+ lineWidth: number;
172
+ }
173
+
174
+ /// Paint a laid-out curve: the baseline, the filled area under it, then the line itself.
175
+ export function drawPnlCurve(ctx: PnlCurveContext, curve: PnlCurve, box: PnlBox, style: PnlCurveStyle): void {
176
+ const colour = curve.positive ? style.up : style.down;
177
+
178
+ ctx.clearRect(0, 0, box.width, box.height);
179
+
180
+ ctx.setLineDash([2, 3]);
181
+ ctx.strokeStyle = style.baseline;
182
+ ctx.lineWidth = 1;
183
+ ctx.beginPath();
184
+ ctx.moveTo(box.padX, curve.zeroY);
185
+ ctx.lineTo(box.width - box.padX, curve.zeroY);
186
+ ctx.stroke();
187
+ ctx.setLineDash([]);
188
+
189
+ ctx.globalAlpha = style.fillOpacity;
190
+ ctx.fillStyle = colour;
191
+ ctx.beginPath();
192
+ ctx.moveTo(curve.area[0][0], curve.area[0][1]);
193
+ for (const [px, py] of curve.area.slice(1)) ctx.lineTo(px, py);
194
+ ctx.closePath();
195
+ ctx.fill();
196
+ ctx.globalAlpha = 1;
197
+
198
+ ctx.strokeStyle = colour;
199
+ ctx.lineWidth = style.lineWidth;
200
+ ctx.beginPath();
201
+ ctx.moveTo(curve.points[0][0], curve.points[0][1]);
202
+ for (const [px, py] of curve.points.slice(1)) ctx.lineTo(px, py);
203
+ ctx.stroke();
204
+ }