@stocksharp/trading-controls 1.2.0 → 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.
- package/README.md +95 -16
- package/dist/esm/black-scholes.js +147 -0
- package/dist/esm/black-scholes.js.map +1 -0
- package/dist/esm/control-types.js +4 -0
- package/dist/esm/control-types.js.map +1 -1
- package/dist/esm/index.js +18 -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/option-desk-widget.js +322 -0
- package/dist/esm/option-desk-widget.js.map +1 -0
- package/dist/esm/pnl-curve.js +129 -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/sstradingcontrols.js +1307 -47
- 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/control-types.d.ts +4 -0
- package/dist/types/control-types.d.ts.map +1 -1
- package/dist/types/index.d.ts +16 -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/option-desk-widget.d.ts +68 -0
- package/dist/types/option-desk-widget.d.ts.map +1 -0
- package/dist/types/pnl-curve.d.ts +43 -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/trading-data.d.ts +9 -0
- package/dist/types/trading-data.d.ts.map +1 -1
- package/package.json +27 -2
- package/screenshots/log-monitor.png +0 -0
- package/screenshots/option-desk.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/control-types.ts +4 -0
- package/src/index.ts +41 -0
- package/src/log-monitor-widget.ts +312 -0
- package/src/log-tree.ts +131 -0
- package/src/option-desk-widget.ts +422 -0
- package/src/pnl-curve.ts +204 -0
- package/src/statistics-widget.ts +226 -0
- package/src/strategies-widget.ts +435 -0
- package/src/trading-data.ts +22 -0
- package/styles/trading-controls.css +356 -0
- package/translation-keys.json +70 -1
package/src/log-tree.ts
ADDED
|
@@ -0,0 +1,131 @@
|
|
|
1
|
+
// The log monitor's shape, as pure functions: how sources nest, and which messages a view of
|
|
2
|
+
// them keeps.
|
|
3
|
+
//
|
|
4
|
+
// A log source announces its parent, not its children, and it can announce itself before its
|
|
5
|
+
// parent has said anything — so the tree is assembled from whatever has arrived rather than
|
|
6
|
+
// walked from a root that may not exist yet. Keeping that here is what makes it checkable: a
|
|
7
|
+
// cycle, an orphan and an unnamed source are all things a live feed produces, and none of them
|
|
8
|
+
// should be discovered as a hung page.
|
|
9
|
+
|
|
10
|
+
/// The levels a log message carries. The names are the wire's; the letter is what a narrow
|
|
11
|
+
/// column shows.
|
|
12
|
+
export const LogLevels = {
|
|
13
|
+
Error: 'error',
|
|
14
|
+
Warning: 'warning',
|
|
15
|
+
Info: 'info',
|
|
16
|
+
Debug: 'debug',
|
|
17
|
+
Verbose: 'verbose',
|
|
18
|
+
} as const;
|
|
19
|
+
|
|
20
|
+
export type LogLevel = typeof LogLevels[keyof typeof LogLevels];
|
|
21
|
+
|
|
22
|
+
/// One source of log messages, as it announces itself.
|
|
23
|
+
export interface LogSourceNode {
|
|
24
|
+
id: string;
|
|
25
|
+
name: string;
|
|
26
|
+
/// The source this one runs under, when it has one.
|
|
27
|
+
parentId?: string | null;
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
/// A source placed in the tree.
|
|
31
|
+
export interface LogTreeNode extends LogSourceNode {
|
|
32
|
+
depth: number;
|
|
33
|
+
children: LogTreeNode[];
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
/// One line of a log.
|
|
37
|
+
export interface LogMessageRow {
|
|
38
|
+
id: number | string;
|
|
39
|
+
/// When it was written, in whatever the consumer counts in.
|
|
40
|
+
time: number | string;
|
|
41
|
+
level: LogLevel | string;
|
|
42
|
+
/// Which source wrote it. The tree filters on this.
|
|
43
|
+
sourceId: string;
|
|
44
|
+
/// That source's name, when the consumer sends it rather than looking it up.
|
|
45
|
+
source?: string;
|
|
46
|
+
message: string;
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
/// Assemble the sources into a forest, roots first, each node carrying its depth.
|
|
50
|
+
///
|
|
51
|
+
/// A source whose parent is not among these is a root: it is the only honest place for it, and
|
|
52
|
+
/// dropping it would silently lose a whole strategy's log because its connector had not spoken
|
|
53
|
+
/// yet. A cycle is broken the same way, by rooting the first node of it — a wrong tree beats a
|
|
54
|
+
/// walk that never ends.
|
|
55
|
+
export function buildLogTree(sources: readonly LogSourceNode[]): LogTreeNode[] {
|
|
56
|
+
const byId = new Map<string, LogTreeNode>();
|
|
57
|
+
for (const s of sources)
|
|
58
|
+
byId.set(s.id, { ...s, name: s.name && s.name.length > 0 ? s.name : '—', depth: 0, children: [] });
|
|
59
|
+
|
|
60
|
+
const roots: LogTreeNode[] = [];
|
|
61
|
+
|
|
62
|
+
for (const node of byId.values()) {
|
|
63
|
+
const parent = node.parentId != null ? byId.get(node.parentId) : undefined;
|
|
64
|
+
if (parent !== undefined && parent !== node && !descends(byId, parent, node.id)) parent.children.push(node);
|
|
65
|
+
else roots.push(node);
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
const setDepth = (node: LogTreeNode, depth: number): void => {
|
|
69
|
+
node.depth = depth;
|
|
70
|
+
for (const child of node.children) setDepth(child, depth + 1);
|
|
71
|
+
};
|
|
72
|
+
for (const root of roots) setDepth(root, 0);
|
|
73
|
+
|
|
74
|
+
return roots;
|
|
75
|
+
}
|
|
76
|
+
|
|
77
|
+
/// Whether `node` already sits under `id`, which is how a cycle is spotted before it is made.
|
|
78
|
+
function descends(byId: Map<string, LogTreeNode>, node: LogTreeNode, id: string): boolean {
|
|
79
|
+
const seen = new Set<string>();
|
|
80
|
+
let at: LogTreeNode | undefined = node;
|
|
81
|
+
while (at !== undefined && !seen.has(at.id)) {
|
|
82
|
+
if (at.id === id) return true;
|
|
83
|
+
seen.add(at.id);
|
|
84
|
+
at = at.parentId != null ? byId.get(at.parentId) : undefined;
|
|
85
|
+
}
|
|
86
|
+
return false;
|
|
87
|
+
}
|
|
88
|
+
|
|
89
|
+
/// The ids a selected node covers: itself and everything under it, or null for no selection.
|
|
90
|
+
///
|
|
91
|
+
/// Null rather than every id, because "everything" and "this node, which happens to be the
|
|
92
|
+
/// root" are different questions and only one of them narrows when a new source appears.
|
|
93
|
+
export function subtreeOf(sources: readonly LogSourceNode[], selectedId: string | null): Set<string> | null {
|
|
94
|
+
if (selectedId === null) return null;
|
|
95
|
+
|
|
96
|
+
const children = new Map<string, string[]>();
|
|
97
|
+
for (const s of sources) {
|
|
98
|
+
if (s.parentId == null) continue;
|
|
99
|
+
const siblings = children.get(s.parentId);
|
|
100
|
+
if (siblings === undefined) children.set(s.parentId, [s.id]);
|
|
101
|
+
else siblings.push(s.id);
|
|
102
|
+
}
|
|
103
|
+
|
|
104
|
+
const out = new Set<string>();
|
|
105
|
+
const walk = (id: string): void => {
|
|
106
|
+
if (out.has(id)) return;
|
|
107
|
+
out.add(id);
|
|
108
|
+
for (const child of children.get(id) ?? []) walk(child);
|
|
109
|
+
};
|
|
110
|
+
walk(selectedId);
|
|
111
|
+
return out;
|
|
112
|
+
}
|
|
113
|
+
|
|
114
|
+
/// What a view of the log is showing.
|
|
115
|
+
export interface LogView {
|
|
116
|
+
levels: ReadonlySet<string>;
|
|
117
|
+
text: string;
|
|
118
|
+
/// Source ids to keep, or null for all of them.
|
|
119
|
+
sources: ReadonlySet<string> | null;
|
|
120
|
+
}
|
|
121
|
+
|
|
122
|
+
/// Whether this message belongs in that view. Every filter applies at once.
|
|
123
|
+
export function keepLog(message: LogMessageRow, view: LogView): boolean {
|
|
124
|
+
if (!view.levels.has(message.level)) return false;
|
|
125
|
+
if (view.sources !== null && !view.sources.has(message.sourceId)) return false;
|
|
126
|
+
|
|
127
|
+
const text = view.text.trim();
|
|
128
|
+
if (text.length === 0) return true;
|
|
129
|
+
|
|
130
|
+
return (message.message ?? '').toLowerCase().includes(text.toLowerCase());
|
|
131
|
+
}
|
|
@@ -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
|
+
}
|