@orangecharts/wrun-chart-host 0.7.1 → 0.8.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 (124) hide show
  1. package/README.md +25 -3
  2. package/dist/constants/feature-flags.constants.d.ts +1 -0
  3. package/dist/constants/feature-flags.constants.js +5 -0
  4. package/dist/constants/option-venues.constants.d.ts +18 -0
  5. package/dist/constants/option-venues.constants.js +14 -0
  6. package/dist/constants/venue-presets.constants.d.ts +17 -3
  7. package/dist/constants/venue-presets.constants.js +17 -3
  8. package/dist/host-env.d.ts +24 -0
  9. package/dist/host-env.js +21 -0
  10. package/dist/host-ports.types.d.ts +12 -0
  11. package/dist/index.d.ts +16 -0
  12. package/dist/index.js +16 -0
  13. package/dist/indicators/controls/tpo-session.util.d.ts +40 -11
  14. package/dist/indicators/controls/tpo-session.util.js +138 -14
  15. package/dist/interfaces/option-instrument.interface.d.ts +6 -0
  16. package/dist/kscript-data/controls/live-trades-merge.util.d.ts +4 -0
  17. package/dist/kscript-data/controls/live-trades-merge.util.js +4 -0
  18. package/dist/settings-templates/footprint-rows.d.ts +25 -0
  19. package/dist/settings-templates/footprint-rows.js +127 -0
  20. package/dist/settings-templates/form-rows.d.ts +56 -0
  21. package/dist/settings-templates/form-rows.js +19 -0
  22. package/dist/settings-templates/frvp-fields.js +14 -0
  23. package/dist/settings-templates/index.d.ts +10 -1
  24. package/dist/settings-templates/index.js +11 -2
  25. package/dist/settings-templates/indicator-fields.js +78 -0
  26. package/dist/settings-templates/tool-rules.d.ts +35 -9
  27. package/dist/settings-templates/tool-rules.js +42 -8
  28. package/dist/settings-templates/tool-tables.generated.js +13 -2
  29. package/dist/utility/chart/candle-volume-unit.leaf.d.ts +16 -0
  30. package/dist/utility/chart/candle-volume-unit.leaf.js +61 -0
  31. package/dist/utility/chart/footprint-columns.util.d.ts +74 -0
  32. package/dist/utility/chart/footprint-columns.util.js +106 -0
  33. package/dist/utility/chart/footprint-display-mode.util.d.ts +40 -0
  34. package/dist/utility/chart/footprint-display-mode.util.js +62 -0
  35. package/dist/utility/chart/footprint-sierra-look.util.d.ts +2 -0
  36. package/dist/utility/chart/footprint-sierra-look.util.js +37 -0
  37. package/dist/utility/chart/kscript-venue-policy.util.js +4 -2
  38. package/dist/utility/chart/om-panel.util.d.ts +11 -0
  39. package/dist/utility/chart/om-panel.util.js +59 -0
  40. package/dist/utility/chart/window-geometry.leaf.d.ts +23 -1
  41. package/dist/utility/chart/window-geometry.leaf.js +78 -6
  42. package/dist/utility/chart/window-owner.leaf.d.ts +13 -0
  43. package/dist/utility/chart/window-owner.leaf.js +5 -0
  44. package/dist/utility/options/cme-options-root.util.d.ts +25 -0
  45. package/dist/utility/options/cme-options-root.util.js +40 -0
  46. package/dist/utility/options/option-book.util.d.ts +27 -0
  47. package/dist/utility/options/option-book.util.js +76 -0
  48. package/dist/utility/options/option-trade-date.util.d.ts +50 -0
  49. package/dist/utility/options/option-trade-date.util.js +120 -0
  50. package/dist/utility/wrun/sources/host-grid-landing.d.ts +4 -2
  51. package/dist/utility/wrun/sources/host-grid-landing.js +8 -0
  52. package/dist/utility/wrun/sources/lanes/options_flow.d.ts +40 -4
  53. package/dist/utility/wrun/sources/lanes/options_flow.js +115 -18
  54. package/dist/utility/wrun/sources/opra-option-lanes.util.d.ts +12 -9
  55. package/dist/utility/wrun/sources/opra-option-lanes.util.js +10 -7
  56. package/dist/utility/wrun/sources/row-lane-registry.js +9 -5
  57. package/dist/utility/wrun/sources/row-lanes/index.js +2 -0
  58. package/dist/utility/wrun/sources/row-lanes/option_contract_flow.d.ts +3 -2
  59. package/dist/utility/wrun/sources/row-lanes/option_contract_flow.js +30 -5
  60. package/dist/utility/wrun/sources/row-lanes/option_prints.d.ts +14 -1
  61. package/dist/utility/wrun/sources/row-lanes/option_prints.js +100 -23
  62. package/dist/utility/wrun/sources/row-lanes/option_strike_flow.d.ts +4 -0
  63. package/dist/utility/wrun/sources/row-lanes/option_strike_flow.js +65 -0
  64. package/dist/utility/wrun/sources/row-lanes/option_strikes.d.ts +47 -1
  65. package/dist/utility/wrun/sources/row-lanes/option_strikes.js +71 -2
  66. package/dist/utility/wrun/sources/row-lanes/option_surface.d.ts +14 -1
  67. package/dist/utility/wrun/sources/row-lanes/option_surface.js +30 -2
  68. package/dist/utility/wrun/sources/wrun-poll-lane.types.d.ts +7 -1
  69. package/dist/utility/wrun/sources/wrun-poll-lanes.util.d.ts +45 -5
  70. package/dist/utility/wrun/sources/wrun-poll-lanes.util.js +115 -3
  71. package/dist/utility/wrun/sources/wrun-row-lane-first-paint.util.d.ts +10 -0
  72. package/dist/utility/wrun/sources/wrun-row-lane-first-paint.util.js +57 -0
  73. package/dist/utility/wrun/sources/wrun-row-lanes.util.d.ts +60 -6
  74. package/dist/utility/wrun/sources/wrun-row-lanes.util.js +160 -23
  75. package/dist/utility/wrun/wrun-cloud-record.leaf.d.ts +27 -0
  76. package/dist/utility/wrun/wrun-cloud-record.leaf.js +71 -0
  77. package/dist/utility/wrun/wrun-cloud-record.util.d.ts +4 -21
  78. package/dist/utility/wrun/wrun-cloud-record.util.js +5 -65
  79. package/dist/utility/wrun/wrun-color-settings.util.d.ts +7 -5
  80. package/dist/utility/wrun/wrun-color-settings.util.js +26 -11
  81. package/dist/utility/wrun/wrun-draft-overlay.util.d.ts +4 -2
  82. package/dist/utility/wrun/wrun-draft-overlay.util.js +40 -3
  83. package/dist/utility/wrun/wrun-hosted-wire-caps.d.ts +1 -1
  84. package/dist/utility/wrun/wrun-hosted-wire-caps.js +4 -0
  85. package/dist/utility/wrun/wrun-lane-refusal.leaf.d.ts +29 -3
  86. package/dist/utility/wrun/wrun-lane-refusal.leaf.js +33 -3
  87. package/dist/utility/wrun/wrun-live-tick.util.d.ts +4 -1
  88. package/dist/utility/wrun/wrun-live-tick.util.js +39 -6
  89. package/dist/utility/wrun/wrun-market-size-defaults.leaf.d.ts +106 -0
  90. package/dist/utility/wrun/wrun-market-size-defaults.leaf.js +159 -0
  91. package/dist/utility/wrun/wrun-market-size-defaults.util.d.ts +44 -0
  92. package/dist/utility/wrun/wrun-market-size-defaults.util.js +213 -0
  93. package/dist/utility/wrun/wrun-opra-flow.leaf.d.ts +43 -8
  94. package/dist/utility/wrun/wrun-opra-flow.leaf.js +37 -6
  95. package/dist/utility/wrun/wrun-option-contract-flow.util.d.ts +51 -10
  96. package/dist/utility/wrun/wrun-option-contract-flow.util.js +85 -33
  97. package/dist/utility/wrun/wrun-option-prints.util.d.ts +133 -3
  98. package/dist/utility/wrun/wrun-option-prints.util.js +318 -8
  99. package/dist/utility/wrun/wrun-option-strike-flow-lane.util.d.ts +96 -0
  100. package/dist/utility/wrun/wrun-option-strike-flow-lane.util.js +215 -0
  101. package/dist/utility/wrun/wrun-option-strike-flow.util.d.ts +342 -0
  102. package/dist/utility/wrun/wrun-option-strike-flow.util.js +742 -0
  103. package/dist/utility/wrun/wrun-option-views.util.d.ts +183 -3
  104. package/dist/utility/wrun/wrun-option-views.util.js +504 -7
  105. package/dist/utility/wrun/wrun-options-chain.util.d.ts +6 -4
  106. package/dist/utility/wrun/wrun-options-chain.util.js +8 -5
  107. package/dist/utility/wrun/wrun-overlay-recovery.util.d.ts +2 -1
  108. package/dist/utility/wrun/wrun-overlay-recovery.util.js +7 -2
  109. package/dist/utility/wrun/wrun-overlay-run.util.js +120 -18
  110. package/dist/utility/wrun/wrun-pack-widths.leaf.d.ts +15 -0
  111. package/dist/utility/wrun/wrun-pack-widths.leaf.js +22 -0
  112. package/dist/utility/wrun/wrun-pack.util.d.ts +9 -8
  113. package/dist/utility/wrun/wrun-pack.util.js +21 -15
  114. package/dist/utility/wrun/wrun-panel-mount.util.d.ts +4 -0
  115. package/dist/utility/wrun/wrun-panel-mount.util.js +62 -22
  116. package/dist/utility/wrun/wrun-panel-style.util.d.ts +17 -2
  117. package/dist/utility/wrun/wrun-panel-style.util.js +47 -9
  118. package/dist/utility/wrun/wrun-pin-spelling.util.js +19 -10
  119. package/dist/utility/wrun/wrun-refusal.util.js +7 -1
  120. package/dist/utility/wrun/wrun-script-inputs.util.d.ts +13 -0
  121. package/dist/utility/wrun/wrun-script-inputs.util.js +43 -0
  122. package/dist/utility/wrun/wrun-tape-source.util.d.ts +9 -0
  123. package/dist/utility/wrun/wrun-tape-source.util.js +18 -0
  124. package/package.json +3 -3
