@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.
- package/README.md +204 -17
- package/dist/esm/black-scholes.js +147 -0
- package/dist/esm/black-scholes.js.map +1 -0
- package/dist/esm/chart-engine.js +15 -0
- package/dist/esm/chart-engine.js.map +1 -0
- package/dist/esm/control-types.js +8 -0
- package/dist/esm/control-types.js.map +1 -1
- package/dist/esm/equity-widget.js +261 -0
- package/dist/esm/equity-widget.js.map +1 -0
- package/dist/esm/heatmap-grid.js +271 -0
- package/dist/esm/heatmap-grid.js.map +1 -0
- package/dist/esm/index.js +37 -0
- package/dist/esm/index.js.map +1 -1
- package/dist/esm/log-monitor-widget.js +265 -0
- package/dist/esm/log-monitor-widget.js.map +1 -0
- package/dist/esm/log-tree.js +96 -0
- package/dist/esm/log-tree.js.map +1 -0
- package/dist/esm/optimization-heatmap-widget.js +303 -0
- package/dist/esm/optimization-heatmap-widget.js.map +1 -0
- package/dist/esm/option-desk-widget.js +322 -0
- package/dist/esm/option-desk-widget.js.map +1 -0
- package/dist/esm/option-smile-widget.js +252 -0
- package/dist/esm/option-smile-widget.js.map +1 -0
- package/dist/esm/pnl-curve.js +133 -0
- package/dist/esm/pnl-curve.js.map +1 -0
- package/dist/esm/statistics-widget.js +194 -0
- package/dist/esm/statistics-widget.js.map +1 -0
- package/dist/esm/strategies-widget.js +348 -0
- package/dist/esm/strategies-widget.js.map +1 -0
- package/dist/esm/surface-grid.js +282 -0
- package/dist/esm/surface-grid.js.map +1 -0
- package/dist/esm/surface-widget.js +379 -0
- package/dist/esm/surface-widget.js.map +1 -0
- package/dist/sstradingcontrols.js +2982 -295
- package/dist/sstradingcontrols.js.map +4 -4
- package/dist/types/black-scholes.d.ts +28 -0
- package/dist/types/black-scholes.d.ts.map +1 -0
- package/dist/types/chart-engine.d.ts +3 -0
- package/dist/types/chart-engine.d.ts.map +1 -0
- package/dist/types/control-types.d.ts +8 -0
- package/dist/types/control-types.d.ts.map +1 -1
- package/dist/types/equity-widget.d.ts +34 -0
- package/dist/types/equity-widget.d.ts.map +1 -0
- package/dist/types/heatmap-grid.d.ts +88 -0
- package/dist/types/heatmap-grid.d.ts.map +1 -0
- package/dist/types/index.d.ts +31 -1
- package/dist/types/index.d.ts.map +1 -1
- package/dist/types/log-monitor-widget.d.ts +42 -0
- package/dist/types/log-monitor-widget.d.ts.map +1 -0
- package/dist/types/log-tree.d.ts +34 -0
- package/dist/types/log-tree.d.ts.map +1 -0
- package/dist/types/optimization-heatmap-widget.d.ts +45 -0
- package/dist/types/optimization-heatmap-widget.d.ts.map +1 -0
- package/dist/types/option-desk-widget.d.ts +68 -0
- package/dist/types/option-desk-widget.d.ts.map +1 -0
- package/dist/types/option-smile-widget.d.ts +39 -0
- package/dist/types/option-smile-widget.d.ts.map +1 -0
- package/dist/types/pnl-curve.d.ts +46 -0
- package/dist/types/pnl-curve.d.ts.map +1 -0
- package/dist/types/statistics-widget.d.ts +29 -0
- package/dist/types/statistics-widget.d.ts.map +1 -0
- package/dist/types/strategies-widget.d.ts +63 -0
- package/dist/types/strategies-widget.d.ts.map +1 -0
- package/dist/types/surface-grid.d.ts +64 -0
- package/dist/types/surface-grid.d.ts.map +1 -0
- package/dist/types/surface-widget.d.ts +64 -0
- package/dist/types/surface-widget.d.ts.map +1 -0
- package/dist/types/trading-data.d.ts +9 -0
- package/dist/types/trading-data.d.ts.map +1 -1
- package/package.json +54 -3
- package/screenshots/equity.png +0 -0
- package/screenshots/log-monitor.png +0 -0
- package/screenshots/optimization-surface.png +0 -0
- package/screenshots/optimization.png +0 -0
- package/screenshots/option-desk.png +0 -0
- package/screenshots/option-smile.png +0 -0
- package/screenshots/panels.jpg +0 -0
- package/screenshots/statistics.png +0 -0
- package/screenshots/strategies.png +0 -0
- package/src/black-scholes.ts +199 -0
- package/src/chart-engine.global.ts +64 -0
- package/src/chart-engine.ts +29 -0
- package/src/control-types.ts +8 -0
- package/src/equity-widget.ts +289 -0
- package/src/heatmap-grid.ts +405 -0
- package/src/index.ts +87 -0
- package/src/log-monitor-widget.ts +312 -0
- package/src/log-tree.ts +131 -0
- package/src/optimization-heatmap-widget.ts +347 -0
- package/src/option-desk-widget.ts +422 -0
- package/src/option-smile-widget.ts +281 -0
- package/src/pnl-curve.ts +216 -0
- package/src/statistics-widget.ts +226 -0
- package/src/strategies-widget.ts +435 -0
- package/src/surface-grid.ts +410 -0
- package/src/surface-widget.ts +457 -0
- package/src/trading-data.ts +22 -0
- package/styles/trading-controls.css +637 -0
- package/translation-keys.json +83 -1
|
@@ -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
ADDED
|
@@ -0,0 +1,216 @@
|
|
|
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
|
+
/// 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;
|
|
43
|
+
/// Whether the run ended at or above where it started. What the curve is coloured by - and
|
|
44
|
+
/// the last value, not the highest: a run that peaked and gave it all back is a loss.
|
|
45
|
+
positive: boolean;
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
/// A run reduced to at most `count` samples, spanning the same stretch of time.
|
|
49
|
+
///
|
|
50
|
+
/// A sparkline that keeps only the newest N samples marches sideways: each new sample pushes the
|
|
51
|
+
/// oldest off the left edge, so the shape slides and the run's beginning is lost. Compressing
|
|
52
|
+
/// instead keeps the whole run in the box and re-buckets it, so a new sample changes the curve's
|
|
53
|
+
/// shape rather than its position - which is what makes two readings of the same strategy
|
|
54
|
+
/// comparable.
|
|
55
|
+
///
|
|
56
|
+
/// A bucket is summarised by its LAST sample, not by an average. This is a cumulative figure:
|
|
57
|
+
/// the last value in a bucket is where the run actually stood at that moment, while an average
|
|
58
|
+
/// would draw a rising run below the line it was on. Every point returned is therefore a real
|
|
59
|
+
/// sample, never a computed one, and the first and last are kept exactly - they are where the
|
|
60
|
+
/// run started and where it stands now.
|
|
61
|
+
export function compressPnl(points: readonly PnlPoint[], count: number): PnlPoint[] {
|
|
62
|
+
if (points.length <= count || count < 2) return points.slice();
|
|
63
|
+
|
|
64
|
+
const first = points[0];
|
|
65
|
+
const last = points[points.length - 1];
|
|
66
|
+
const span = last.time - first.time;
|
|
67
|
+
|
|
68
|
+
// Every sample at the same instant: there is no time to bucket by, so fall back to position.
|
|
69
|
+
if (!(span > 0)) {
|
|
70
|
+
const step = (points.length - 1) / (count - 1);
|
|
71
|
+
return Array.from({ length: count }, (_, i) => points[Math.round(i * step)]);
|
|
72
|
+
}
|
|
73
|
+
|
|
74
|
+
// One bucket per output point, the last sample in each standing for it. Buckets that caught
|
|
75
|
+
// nothing are skipped rather than repeated, so a quiet stretch reads as a long flat segment
|
|
76
|
+
// instead of as a row of identical points.
|
|
77
|
+
// `count - 1` buckets, not `count`: the first sample is seeded and the last is appended, so
|
|
78
|
+
// the buckets between them may contribute at most `count - 2` points. Sized any wider the
|
|
79
|
+
// result can overrun `count`, and trimming it afterwards would drop the run's start - the
|
|
80
|
+
// one point this function exists to keep.
|
|
81
|
+
const buckets = count - 1;
|
|
82
|
+
const out: PnlPoint[] = [first];
|
|
83
|
+
let bucket = 0;
|
|
84
|
+
for (let i = 1; i < points.length; i++) {
|
|
85
|
+
const index = Math.min(buckets - 1, Math.floor(((points[i].time - first.time) / span) * buckets));
|
|
86
|
+
if (index > bucket) {
|
|
87
|
+
out.push(points[i - 1]);
|
|
88
|
+
bucket = index;
|
|
89
|
+
}
|
|
90
|
+
}
|
|
91
|
+
if (out[out.length - 1] !== last) out.push(last);
|
|
92
|
+
|
|
93
|
+
return out;
|
|
94
|
+
}
|
|
95
|
+
|
|
96
|
+
/// Lay a run out in a box, or null when there is no curve to draw.
|
|
97
|
+
///
|
|
98
|
+
/// Two rules that are not arbitrary. Zero is always in the range, so a run that only ever won
|
|
99
|
+
/// still shows the line it started from and the height of the curve means something. And the
|
|
100
|
+
/// horizontal axis is time, not sample index: a strategy that traded twice in the morning and
|
|
101
|
+
/// forty times after lunch should look like that, not like a curve with evenly spaced steps.
|
|
102
|
+
export function pnlCurve(points: readonly PnlPoint[], box: PnlBox): PnlCurve | null {
|
|
103
|
+
const clean = points
|
|
104
|
+
.filter(p => p !== null && p !== undefined && Number.isFinite(p.time) && Number.isFinite(p.value))
|
|
105
|
+
.slice()
|
|
106
|
+
.sort((a, b) => a.time - b.time);
|
|
107
|
+
|
|
108
|
+
if (clean.length < 2) return null;
|
|
109
|
+
|
|
110
|
+
// One sample per drawable pixel is as much as a box can show; past that the extra points are
|
|
111
|
+
// strokes on top of strokes. Compressing here rather than asking the caller to do it is what
|
|
112
|
+
// lets a host keep the whole run and still get a curve that does not slide.
|
|
113
|
+
const drawable = Math.max(2, Math.round(box.width - box.padX * 2));
|
|
114
|
+
const shown = compressPnl(clean, drawable);
|
|
115
|
+
|
|
116
|
+
const values = shown.map(p => p.value);
|
|
117
|
+
const min = Math.min(0, ...values);
|
|
118
|
+
const max = Math.max(0, ...values);
|
|
119
|
+
|
|
120
|
+
const left = box.padX;
|
|
121
|
+
const right = box.width - box.padX;
|
|
122
|
+
const top = box.padY;
|
|
123
|
+
const bottom = box.height - box.padY;
|
|
124
|
+
|
|
125
|
+
const firstTime = shown[0].time;
|
|
126
|
+
const lastTime = shown[shown.length - 1].time;
|
|
127
|
+
const timeSpan = lastTime - firstTime;
|
|
128
|
+
const valueSpan = max - min;
|
|
129
|
+
|
|
130
|
+
// A run with no spread in one axis collapses onto a line rather than dividing by nothing:
|
|
131
|
+
// every sample at the same instant stacks at the left edge, every sample at the same value
|
|
132
|
+
// rests on the top edge, which for a flat run is also its baseline.
|
|
133
|
+
const x = (time: number): number => (timeSpan === 0 ? left : left + ((time - firstTime) / timeSpan) * (right - left));
|
|
134
|
+
const y = (value: number): number => (valueSpan === 0 ? top : bottom - ((value - min) / valueSpan) * (bottom - top));
|
|
135
|
+
|
|
136
|
+
const curve = shown.map(p => [x(p.time), y(p.value)] as [number, number]);
|
|
137
|
+
const zeroY = y(0);
|
|
138
|
+
const last = shown[shown.length - 1].value;
|
|
139
|
+
|
|
140
|
+
return {
|
|
141
|
+
points: curve,
|
|
142
|
+
// Closed along the baseline rather than along the foot of the box: a run entirely above
|
|
143
|
+
// water fills the gap between itself and zero, and nothing below it.
|
|
144
|
+
area: [...curve, [curve[curve.length - 1][0], zeroY], [curve[0][0], zeroY]],
|
|
145
|
+
zeroY,
|
|
146
|
+
min,
|
|
147
|
+
max,
|
|
148
|
+
from: firstTime,
|
|
149
|
+
to: lastTime,
|
|
150
|
+
last,
|
|
151
|
+
positive: last >= 0,
|
|
152
|
+
};
|
|
153
|
+
}
|
|
154
|
+
|
|
155
|
+
/// What a curve is drawn with. Colours come from the caller because the page owns its palette;
|
|
156
|
+
/// the two directions are the same pair every other control uses for up and down.
|
|
157
|
+
export interface PnlCurveStyle {
|
|
158
|
+
up: string;
|
|
159
|
+
down: string;
|
|
160
|
+
/// The zero line. A curve is read against it, so it is drawn even when nothing crosses it.
|
|
161
|
+
baseline: string;
|
|
162
|
+
lineWidth: number;
|
|
163
|
+
/// How much of the direction colour the filled area keeps, 0 to 1.
|
|
164
|
+
fillOpacity: number;
|
|
165
|
+
}
|
|
166
|
+
|
|
167
|
+
/// The 2D calls one paint makes. Narrow on purpose: a test supplies a recorder, and a control
|
|
168
|
+
/// that started reaching for something else shows up here rather than in a screenshot.
|
|
169
|
+
export interface PnlCurveContext {
|
|
170
|
+
clearRect(x: number, y: number, w: number, h: number): void;
|
|
171
|
+
beginPath(): void;
|
|
172
|
+
moveTo(x: number, y: number): void;
|
|
173
|
+
lineTo(x: number, y: number): void;
|
|
174
|
+
closePath(): void;
|
|
175
|
+
stroke(): void;
|
|
176
|
+
fill(): void;
|
|
177
|
+
setLineDash(segments: number[]): void;
|
|
178
|
+
globalAlpha: number;
|
|
179
|
+
// The browser's own type for these, so a real 2D context satisfies this contract as
|
|
180
|
+
// it stands: it accepts a gradient or a pattern where this only ever writes a colour.
|
|
181
|
+
strokeStyle: string | CanvasGradient | CanvasPattern;
|
|
182
|
+
fillStyle: string | CanvasGradient | CanvasPattern;
|
|
183
|
+
lineWidth: number;
|
|
184
|
+
}
|
|
185
|
+
|
|
186
|
+
/// Paint a laid-out curve: the baseline, the filled area under it, then the line itself.
|
|
187
|
+
export function drawPnlCurve(ctx: PnlCurveContext, curve: PnlCurve, box: PnlBox, style: PnlCurveStyle): void {
|
|
188
|
+
const colour = curve.positive ? style.up : style.down;
|
|
189
|
+
|
|
190
|
+
ctx.clearRect(0, 0, box.width, box.height);
|
|
191
|
+
|
|
192
|
+
ctx.setLineDash([2, 3]);
|
|
193
|
+
ctx.strokeStyle = style.baseline;
|
|
194
|
+
ctx.lineWidth = 1;
|
|
195
|
+
ctx.beginPath();
|
|
196
|
+
ctx.moveTo(box.padX, curve.zeroY);
|
|
197
|
+
ctx.lineTo(box.width - box.padX, curve.zeroY);
|
|
198
|
+
ctx.stroke();
|
|
199
|
+
ctx.setLineDash([]);
|
|
200
|
+
|
|
201
|
+
ctx.globalAlpha = style.fillOpacity;
|
|
202
|
+
ctx.fillStyle = colour;
|
|
203
|
+
ctx.beginPath();
|
|
204
|
+
ctx.moveTo(curve.area[0][0], curve.area[0][1]);
|
|
205
|
+
for (const [px, py] of curve.area.slice(1)) ctx.lineTo(px, py);
|
|
206
|
+
ctx.closePath();
|
|
207
|
+
ctx.fill();
|
|
208
|
+
ctx.globalAlpha = 1;
|
|
209
|
+
|
|
210
|
+
ctx.strokeStyle = colour;
|
|
211
|
+
ctx.lineWidth = style.lineWidth;
|
|
212
|
+
ctx.beginPath();
|
|
213
|
+
ctx.moveTo(curve.points[0][0], curve.points[0][1]);
|
|
214
|
+
for (const [px, py] of curve.points.slice(1)) ctx.lineTo(px, py);
|
|
215
|
+
ctx.stroke();
|
|
216
|
+
}
|