@@ -0,0 +1,742 @@
1
+ /**
2
+ * The `option_strike_flow` class (OPTLOAD G3, OPTLOAD-READ-CONTRACT sections 6.3 to 6.8; om kit 0.89.0): one underlying's
3
+ * option flow summed per strike, per expiry or per both, per chart bar (or per trade date with `span` "session"), on
4
+ * every chain (OPRA, CME, the crypto venues). Pure: its K control (`K_OPTION_STRIKE_FLOW`) and the worker twin read the
5
+ * same rules from here, and so do the per-contract flow's grouped reads (`option_contract_flow`). The row lane's own part
6
+ * (the tuple's shape, the tiers, the horizon, the row budget, the per-bar fold) is wrun-option-strike-flow-lane.util,
7
+ * re-exported here: it rides the boot path with every row lane, and this module never does (the lane loads it for its
8
+ * facets; tests/utility/wrun/sources/option_strike_flow.boot-path.spec.ts).
9
+ *
10
+ * The tuple, 15 f64 (om `WRUN_OPTION_CELL_COLUMNS.option_strike_flow`, `OPTION_STRIKE_FLOW_TUPLE`): `[expiry_ms, strike,
11
+ * side_cp, dte_class, vol_ask, vol_bid, vol_mid, vol_none, vol_above_ask, vol_below_bid, prem_ask, prem_bid, prem_mid,
12
+ * prem_none, present]`. `expiry_ms` is 0 on a strike row, `strike` 0 on an expiry row; `side_cp` +1 a call, -1 a put, 0
13
+ * with `fold_types` (the ask columns then carry the bullish side, call ask plus put bid, and the bid columns the bearish
14
+ * one); `dte_class` 0 not split, 1 the 0DTE part, 2 the later expiries (`split_dte`). No NaN: a sum over no print is 0.
15
+ * Bit 14 of `present` marks a partial bar; a partial bar with no tuple carries one all-zero tuple with bit 14.
16
+ *
17
+ * Two reads land the same tuples:
18
+ * - GROUPED (the data plane computes): OPTION_PRINT_AGG's STRIKE, EXPIRY or EXPIRY_STRIKE scope rows, grouped to the
19
+ * chart's bar (`barSeconds` and `barAnchor`) or trade date (`span`) by the gateway, every knob applied there
20
+ * (`optionRead`, `wrunOptionStrikeFlowOptionRead`), one row per group key per bar (`wrunOptionStrikeFlowTupleOf`);
21
+ * - FOLDED (today's ask): the chain's CONTRACT rows at a contract tier, summed per group key and cut by the same rules
22
+ * in the browser (`foldWrunOptionStrikeFlowGroup`, section 6.4 step by step), when the gateway refuses `optionRead` by
23
+ * name (a deployment without the read: the session's fallback for the plane), when the chart's bars are no grouping
24
+ * the gateway can draw (a CME session bar, a week), or when the chain's book is one of several of its coin (a crypto
25
+ * venue: the gateway groups by coin, every book together).
26
+ * The worker twin answers one row per group stamp, `[stampMs, block]`, the block one Float64Array of the stamp's tuples
27
+ * back to back (`packWrunOptionStrikeFlowTuples`), handed over by transfer; the lane's fold reads them in place
28
+ * (`foldWrunOptionStrikeFlowBar`, the identity of a grouped bar).
29
+ *
30
+ * The 0DTE class (`expiries` "0dte" and "after_today", `split_dte`) is the venue family's clock (option-trade-date.util),
31
+ * the table the data plane's strike views are dated with, on both reads. `history` "today" is the trade date of the
32
+ * chart's newest bar on that clock, named on the request (`wrunOptionFlowTodayWindow`), never a clock's date.
33
+ */
34
+ import { KSCRIPT_SOURCE_CELL_BYTES, kScriptSourceAnswerRows } from '../chart/kscript-source-answer-budget.leaf.js';
35
+ import { liveBucketStartsInRange } from '../chart/live-bucket.util.js';
36
+ import { isEquityRegularSessionGated, usEquityAnchoredBucketStartMs } from '../chart/us-equities-session.util.js';
37
+ import { optionExpiresOnTradeDay, optionTradeDateClockOf, optionTradeDayByClock, optionTradeDayStartMsByClock, } from '../options/option-trade-date.util.js';
38
+ import { wrunPartialMarkerTuple } from './wrun-present-bits.util.js';
39
+ import { WRUN_OPTION_CONTRACT_FLOW_BOOK_FIELD, WRUN_OPTION_CONTRACT_FLOW_EXCHANGE_FIELD, WRUN_OPTION_CONTRACT_FLOW_RAW, WRUN_OPTION_CONTRACT_FLOW_RAW_WIDTH, WRUN_OPTION_PRINT_AGG_TIERS, wrunOptionContractFlowBarRows, wrunOptionFlowTodayFromOf, } from './wrun-option-contract-flow.util.js';
40
+ import { compareWrunOptionStrikeFlowTuples, WRUN_OPTION_FLOW_HISTORY, WRUN_OPTION_FLOW_SPANS, WRUN_OPTION_STRIKE_FLOW_COLUMN, WRUN_OPTION_STRIKE_FLOW_GROUPS, WRUN_OPTION_STRIKE_FLOW_TIERS, WRUN_OPTION_STRIKE_FLOW_WIDTH, wrunOptionStrikeFlowExpiriesOf, wrunOptionStrikeFlowPayloadKnobsOf, } from './wrun-option-strike-flow-lane.util.js';
41
+ import { refuseWrunOptionKnob, WRUN_OPTION_STRIKE_WINDOW_MAX_PCT } from './wrun-option-knobs.util.js';
42
+ import { wrunOptionChainAskStampHolds } from './wrun-option-prints.util.js';
43
+ import { wrunBarTiers, wrunHostBarOf, wrunHostBarSpanOf, wrunTierSegments, } from './wrun-tier-grid.util.js';
44
+ export * from './wrun-option-strike-flow-lane.util.js';
45
+ const MINUTE_MS = 60_000;
46
+ const DAY_MS = 86_400_000;
47
+ const HALF_HOUR_MS = 30 * MINUTE_MS;
48
+ /** The tuple's columns by name, in om's order (`WRUN_OPTION_CELL_COLUMNS.option_strike_flow`). */
49
+ export const WRUN_OPTION_STRIKE_FLOW_COLUMNS = Object.freeze([
50
+ 'expiry_ms',
51
+ 'strike',
52
+ 'side_cp',
53
+ 'dte_class',
54
+ 'vol_ask',
55
+ 'vol_bid',
56
+ 'vol_mid',
57
+ 'vol_none',
58
+ 'vol_above_ask',
59
+ 'vol_below_bid',
60
+ 'prem_ask',
61
+ 'prem_bid',
62
+ 'prem_mid',
63
+ 'prem_none',
64
+ 'present',
65
+ ]);
66
+ /** `dte_class`: 0 not split, 1 the 0DTE part, 2 the expiries after the trade date. */
67
+ export const WRUN_OPTION_STRIKE_FLOW_DTE_CLASS = Object.freeze({ whole: 0, zero: 1, later: 2 });
68
+ /** `strike_rows`: 1 to 200 (om `WRUN_OPTION_STRIKE_ROWS_MAX`). */
69
+ export const WRUN_OPTION_STRIKE_ROWS_MAX = 200;
70
+ /** The scope word of each group (pb-common `OptionPrintAggScope` STRIKE 5, EXPIRY 6, EXPIRY_STRIKE 7). */
71
+ export const WRUN_OPTION_STRIKE_FLOW_SCOPE = Object.freeze({
72
+ strike: { word: 'STRIKE', id: 5 },
73
+ expiry: { word: 'EXPIRY', id: 6 },
74
+ expiry_strike: { word: 'EXPIRY_STRIKE', id: 7 },
75
+ });
76
+ /** pb-common enums the request names by number (the gateway decodes JSON with encoding/json): `BarAnchor`, `BarSpan`,
77
+ * `OptionExpiryClass`, `OptionDteBucket`, `OptionType`. */
78
+ export const WRUN_OPTION_READ_ENUM = Object.freeze({
79
+ anchorUtc: 0,
80
+ anchorUsEquityRth: 1,
81
+ spanSession: 1,
82
+ expiryZeroDte: 1,
83
+ expiryAfterToday: 2,
84
+ dteZero: 1,
85
+ dteAfterZero: 5,
86
+ put: 1,
87
+ call: 2,
88
+ });
89
+ /** The tier a key names among the class's tiers, or undefined. */
90
+ export function wrunOptionStrikeFlowTierOf(key) {
91
+ return WRUN_OPTION_STRIKE_FLOW_TIERS.strike.find((tier) => tier.key === key);
92
+ }
93
+ // ---------------------------------------------------------------------------
94
+ // Knobs (om `optionCellFacets` and `planStrikeFlowFacets`, refused by the same names).
95
+ // ---------------------------------------------------------------------------
96
+ /**
97
+ * One input's knobs, validated as om's planner validates them (in its order), each refused by name
98
+ * (`wrun_option_knob_invalid`): `expiries`, `strike_window_pct`, `min_volume`, `span`, `history`, then `group`
99
+ * (required) and the knobs one group alone takes (`strike_window_pct` and `strike_rows` the strike and expiry_strike
100
+ * groups, `split_dte` and `fold_types` the strike group, "nearest:N" never the strike group), `strike_rows` (1 to 200),
101
+ * `split_dte` and `fold_types` (true or false). A knob that names a setting arrives as the setting's value (the
102
+ * planner's `resolveWrunOptionSettingKnobs`); a name still here is refused like any other value.
103
+ */
104
+ export function wrunOptionStrikeFlowKnobsOf(source, ctx) {
105
+ const expiries = wrunOptionStrikeFlowExpiriesOf(source.expiries);
106
+ if (expiries === undefined) {
107
+ refuseWrunOptionKnob(ctx, 'expiries', source.expiries, '"all", "0dte", "after_today" or "nearest:N"');
108
+ }
109
+ const windowPct = source.strike_window_pct;
110
+ if (windowPct !== undefined &&
111
+ !(typeof windowPct === 'number' &&
112
+ Number.isFinite(windowPct) &&
113
+ windowPct > 0 &&
114
+ windowPct <= WRUN_OPTION_STRIKE_WINDOW_MAX_PCT)) {
115
+ refuseWrunOptionKnob(ctx, 'strike_window_pct', windowPct, `a number above 0, at most ${WRUN_OPTION_STRIKE_WINDOW_MAX_PCT}`);
116
+ }
117
+ const minVolume = source.min_volume;
118
+ if (minVolume !== undefined && !(typeof minVolume === 'number' && Number.isFinite(minVolume) && minVolume > 0)) {
119
+ refuseWrunOptionKnob(ctx, 'min_volume', minVolume, 'a contract count above 0');
120
+ }
121
+ const word = (knob, words, absent) => {
122
+ const value = source[knob] ?? absent;
123
+ if (typeof value !== 'string' || !words.includes(value)) {
124
+ refuseWrunOptionKnob(ctx, knob, value, words.join(', '));
125
+ }
126
+ return value;
127
+ };
128
+ const span = word('span', WRUN_OPTION_FLOW_SPANS, 'bar');
129
+ const history = word('history', WRUN_OPTION_FLOW_HISTORY, 'window');
130
+ if (source.group === undefined) {
131
+ refuseWrunOptionKnob(ctx, 'group', '(none)', WRUN_OPTION_STRIKE_FLOW_GROUPS.join(', '));
132
+ }
133
+ const group = word('group', WRUN_OPTION_STRIKE_FLOW_GROUPS, 'strike');
134
+ const strikes = group === 'strike' || group === 'expiry_strike';
135
+ const onGroup = (knob, served, groups) => {
136
+ if (source[knob] === undefined || served)
137
+ return;
138
+ const plural = groups.includes(' and ') ? 's' : '';
139
+ refuseWrunOptionKnob(ctx, knob, source[knob], `a knob of the ${groups} group${plural} only`);
140
+ };
141
+ onGroup('strike_window_pct', strikes, 'strike and expiry_strike');
142
+ onGroup('strike_rows', strikes, 'strike and expiry_strike');
143
+ onGroup('split_dte', group === 'strike', 'strike');
144
+ onGroup('fold_types', group === 'strike', 'strike');
145
+ const read = expiries;
146
+ const expiriesWord = read.kind === 'all' ? undefined : read.kind === 'nearest' ? `nearest:${read.count}` : read.kind;
147
+ if (read.kind === 'nearest' && group === 'strike') {
148
+ refuseWrunOptionKnob(ctx, 'expiries', expiriesWord, 'a word of the strike group ("all", "0dte" or "after_today")');
149
+ }
150
+ const rows = source.strike_rows;
151
+ if (rows !== undefined &&
152
+ !(typeof rows === 'number' && Number.isInteger(rows) && rows >= 1 && rows <= WRUN_OPTION_STRIKE_ROWS_MAX)) {
153
+ refuseWrunOptionKnob(ctx, 'strike_rows', rows, `a whole number from 1 to ${WRUN_OPTION_STRIKE_ROWS_MAX}`);
154
+ }
155
+ const flag = (knob) => {
156
+ const value = source[knob];
157
+ if (value !== undefined && typeof value !== 'boolean')
158
+ refuseWrunOptionKnob(ctx, knob, value, 'true or false');
159
+ return value === true ? true : undefined;
160
+ };
161
+ const splitDte = flag('split_dte');
162
+ const foldTypes = flag('fold_types');
163
+ return {
164
+ group,
165
+ ...(expiriesWord !== undefined ? { expiries: expiriesWord } : {}),
166
+ ...(windowPct !== undefined ? { strikeWindowPct: windowPct } : {}),
167
+ ...(rows !== undefined ? { strikeRows: rows } : {}),
168
+ ...(splitDte ? { splitDte } : {}),
169
+ ...(foldTypes ? { foldTypes } : {}),
170
+ ...(span === 'session' ? { span: 'session' } : {}),
171
+ ...(history === 'today' ? { history: 'today' } : {}),
172
+ ...(minVolume !== undefined ? { minVolume: minVolume } : {}),
173
+ };
174
+ }
175
+ /** The fields an ask names its bars in: the run's bar span (ms) and the chart's bar grid. */
176
+ export const WRUN_OPTION_FLOW_BAR_MS_FIELD = 'barMs';
177
+ export const WRUN_OPTION_FLOW_BAR_GRID_FIELD = 'barGrid';
178
+ function positiveOf(value) {
179
+ return typeof value === 'number' && Number.isFinite(value) && value > 0 ? value : undefined;
180
+ }
181
+ function upperOf(value) {
182
+ return typeof value === 'string' ? value.trim().toUpperCase() : '';
183
+ }
184
+ function barGridOf(value) {
185
+ if (value === null || typeof value !== 'object')
186
+ return undefined;
187
+ const record = value;
188
+ const grid = {};
189
+ for (const key of ['exchange', 'symbol', 'sessionType', 'transformations']) {
190
+ if (typeof record[key] === 'string' && record[key] !== '')
191
+ grid[key] = record[key];
192
+ }
193
+ return grid;
194
+ }
195
+ /** The bars an ask names (both flow classes' K controls send them, option-flow-bars.util): the run's bar span and the
196
+ * chart's bar grid, each absent when the ask carries none. */
197
+ export function wrunOptionFlowBarsOf(payload) {
198
+ const barMs = positiveOf(payload?.[WRUN_OPTION_FLOW_BAR_MS_FIELD]);
199
+ const barGrid = barGridOf(payload?.[WRUN_OPTION_FLOW_BAR_GRID_FIELD]);
200
+ return { ...(barMs !== undefined ? { barMs } : {}), ...(barGrid !== undefined ? { barGrid } : {}) };
201
+ }
202
+ /** A payload as its acquisition (knob fields that are not valid read absent). */
203
+ export function wrunOptionStrikeFlowAcquisitionOf(payload) {
204
+ const coin = upperOf(payload?.coin);
205
+ const book = upperOf(payload?.[WRUN_OPTION_CONTRACT_FLOW_BOOK_FIELD]);
206
+ const knobs = wrunOptionStrikeFlowPayloadKnobsOf(payload);
207
+ const todayFromMs = wrunOptionFlowTodayFromOf(payload);
208
+ return {
209
+ coin,
210
+ exchange: upperOf(payload?.[WRUN_OPTION_CONTRACT_FLOW_EXCHANGE_FIELD]),
211
+ book: book !== '' ? book : coin,
212
+ ...knobs,
213
+ ...(typeof payload?.tier === 'string' ? { tier: payload.tier } : {}),
214
+ ...wrunOptionFlowBarsOf(payload),
215
+ ...(knobs.history === 'today' && todayFromMs !== undefined ? { todayFromMs } : {}),
216
+ };
217
+ }
218
+ /** Whether a payload is an `option_strike_flow` lane ask the K control serves: a coin, a group, one of the class's tiers
219
+ * and a chain whose OPRA stamp holds (the print classes' one rule); any other caller is declined, fail closed. */
220
+ export function isWrunOptionStrikeFlowAsk(payload) {
221
+ const acquisition = wrunOptionStrikeFlowAcquisitionOf(payload);
222
+ return (acquisition.coin !== '' &&
223
+ WRUN_OPTION_STRIKE_FLOW_GROUPS.includes(payload?.group) &&
224
+ wrunOptionStrikeFlowTierOf(acquisition.tier) !== undefined &&
225
+ wrunOptionChainAskStampHolds(payload, acquisition.exchange));
226
+ }
227
+ /** The chain an acquisition's rows are dated on (option-trade-date.util). */
228
+ export function wrunOptionFlowClockOf(acquisition) {
229
+ const chain = { exchange: acquisition.exchange, coin: acquisition.coin };
230
+ return optionTradeDateClockOf(chain);
231
+ }
232
+ /** The most tier buckets a grouping is proved over bucket by bucket (beyond it the fold reads the chart's bars). */
233
+ const GROUPING_PROOF_MAX_BUCKETS = 60_000;
234
+ /** The clock's session the gateway draws (contract 3.4): RTH on the New York date, UTC on the UTC date; none else. */
235
+ function sessionAnchorOf(clock) {
236
+ if (clock.rule.offsetHours !== 0 || clock.rule.weekendsToMonday === true)
237
+ return undefined;
238
+ if (clock.zone === 'America/New_York')
239
+ return WRUN_OPTION_READ_ENUM.anchorUsEquityRth;
240
+ if (clock.zone === 'UTC')
241
+ return WRUN_OPTION_READ_ENUM.anchorUtc;
242
+ return undefined;
243
+ }
244
+ /**
245
+ * The grouping of one ask's window `[fromMs, toMs)` at a tier: a session span groups by trade date (the gateway's
246
+ * session where the clock has one), else a chart bar of a day reads its trade date's session where that session lands
247
+ * on it (a daily bar holding one New York regular session, the cash session's buckets alone, or one UTC date), else the
248
+ * chart's bars when the gateway's bars are exactly them (every tier bucket of the window lands on the host bar the
249
+ * gateway's bar opens on: the UTC floor, or the 09:30 New York lattice of a regular-session stock chart's 45m to 12h
250
+ * bars, the tier dividing 30 minutes, a bucket outside the cash session reaching no bar on either side), else the
251
+ * chart's own bars, folded in the browser.
252
+ */
253
+ export function wrunOptionFlowGrouping(args) {
254
+ const { barMs, barGrid, tierMs, fromMs, toMs, clock } = args;
255
+ const sessionAnchor = sessionAnchorOf(clock);
256
+ const sessionServed = sessionAnchor !== undefined &&
257
+ tierMs > 0 &&
258
+ (sessionAnchor === WRUN_OPTION_READ_ENUM.anchorUtc ? DAY_MS % tierMs === 0 : HALF_HOUR_MS % tierMs === 0);
259
+ if (args.session) {
260
+ return sessionServed ? { kind: 'session', barAnchor: sessionAnchor } : { kind: 'host', session: true };
261
+ }
262
+ if (barMs === undefined || !(tierMs > 0) || !(toMs > fromMs) || fromMs % tierMs !== 0 || toMs % tierMs !== 0) {
263
+ return { kind: 'host', session: false };
264
+ }
265
+ const buckets = (toMs - fromMs) / tierMs;
266
+ if (buckets > GROUPING_PROOF_MAX_BUCKETS)
267
+ return { kind: 'host', session: false };
268
+ /** Whether every bucket's group (`barOf`: the host bar its group lands on, null for a bucket the anchor drops) is the
269
+ * bucket's own host bar; a dropped bucket counts only where the anchor drops off the cash session (`drops`). */
270
+ const lands = (barOf, drops) => {
271
+ for (let ts = fromMs; ts < toMs; ts += tierMs) {
272
+ const bar = barOf(ts);
273
+ const host = wrunHostBarOf(ts, barMs, barGrid);
274
+ if (bar === null) {
275
+ if (!drops && host !== null)
276
+ return false;
277
+ continue;
278
+ }
279
+ if (host !== bar)
280
+ return false;
281
+ }
282
+ return true;
283
+ };
284
+ if (barMs === DAY_MS && sessionServed) {
285
+ const anchor = sessionAnchor;
286
+ const sessionBar = (ts) => {
287
+ const stamp = wrunOptionFlowSessionStampMs(ts, anchor);
288
+ return stamp === null ? null : wrunHostBarOf(stamp, barMs, barGrid);
289
+ };
290
+ if (lands(sessionBar, anchor === WRUN_OPTION_READ_ENUM.anchorUsEquityRth)) {
291
+ return { kind: 'session', barAnchor: anchor };
292
+ }
293
+ }
294
+ if (barMs >= DAY_MS || barMs % tierMs !== 0)
295
+ return { kind: 'host', session: false };
296
+ if (fromMs % barMs === 0 && toMs % barMs === 0 && lands((ts) => ts - (ts % barMs), false)) {
297
+ return { kind: 'bars', barSeconds: barMs / 1000, barAnchor: WRUN_OPTION_READ_ENUM.anchorUtc };
298
+ }
299
+ if (HALF_HOUR_MS % tierMs === 0 &&
300
+ isEquityRegularSessionGated(barGrid?.exchange, barGrid?.sessionType) &&
301
+ lands((ts) => usEquityAnchoredBucketStartMs(ts, barMs), true)) {
302
+ return { kind: 'bars', barSeconds: barMs / 1000, barAnchor: WRUN_OPTION_READ_ENUM.anchorUsEquityRth };
303
+ }
304
+ return { kind: 'host', session: false };
305
+ }
306
+ /** The trade-date group a bucket stamped `ts` sums into under the gateway's session (contract 3.4): on RTH the New York
307
+ * date's 09:30 open for a bucket inside the cash session (null outside it), on UTC the UTC date's 00:00Z. */
308
+ export function wrunOptionFlowSessionStampMs(ts, barAnchor) {
309
+ if (!Number.isFinite(ts))
310
+ return null;
311
+ if (barAnchor === WRUN_OPTION_READ_ENUM.anchorUsEquityRth)
312
+ return usEquityAnchoredBucketStartMs(ts, DAY_MS);
313
+ return ts - (((ts % DAY_MS) + DAY_MS) % DAY_MS);
314
+ }
315
+ /**
316
+ * The stamp of the group a bucket stamped `ts` sums into, on the browser's side of a grouping (the fold's): the
317
+ * gateway's bar or session rule (`bars`, `session`), the chart's own bar, or a trade date of the clock stamped at its
318
+ * first instant (`host` with a session span); null for a bucket no group holds (off the cash session on RTH).
319
+ */
320
+ export function wrunOptionFlowGroupStampMs(ts, grouping, bars) {
321
+ if (!Number.isFinite(ts))
322
+ return null;
323
+ switch (grouping.kind) {
324
+ case 'bars': {
325
+ const barMs = grouping.barSeconds * 1000;
326
+ return grouping.barAnchor === WRUN_OPTION_READ_ENUM.anchorUsEquityRth
327
+ ? usEquityAnchoredBucketStartMs(ts, barMs)
328
+ : ts - (((ts % barMs) + barMs) % barMs);
329
+ }
330
+ case 'session':
331
+ return wrunOptionFlowSessionStampMs(ts, grouping.barAnchor);
332
+ case 'host': {
333
+ if (grouping.session) {
334
+ const start = optionTradeDayStartMsByClock(bars.clock, optionTradeDayByClock(bars.clock, ts));
335
+ return Number.isFinite(start) ? start : null;
336
+ }
337
+ return bars.barMs === undefined ? ts : wrunHostBarOf(ts, bars.barMs, bars.barGrid);
338
+ }
339
+ }
340
+ }
341
+ /**
342
+ * The window a session grouping reads: from the first instant of the trade date holding `fromMs` to the first instant
343
+ * of the trade date after the one holding `toMs - 1` (whole sessions, so a session's row sums every bucket of it
344
+ * whichever asked bars hold it), on the clock (the New York date for an RTH session: its midnights sit outside the
345
+ * cash session, a boundary the gateway takes).
346
+ */
347
+ export function wrunOptionFlowSessionWindow(fromMs, toMs, clock) {
348
+ const first = optionTradeDayByClock(clock, fromMs);
349
+ const last = optionTradeDayByClock(clock, toMs - 1);
350
+ if (!Number.isFinite(first) || !Number.isFinite(last))
351
+ return { fromMs, toMs };
352
+ let from = optionTradeDayStartMsByClock(clock, first);
353
+ let to = Number.NaN;
354
+ for (let day = last + 1; day <= last + 3 && !Number.isFinite(to); day += 1) {
355
+ to = optionTradeDayStartMsByClock(clock, day);
356
+ }
357
+ if (!Number.isFinite(from))
358
+ from = fromMs;
359
+ return { fromMs: Math.min(from, fromMs), toMs: Number.isFinite(to) ? Math.max(to, toMs) : toMs };
360
+ }
361
+ /**
362
+ * The part of an ask `[fromMs, toMs)` that `history` "today" reads (both flow classes' worker twins): from the first
363
+ * host bar ending after today's first instant, else from that instant on the tier's grid, to the ask's end. Today's
364
+ * first instant is the request's (`todayFromMs`, wrun-option-contract-flow.util `WRUN_OPTION_FLOW_TODAY_FIELD`): the
365
+ * trade date of the chart's newest bar on the chain's venue clock, which the K control names off the chart's bars
366
+ * (option-flow-bars.util `optionFlowTodayFields`), so a weekend, a holiday or a morning before the first print reads
367
+ * the last session the chart shows. Null when the ask holds nothing of today (an ask of older bars: quiet), and when
368
+ * the request names no today: no clock stands in for the chart's bars (a server clock reads Saturday on a Saturday).
369
+ */
370
+ export function wrunOptionFlowTodayWindow(args) {
371
+ const { toMs, todayFromMs, tierMs, barMs, barGrid } = args;
372
+ if (todayFromMs === undefined || !Number.isFinite(todayFromMs) || !(tierMs > 0))
373
+ return null;
374
+ const first = barMs === undefined
375
+ ? undefined
376
+ : wrunOptionFlowHostBars(args.fromMs, toMs, barMs, barGrid).find((open) => open + barMs > todayFromMs);
377
+ const fromMs = Math.max(args.fromMs, first ?? Math.ceil(todayFromMs / tierMs) * tierMs);
378
+ return toMs > fromMs ? { fromMs, toMs } : null;
379
+ }
380
+ /** The grouping's own fields: its bars, or its session on its anchor. */
381
+ export function wrunOptionFlowGroupingShape(grouping) {
382
+ return grouping.kind === 'bars'
383
+ ? { barSeconds: grouping.barSeconds, barAnchor: grouping.barAnchor }
384
+ : { span: WRUN_OPTION_READ_ENUM.spanSession, barAnchor: grouping.barAnchor };
385
+ }
386
+ /** The `expiryClass` an `expiries` word asks (0DTE or after today), else none. */
387
+ export function wrunOptionFlowExpiryClassOf(expiries) {
388
+ const read = wrunOptionStrikeFlowExpiriesOf(expiries);
389
+ if (read?.kind === '0dte')
390
+ return WRUN_OPTION_READ_ENUM.expiryZeroDte;
391
+ if (read?.kind === 'after_today')
392
+ return WRUN_OPTION_READ_ENUM.expiryAfterToday;
393
+ return undefined;
394
+ }
395
+ /**
396
+ * The `optionRead` of a grouped strike flow read (contract 3.1 and 6.4): the grouping, the expiry class, and the knobs
397
+ * the group's scope takes (STRIKE: the window, the strike rows, the volume floor, the split, the fold; EXPIRY: the
398
+ * nearest expiries and the volume floor; EXPIRY_STRIKE: the nearest expiries, the window, the strike rows and the
399
+ * volume floor). The planner refuses every other combination by name, so each field the read names is taken.
400
+ */
401
+ export function wrunOptionStrikeFlowOptionRead(knobs, grouping) {
402
+ const expiries = wrunOptionStrikeFlowExpiriesOf(knobs.expiries);
403
+ const expiryClass = wrunOptionFlowExpiryClassOf(knobs.expiries);
404
+ const strikes = knobs.group !== 'expiry';
405
+ return {
406
+ ...wrunOptionFlowGroupingShape(grouping),
407
+ ...(expiryClass !== undefined ? { expiryClass } : {}),
408
+ ...(expiries?.kind === 'nearest' && knobs.group !== 'strike' ? { nearestExpiries: expiries.count } : {}),
409
+ ...(strikes && knobs.strikeWindowPct !== undefined ? { strikeWindowPct: knobs.strikeWindowPct } : {}),
410
+ ...(strikes && knobs.strikeRows !== undefined ? { strikeRows: knobs.strikeRows } : {}),
411
+ ...(knobs.minVolume !== undefined ? { minVolume: knobs.minVolume } : {}),
412
+ ...(knobs.group === 'strike' && knobs.splitDte ? { splitDte: true } : {}),
413
+ ...(knobs.group === 'strike' && knobs.foldTypes ? { foldTypes: true } : {}),
414
+ };
415
+ }
416
+ /** The tiers the gateway groups a CONTRACT read at (contract 6.3: the contract tiers at 1m and 5m, the per-contract
417
+ * 30-minute view); an ask at any other tier (the hour, the day) is read as today. */
418
+ export const WRUN_OPTION_CONTRACT_GROUPED_TIERS = Object.freeze(['1m', '5m', '30m']);
419
+ /** The per-contract 30-minute view a session-span CONTRACT read asks (contract 6.3: `option_print_agg_bar_30m`, kept 30
420
+ * days). */
421
+ export const WRUN_OPTION_CONTRACT_SESSION_TIER = Object.freeze({
422
+ key: '30m',
423
+ ms: HALF_HOUR_MS,
424
+ retentionMs: 30 * DAY_MS,
425
+ });
426
+ /** The 30-minute tier of a strike flow group: its coarsest (kept, or 30 days on `expiry_strike`). */
427
+ export function wrunOptionStrikeFlowSessionTierOf(group) {
428
+ const tiers = WRUN_OPTION_STRIKE_FLOW_TIERS[group];
429
+ return tiers[tiers.length - 1];
430
+ }
431
+ /**
432
+ * The tier a grouped read asks (contract 6.8: "span session reads 30m"). A session grouping reads `sessionTier`, the
433
+ * 30-minute view that holds each session whole at the fewest rows (one SPY session, contract section 1: STRIKE 6,564
434
+ * rows at 30m against 23,271 at 5m; CONTRACT 30,239 against 76,740), where that view still holds the window's start
435
+ * (`retentionMs` back from `nowMs`). Any other grouping, and a window older than the view keeps, reads the ask's own
436
+ * tier. A session row is stamped by its anchor whatever tier sums it, so it lands where the ask's tier's would.
437
+ */
438
+ export function wrunOptionFlowGroupedTier(grouping, askTier, sessionTier, fromMs, nowMs) {
439
+ if (grouping.kind !== 'session')
440
+ return askTier;
441
+ const retention = sessionTier.retentionMs;
442
+ return retention === undefined || fromMs >= nowMs - retention ? sessionTier : askTier;
443
+ }
444
+ /**
445
+ * The `optionRead` of a grouped CONTRACT read (contract 3.1 and 6.4: steps 1, 2 and the premium floor of 7): the
446
+ * grouping, the 0DTE class of `expiries` "0dte", and `minBarPremium` from `min_premium` (a contract's group premium, the
447
+ * four sides' sum). Every other knob of `option_contract_flow` stays the fold's, as today.
448
+ */
449
+ export function wrunOptionContractFlowOptionRead(acquisition, grouping) {
450
+ return {
451
+ ...wrunOptionFlowGroupingShape(grouping),
452
+ ...(acquisition.expiries === '0dte' ? { expiryClass: WRUN_OPTION_READ_ENUM.expiryZeroDte } : {}),
453
+ ...(acquisition.minPremium !== undefined ? { minBarPremium: acquisition.minPremium } : {}),
454
+ };
455
+ }
456
+ /**
457
+ * Whether a CONTRACT row is a "0dte" row on today's read of `option_contract_flow` (the grouped read classes rows
458
+ * itself): its expiry falls on the trade date of its bucket on its chain's venue clock (option-trade-date.util, the data
459
+ * plane's `option_venue_clocks`), read at the bucket's middle so a UTC day bucket reads its own session's date.
460
+ */
461
+ export function wrunOptionContractFlowRowIsZeroDte(row, tierMs, chain) {
462
+ const middle = row.bucketMs + Math.floor(Math.max(0, tierMs) / 2);
463
+ return optionExpiresOnTradeDay(chain, row.raw[WRUN_OPTION_CONTRACT_FLOW_RAW.expiry], middle);
464
+ }
465
+ /** A value of a row: a finite number, else 0 (an unset sum). */
466
+ function sumOrZero(value) {
467
+ return typeof value === 'number' && Number.isFinite(value) ? value : 0;
468
+ }
469
+ /** The side a row's option type reads: CALL +1, PUT -1, any other (UNKNOWN, folded) 0. */
470
+ function sideOfType(optionType) {
471
+ if (optionType === WRUN_OPTION_READ_ENUM.call || optionType === 'CALL')
472
+ return 1;
473
+ if (optionType === WRUN_OPTION_READ_ENUM.put || optionType === 'PUT')
474
+ return -1;
475
+ return 0;
476
+ }
477
+ /**
478
+ * One grouped STRIKE, EXPIRY or EXPIRY_STRIKE row as the class's tuple (contract 6.5): `expiry_ms` 0 on a strike row,
479
+ * `strike` 0 on an expiry row, `side_cp` from the series' option type (0 with `fold_types`), `dte_class` from
480
+ * `dte_bucket` (ZERO 1, AFTER_ZERO 2, unset 0), every unset value 0. A row of another scope is dropped.
481
+ */
482
+ export function wrunOptionStrikeFlowTupleOf(record, group) {
483
+ if (record.scope !== WRUN_OPTION_STRIKE_FLOW_SCOPE[group].id)
484
+ return 'scope';
485
+ const strike = group === 'expiry' ? 0 : sumOrZero(record.strike);
486
+ const expiry = group === 'strike' ? 0 : sumOrZero(record.expiryMs);
487
+ if ((group !== 'expiry' && !(strike > 0)) || (group !== 'strike' && !(expiry > 0)))
488
+ return 'value';
489
+ const dte = record.dteBucket === WRUN_OPTION_READ_ENUM.dteZero
490
+ ? WRUN_OPTION_STRIKE_FLOW_DTE_CLASS.zero
491
+ : record.dteBucket === WRUN_OPTION_READ_ENUM.dteAfterZero
492
+ ? WRUN_OPTION_STRIKE_FLOW_DTE_CLASS.later
493
+ : WRUN_OPTION_STRIKE_FLOW_DTE_CLASS.whole;
494
+ return [
495
+ expiry,
496
+ strike,
497
+ sideOfType(record.optionType),
498
+ dte,
499
+ sumOrZero(record.volAsk),
500
+ sumOrZero(record.volBid),
501
+ sumOrZero(record.volMid),
502
+ sumOrZero(record.volNone),
503
+ sumOrZero(record.volAboveAsk),
504
+ sumOrZero(record.volBelowBid),
505
+ sumOrZero(record.premAsk),
506
+ sumOrZero(record.premBid),
507
+ sumOrZero(record.premMid),
508
+ sumOrZero(record.premNone),
509
+ 0,
510
+ ];
511
+ }
512
+ /** The flow columns a group key sums, in the tuple's order (vol_ask .. prem_none). */
513
+ const FLOW_KEYS = [
514
+ 'volAsk',
515
+ 'volBid',
516
+ 'volMid',
517
+ 'volNone',
518
+ 'volAboveAsk',
519
+ 'volBelowBid',
520
+ 'premAsk',
521
+ 'premBid',
522
+ 'premMid',
523
+ 'premNone',
524
+ ];
525
+ /** The columns `fold_types` crosses on a put (contract 6.4 step 8): a put's bid is the bullish side's ask. */
526
+ const PUT_FOLDED = Object.freeze({
527
+ volAsk: 'volBid',
528
+ volBid: 'volAsk',
529
+ volMid: 'volMid',
530
+ volNone: 'volNone',
531
+ volAboveAsk: 'volBelowBid',
532
+ volBelowBid: 'volAboveAsk',
533
+ premAsk: 'premBid',
534
+ premBid: 'premAsk',
535
+ premMid: 'premMid',
536
+ premNone: 'premNone',
537
+ });
538
+ function emptySums() {
539
+ return {
540
+ volAsk: 0,
541
+ volBid: 0,
542
+ volMid: 0,
543
+ volNone: 0,
544
+ volAboveAsk: 0,
545
+ volBelowBid: 0,
546
+ premAsk: 0,
547
+ premBid: 0,
548
+ premMid: 0,
549
+ premNone: 0,
550
+ };
551
+ }
552
+ /**
553
+ * One group's tuples (a chart bar's or a trade date's) from its CONTRACT rows, by section 6.4's rules in order, the
554
+ * gateway's own (tsdb-gateway `option_print_agg_group.go`):
555
+ * 1. the expiry class per row: 0DTE when the contract expires on the trade date of the row's bucket (its middle) on the
556
+ * chain's venue clock (`zero`, computed by the caller: `wrunOptionStrikeFlowZeroDte`); `expiries` "0dte" keeps those,
557
+ * "after_today" the others;
558
+ * 2. the sums per key: (side, strike, class) for the strike group, (side, expiry) for the expiry group, (side, strike,
559
+ * expiry) for both;
560
+ * 3. the spot: the group's sum_spot_size over its size_priced (every kept row: all strikes, expiries and sides), unset
561
+ * when nothing was priced;
562
+ * 4. `nearest:N` (expiry and expiry_strike): the N smallest distinct expiries of the group;
563
+ * 5. `strike_window_pct` (strike and expiry_strike): the strikes within that many percent of the spot;
564
+ * 6. `strike_rows` R: the R distinct strikes nearest the spot after the window (ties: the lower strike); 5 and 6
565
+ * skipped when the spot is unset or not above 0;
566
+ * 7. `min_volume`: a key's contracts at least the floor (on the strike group the side's strike over both classes);
567
+ * 8. the shape: `split_dte` one row per class part, else the parts summed; `fold_types` one row per strike, calls and
568
+ * puts summed with the put's sides crossed (the bullish side in the ask columns).
569
+ * Sorted by expiry, strike, side (calls first), class.
570
+ */
571
+ export function foldWrunOptionStrikeFlowGroup(rows, knobs) {
572
+ const expiries = wrunOptionStrikeFlowExpiriesOf(knobs.expiries) ?? { kind: 'all' };
573
+ const group = knobs.group;
574
+ const keys = new Map();
575
+ let spotSize = 0;
576
+ let sizePriced = 0;
577
+ for (const row of rows) {
578
+ if (expiries.kind === '0dte' && !row.zero)
579
+ continue;
580
+ if (expiries.kind === 'after_today' && row.zero)
581
+ continue;
582
+ spotSize += row.sumSpotSize;
583
+ sizePriced += row.sizePriced;
584
+ const strike = group === 'expiry' ? 0 : row.strike;
585
+ const expiry = group === 'strike' ? 0 : row.expiryMs;
586
+ const zero = group === 'strike' ? row.zero : false;
587
+ const key = `${row.side}|${strike}|${expiry}|${zero ? 1 : 0}`;
588
+ let sum = keys.get(key);
589
+ if (sum === undefined) {
590
+ sum = { side: row.side, strike, expiry, zero, sums: emptySums(), sumSize: 0 };
591
+ keys.set(key, sum);
592
+ }
593
+ for (const column of FLOW_KEYS)
594
+ sum.sums[column] += row[column];
595
+ sum.sumSize += row.sumSize;
596
+ }
597
+ let kept = [...keys.values()];
598
+ const spot = sizePriced > 0 ? spotSize / sizePriced : undefined;
599
+ const judged = spot !== undefined && spot > 0;
600
+ // Step 7's measure on the strike group: the side's strike over both class parts, read before the strike cuts.
601
+ const strikeSize = new Map();
602
+ if (group === 'strike') {
603
+ for (const sum of kept) {
604
+ const key = `${sum.side}|${sum.strike}`;
605
+ strikeSize.set(key, (strikeSize.get(key) ?? 0) + sum.sumSize);
606
+ }
607
+ }
608
+ if (expiries.kind === 'nearest' && group !== 'strike') {
609
+ const nearest = new Set([...new Set(kept.map((sum) => sum.expiry))].sort((a, b) => a - b).slice(0, expiries.count));
610
+ kept = kept.filter((sum) => nearest.has(sum.expiry));
611
+ }
612
+ if (group !== 'expiry' && judged) {
613
+ if (knobs.strikeWindowPct !== undefined) {
614
+ const reach = (spot * knobs.strikeWindowPct) / 100;
615
+ kept = kept.filter((sum) => Math.abs(sum.strike - spot) <= reach);
616
+ }
617
+ if (knobs.strikeRows !== undefined) {
618
+ const nearest = new Set([...new Set(kept.map((sum) => sum.strike))]
619
+ .sort((a, b) => Math.abs(a - spot) - Math.abs(b - spot) || a - b)
620
+ .slice(0, knobs.strikeRows));
621
+ kept = kept.filter((sum) => nearest.has(sum.strike));
622
+ }
623
+ }
624
+ if (knobs.minVolume !== undefined) {
625
+ const floor = knobs.minVolume;
626
+ kept = kept.filter((sum) => group === 'strike' ? (strikeSize.get(`${sum.side}|${sum.strike}`) ?? 0) >= floor : sum.sumSize >= floor);
627
+ }
628
+ const shaped = new Map();
629
+ const C = WRUN_OPTION_STRIKE_FLOW_COLUMN;
630
+ for (const sum of kept) {
631
+ const fold = group === 'strike' && knobs.foldTypes === true;
632
+ const split = group === 'strike' && knobs.splitDte === true;
633
+ const side = fold ? 0 : sum.side;
634
+ const dte = split
635
+ ? sum.zero
636
+ ? WRUN_OPTION_STRIKE_FLOW_DTE_CLASS.zero
637
+ : WRUN_OPTION_STRIKE_FLOW_DTE_CLASS.later
638
+ : 0;
639
+ const key = `${side}|${sum.strike}|${sum.expiry}|${dte}`;
640
+ let tuple = shaped.get(key);
641
+ if (tuple === undefined) {
642
+ tuple = new Array(WRUN_OPTION_STRIKE_FLOW_WIDTH).fill(0);
643
+ tuple[C.expiry] = sum.expiry;
644
+ tuple[C.strike] = sum.strike;
645
+ tuple[C.side] = side;
646
+ tuple[C.dteClass] = dte;
647
+ shaped.set(key, tuple);
648
+ }
649
+ FLOW_KEYS.forEach((column, at) => {
650
+ const from = fold && sum.side < 0 ? PUT_FOLDED[column] : column;
651
+ tuple[C.volAsk + at] += sum.sums[from];
652
+ });
653
+ }
654
+ return [...shaped.values()].sort(compareWrunOptionStrikeFlowTuples);
655
+ }
656
+ /** Whether a CONTRACT row is a 0DTE row: its expiry trades on the trade date of its bucket's middle (a UTC day bucket
657
+ * reads its own session's date) on the chain's venue clock. */
658
+ export function wrunOptionStrikeFlowZeroDte(row, tierMs, clock) {
659
+ const day = optionTradeDayByClock(clock, row.expiryMs);
660
+ return (Number.isFinite(day) && day === optionTradeDayByClock(clock, row.bucketMs + Math.floor(Math.max(0, tierMs) / 2)));
661
+ }
662
+ /**
663
+ * Today's ask for one strike flow ask's host bars, before any fetch, as the `option_contract_flow` lane plans its own
664
+ * (the read the class is folded from while the gateway does not group it): each bar's coarsest contract tier that fits,
665
+ * retains and already serves it (`WRUN_OPTION_PRINT_AGG_TIERS`, the bars' session grid), and the NEWEST bars whose
666
+ * projected contract rows (`wrunOptionContractFlowBarRows`, the chain's plane) fit the source answer budget, counted
667
+ * from the clock: the bars after the ask (a later ask's) are counted first, so every ask of one window keeps the same
668
+ * bars. A newest bar that cannot fit alone is skipped (a forming day read from minutes); from the first bar that fits,
669
+ * a bar that would pass the budget stops the walk. The kept bars are read per run of one tier (`reads`); every asked
670
+ * bar outside them is partial. `newerBarOpens` are the host bars after the ask, up to the clock.
671
+ */
672
+ export function wrunOptionStrikeFlowFoldPlan(args) {
673
+ const { barOpens, barMs, barGrid, nowMs } = args;
674
+ const all = [...new Set([...barOpens, ...args.newerBarOpens])].sort((a, b) => a - b);
675
+ const tiers = wrunBarTiers({
676
+ tiers: WRUN_OPTION_PRINT_AGG_TIERS,
677
+ barOpens: all,
678
+ barMs,
679
+ nowMs,
680
+ choice: 'coarsest',
681
+ sessionGrid: barGrid ?? null,
682
+ });
683
+ // The per-contract read weighs as `option_contract_flow`'s raw rows do: the same read, the same budget.
684
+ const budget = kScriptSourceAnswerRows(WRUN_OPTION_CONTRACT_FLOW_RAW_WIDTH);
685
+ let rows = 0;
686
+ let keptFromMs = Number.POSITIVE_INFINITY;
687
+ let keptToMs = Number.NEGATIVE_INFINITY;
688
+ for (let at = tiers.length - 1; at >= 0; at -= 1) {
689
+ const bar = tiers[at];
690
+ if (bar.partial || bar.tier === undefined) {
691
+ if (keptToMs !== Number.NEGATIVE_INFINITY)
692
+ break;
693
+ continue;
694
+ }
695
+ const span = bar.span ?? wrunHostBarSpanOf(bar.barOpenMs, barMs, barGrid ?? null);
696
+ const projected = wrunOptionContractFlowBarRows({ openMs: span.fromMs, endMs: span.toMs, tier: bar.tier }, nowMs, args.acquisition);
697
+ const barRows = Number.isFinite(projected) && projected > 0 ? projected : 0;
698
+ if (keptToMs === Number.NEGATIVE_INFINITY && barRows > budget)
699
+ continue;
700
+ if (rows + barRows > budget)
701
+ break;
702
+ rows += barRows;
703
+ keptFromMs = bar.barOpenMs;
704
+ if (keptToMs === Number.NEGATIVE_INFINITY)
705
+ keptToMs = bar.barOpenMs;
706
+ }
707
+ const asked = new Set(barOpens);
708
+ const keptBars = tiers.filter((bar) => asked.has(bar.barOpenMs) && !bar.partial && bar.barOpenMs >= keptFromMs && bar.barOpenMs <= keptToMs);
709
+ const keptSet = new Set(keptBars.map((bar) => bar.barOpenMs));
710
+ return {
711
+ reads: wrunTierSegments(keptBars, barMs),
712
+ partialBars: barOpens.filter((open) => !keptSet.has(open)),
713
+ keptFromMs,
714
+ keptToMs,
715
+ };
716
+ }
717
+ /** The host bars `[fromMs, toMs)` holds on the chart's grid, ascending (`liveBucketStartsInRange` over the grid). */
718
+ export function wrunOptionFlowHostBars(fromMs, toMs, barMs, barGrid) {
719
+ if (!(toMs > fromMs) || !(barMs > 0))
720
+ return [];
721
+ return liveBucketStartsInRange(fromMs, toMs - 1, barMs, barGrid ?? null).filter((open) => open < toMs);
722
+ }
723
+ // ---------------------------------------------------------------------------
724
+ // The answer: packed blocks (the lane's fold of a host bar is the lane module's).
725
+ // ---------------------------------------------------------------------------
726
+ /** A stamp's tuples packed as the worker hands them over: one Float64Array of `count x WIDTH` values. */
727
+ export function packWrunOptionStrikeFlowTuples(tuples) {
728
+ const block = new Float64Array(tuples.length * WRUN_OPTION_STRIKE_FLOW_WIDTH);
729
+ let at = 0;
730
+ for (const tuple of tuples) {
731
+ for (let column = 0; column < WRUN_OPTION_STRIKE_FLOW_WIDTH; column += 1)
732
+ block[at + column] = tuple[column];
733
+ at += WRUN_OPTION_STRIKE_FLOW_WIDTH;
734
+ }
735
+ return block;
736
+ }
737
+ /** The marker of a partial bar holding no tuple (every value 0, bit 14 of `present`). */
738
+ export function wrunOptionStrikeFlowPartialMarker() {
739
+ return wrunPartialMarkerTuple(WRUN_OPTION_STRIKE_FLOW_WIDTH);
740
+ }
741
+ /** The bytes one answered tuple weighs in every estimate of a source answer. */
742
+ export const WRUN_OPTION_STRIKE_FLOW_TUPLE_BYTES = WRUN_OPTION_STRIKE_FLOW_WIDTH * KSCRIPT_SOURCE_CELL_BYTES;