@orangecharts/wrun-chart-host 0.7.1 → 0.9.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 (210) hide show
  1. package/README.md +27 -4
  2. package/dist/constants/feature-flags.constants.d.ts +5 -0
  3. package/dist/constants/feature-flags.constants.js +32 -0
  4. package/dist/constants/marketCapabilities.constants.d.ts +14 -9
  5. package/dist/constants/marketCapabilities.constants.js +36 -13
  6. package/dist/constants/opra-compliance.constants.d.ts +14 -0
  7. package/dist/constants/opra-compliance.constants.js +14 -0
  8. package/dist/constants/option-venues.constants.d.ts +29 -6
  9. package/dist/constants/option-venues.constants.js +19 -2
  10. package/dist/constants/venue-presets.constants.d.ts +17 -3
  11. package/dist/constants/venue-presets.constants.js +17 -3
  12. package/dist/host-env.d.ts +34 -4
  13. package/dist/host-env.js +21 -0
  14. package/dist/host-ports.types.d.ts +51 -3
  15. package/dist/index.d.ts +17 -0
  16. package/dist/index.js +17 -0
  17. package/dist/indicators/controls/tpo-session.util.d.ts +40 -11
  18. package/dist/indicators/controls/tpo-session.util.js +138 -14
  19. package/dist/interfaces/opra-realtime.interface.d.ts +13 -11
  20. package/dist/interfaces/opra-realtime.interface.js +10 -10
  21. package/dist/interfaces/option-instrument.interface.d.ts +6 -0
  22. package/dist/interfaces/wrun-runtime.interface.d.ts +34 -13
  23. package/dist/kscript-data/controls/live-trades-merge.util.d.ts +57 -10
  24. package/dist/kscript-data/controls/live-trades-merge.util.js +85 -16
  25. package/dist/market-data/billing.interface.d.ts +138 -17
  26. package/dist/market-data/billing.interface.js +25 -8
  27. package/dist/market-data/venues/index.d.ts +3 -3
  28. package/dist/market-data/venues/opra.contract.copy.json +5 -3
  29. package/dist/market-data/venues/opra.d.ts +3 -3
  30. package/dist/market-data/venues/opra.js +5 -4
  31. package/dist/replay/replayLadder.js +3 -1
  32. package/dist/settings-templates/footprint-rows.d.ts +25 -0
  33. package/dist/settings-templates/footprint-rows.js +127 -0
  34. package/dist/settings-templates/form-rows.d.ts +56 -0
  35. package/dist/settings-templates/form-rows.js +19 -0
  36. package/dist/settings-templates/frvp-fields.js +14 -0
  37. package/dist/settings-templates/index.d.ts +10 -1
  38. package/dist/settings-templates/index.js +11 -2
  39. package/dist/settings-templates/indicator-fields.js +78 -0
  40. package/dist/settings-templates/tool-rules.d.ts +35 -9
  41. package/dist/settings-templates/tool-rules.js +42 -8
  42. package/dist/settings-templates/tool-tables.generated.js +13 -2
  43. package/dist/utility/chart/candle-volume-unit.leaf.d.ts +16 -0
  44. package/dist/utility/chart/candle-volume-unit.leaf.js +61 -0
  45. package/dist/utility/chart/crypto-index.leaf.d.ts +2 -2
  46. package/dist/utility/chart/crypto-index.leaf.js +2 -2
  47. package/dist/utility/chart/footprint-columns.util.d.ts +74 -0
  48. package/dist/utility/chart/footprint-columns.util.js +106 -0
  49. package/dist/utility/chart/footprint-display-mode.util.d.ts +40 -0
  50. package/dist/utility/chart/footprint-display-mode.util.js +62 -0
  51. package/dist/utility/chart/footprint-sierra-look.util.d.ts +2 -0
  52. package/dist/utility/chart/footprint-sierra-look.util.js +37 -0
  53. package/dist/utility/chart/index-mode-admission.util.js +9 -1
  54. package/dist/utility/chart/index-mode.util.d.ts +5 -2
  55. package/dist/utility/chart/index-mode.util.js +23 -13
  56. package/dist/utility/chart/kscript-venue-policy.util.d.ts +28 -21
  57. package/dist/utility/chart/kscript-venue-policy.util.js +34 -26
  58. package/dist/utility/chart/marketKind.util.d.ts +12 -10
  59. package/dist/utility/chart/marketKind.util.js +17 -7
  60. package/dist/utility/chart/om-panel-push-style.util.d.ts +7 -7
  61. package/dist/utility/chart/om-panel-push-style.util.js +17 -15
  62. package/dist/utility/chart/om-panel.util.d.ts +11 -0
  63. package/dist/utility/chart/om-panel.util.js +65 -6
  64. package/dist/utility/chart/profile-block-size.util.d.ts +16 -0
  65. package/dist/utility/chart/profile-block-size.util.js +7 -0
  66. package/dist/utility/chart/quote-perp.leaf.d.ts +17 -0
  67. package/dist/utility/chart/quote-perp.leaf.js +20 -0
  68. package/dist/utility/chart/window-geometry.leaf.d.ts +23 -1
  69. package/dist/utility/chart/window-geometry.leaf.js +78 -6
  70. package/dist/utility/chart/window-owner.leaf.d.ts +13 -0
  71. package/dist/utility/chart/window-owner.leaf.js +5 -0
  72. package/dist/utility/chart/wrun-run-result.util.d.ts +5 -0
  73. package/dist/utility/chart/wrun-run-result.util.js +4 -1
  74. package/dist/utility/common/transformations.util.d.ts +7 -0
  75. package/dist/utility/common/transformations.util.js +11 -0
  76. package/dist/utility/options/cme-options-root.util.d.ts +25 -0
  77. package/dist/utility/options/cme-options-root.util.js +40 -0
  78. package/dist/utility/options/option-book.util.d.ts +27 -0
  79. package/dist/utility/options/option-book.util.js +76 -0
  80. package/dist/utility/options/option-trade-date.util.d.ts +50 -0
  81. package/dist/utility/options/option-trade-date.util.js +120 -0
  82. package/dist/utility/options/option-venue.util.d.ts +3 -3
  83. package/dist/utility/options/option-venue.util.js +3 -3
  84. package/dist/utility/wrun/run-schedule/wrun-late-reads.util.d.ts +1 -1
  85. package/dist/utility/wrun/run-schedule/wrun-late-reads.util.js +2 -2
  86. package/dist/utility/wrun/run-schedule/wrun-prefix-feeds.util.d.ts +2 -2
  87. package/dist/utility/wrun/run-schedule/wrun-prefix-feeds.util.js +5 -1
  88. package/dist/utility/wrun/sources/host-grid-landing.d.ts +4 -2
  89. package/dist/utility/wrun/sources/host-grid-landing.js +8 -0
  90. package/dist/utility/wrun/sources/lanes/options_flow.d.ts +40 -4
  91. package/dist/utility/wrun/sources/lanes/options_flow.js +115 -18
  92. package/dist/utility/wrun/sources/opra-option-lanes.util.d.ts +12 -9
  93. package/dist/utility/wrun/sources/opra-option-lanes.util.js +10 -7
  94. package/dist/utility/wrun/sources/row-lane-registry.js +10 -5
  95. package/dist/utility/wrun/sources/row-lanes/index.js +2 -0
  96. package/dist/utility/wrun/sources/row-lanes/option_contract_flow.d.ts +3 -2
  97. package/dist/utility/wrun/sources/row-lanes/option_contract_flow.js +30 -5
  98. package/dist/utility/wrun/sources/row-lanes/option_contract_state.d.ts +9 -3
  99. package/dist/utility/wrun/sources/row-lanes/option_contract_state.js +13 -5
  100. package/dist/utility/wrun/sources/row-lanes/option_prints.d.ts +25 -1
  101. package/dist/utility/wrun/sources/row-lanes/option_prints.js +161 -30
  102. package/dist/utility/wrun/sources/row-lanes/option_strike_flow.d.ts +4 -0
  103. package/dist/utility/wrun/sources/row-lanes/option_strike_flow.js +65 -0
  104. package/dist/utility/wrun/sources/row-lanes/option_strikes.d.ts +55 -1
  105. package/dist/utility/wrun/sources/row-lanes/option_strikes.js +83 -2
  106. package/dist/utility/wrun/sources/row-lanes/option_surface.d.ts +17 -1
  107. package/dist/utility/wrun/sources/row-lanes/option_surface.js +33 -2
  108. package/dist/utility/wrun/sources/wrun-poll-lane.types.d.ts +7 -1
  109. package/dist/utility/wrun/sources/wrun-poll-lanes.util.d.ts +51 -5
  110. package/dist/utility/wrun/sources/wrun-poll-lanes.util.js +136 -3
  111. package/dist/utility/wrun/sources/wrun-row-lane-first-paint.util.d.ts +42 -0
  112. package/dist/utility/wrun/sources/wrun-row-lane-first-paint.util.js +146 -0
  113. package/dist/utility/wrun/sources/wrun-row-lane.types.d.ts +25 -5
  114. package/dist/utility/wrun/sources/wrun-row-lanes.util.d.ts +111 -20
  115. package/dist/utility/wrun/sources/wrun-row-lanes.util.js +291 -48
  116. package/dist/utility/wrun/wrun-batched-marks.util.d.ts +16 -3
  117. package/dist/utility/wrun/wrun-batched-marks.util.js +30 -19
  118. package/dist/utility/wrun/wrun-batched-readout.util.d.ts +37 -9
  119. package/dist/utility/wrun/wrun-batched-readout.util.js +61 -15
  120. package/dist/utility/wrun/wrun-canvas-readout.util.d.ts +4 -0
  121. package/dist/utility/wrun/wrun-cell-capacity.leaf.d.ts +66 -0
  122. package/dist/utility/wrun/wrun-cell-capacity.leaf.js +86 -0
  123. package/dist/utility/wrun/wrun-chart-market-facts.util.d.ts +147 -9
  124. package/dist/utility/wrun/wrun-chart-market-facts.util.js +345 -11
  125. package/dist/utility/wrun/wrun-cloud-record.leaf.d.ts +27 -0
  126. package/dist/utility/wrun/wrun-cloud-record.leaf.js +71 -0
  127. package/dist/utility/wrun/wrun-cloud-record.util.d.ts +4 -21
  128. package/dist/utility/wrun/wrun-cloud-record.util.js +5 -65
  129. package/dist/utility/wrun/wrun-color-facts.util.d.ts +19 -9
  130. package/dist/utility/wrun/wrun-color-facts.util.js +24 -14
  131. package/dist/utility/wrun/wrun-color-settings.util.d.ts +22 -9
  132. package/dist/utility/wrun/wrun-color-settings.util.js +57 -23
  133. package/dist/utility/wrun/wrun-dollar-unit-port.leaf.d.ts +17 -0
  134. package/dist/utility/wrun/wrun-dollar-unit-port.leaf.js +9 -0
  135. package/dist/utility/wrun/wrun-download-meter.util.d.ts +92 -0
  136. package/dist/utility/wrun/wrun-download-meter.util.js +122 -0
  137. package/dist/utility/wrun/wrun-draft-overlay.util.d.ts +10 -3
  138. package/dist/utility/wrun/wrun-draft-overlay.util.js +63 -6
  139. package/dist/utility/wrun/wrun-frames.js +5 -5
  140. package/dist/utility/wrun/wrun-hosted-wire-caps.d.ts +2 -2
  141. package/dist/utility/wrun/wrun-hosted-wire-caps.js +11 -0
  142. package/dist/utility/wrun/wrun-hud-looks.util.d.ts +33 -17
  143. package/dist/utility/wrun/wrun-hud-looks.util.js +30 -16
  144. package/dist/utility/wrun/wrun-lane-refusal.leaf.d.ts +29 -3
  145. package/dist/utility/wrun/wrun-lane-refusal.leaf.js +33 -3
  146. package/dist/utility/wrun/wrun-lifecycle-runtime.util.d.ts +8 -6
  147. package/dist/utility/wrun/wrun-lifecycle-runtime.util.js +8 -6
  148. package/dist/utility/wrun/wrun-lifecycle.contract.d.ts +4 -2
  149. package/dist/utility/wrun/wrun-live-intake.util.d.ts +6 -2
  150. package/dist/utility/wrun/wrun-live-intake.util.js +136 -21
  151. package/dist/utility/wrun/wrun-live-tick.util.d.ts +4 -1
  152. package/dist/utility/wrun/wrun-live-tick.util.js +130 -44
  153. package/dist/utility/wrun/wrun-market-size-contract-carry.leaf.d.ts +53 -0
  154. package/dist/utility/wrun/wrun-market-size-contract-carry.leaf.js +162 -0
  155. package/dist/utility/wrun/wrun-market-size-defaults.leaf.d.ts +224 -0
  156. package/dist/utility/wrun/wrun-market-size-defaults.leaf.js +342 -0
  157. package/dist/utility/wrun/wrun-market-size-defaults.util.d.ts +88 -0
  158. package/dist/utility/wrun/wrun-market-size-defaults.util.js +471 -0
  159. package/dist/utility/wrun/wrun-opra-flow.leaf.d.ts +43 -8
  160. package/dist/utility/wrun/wrun-opra-flow.leaf.js +37 -6
  161. package/dist/utility/wrun/wrun-option-contract-flow.util.d.ts +51 -10
  162. package/dist/utility/wrun/wrun-option-contract-flow.util.js +85 -33
  163. package/dist/utility/wrun/wrun-option-prints.util.d.ts +172 -3
  164. package/dist/utility/wrun/wrun-option-prints.util.js +394 -17
  165. package/dist/utility/wrun/wrun-option-strike-flow-lane.util.d.ts +99 -0
  166. package/dist/utility/wrun/wrun-option-strike-flow-lane.util.js +218 -0
  167. package/dist/utility/wrun/wrun-option-strike-flow.util.d.ts +365 -0
  168. package/dist/utility/wrun/wrun-option-strike-flow.util.js +797 -0
  169. package/dist/utility/wrun/wrun-option-views.util.d.ts +231 -7
  170. package/dist/utility/wrun/wrun-option-views.util.js +643 -23
  171. package/dist/utility/wrun/wrun-options-chain.util.d.ts +6 -4
  172. package/dist/utility/wrun/wrun-options-chain.util.js +8 -5
  173. package/dist/utility/wrun/wrun-options-stop.util.d.ts +2 -1
  174. package/dist/utility/wrun/wrun-options-stop.util.js +3 -2
  175. package/dist/utility/wrun/wrun-overlay-drivers.util.d.ts +3 -0
  176. package/dist/utility/wrun/wrun-overlay-lifecycle.lazy.d.ts +31 -14
  177. package/dist/utility/wrun/wrun-overlay-lifecycle.lazy.js +22 -0
  178. package/dist/utility/wrun/wrun-overlay-recovery.util.d.ts +9 -1
  179. package/dist/utility/wrun/wrun-overlay-recovery.util.js +32 -3
  180. package/dist/utility/wrun/wrun-overlay-result.util.d.ts +7 -1
  181. package/dist/utility/wrun/wrun-overlay-result.util.js +2 -0
  182. package/dist/utility/wrun/wrun-overlay-run.util.d.ts +34 -6
  183. package/dist/utility/wrun/wrun-overlay-run.util.js +527 -180
  184. package/dist/utility/wrun/wrun-pack-widths.leaf.d.ts +15 -0
  185. package/dist/utility/wrun/wrun-pack-widths.leaf.js +22 -0
  186. package/dist/utility/wrun/wrun-pack.util.d.ts +13 -8
  187. package/dist/utility/wrun/wrun-pack.util.js +38 -21
  188. package/dist/utility/wrun/wrun-panel-mount.util.d.ts +4 -0
  189. package/dist/utility/wrun/wrun-panel-mount.util.js +62 -22
  190. package/dist/utility/wrun/wrun-panel-style.util.d.ts +41 -14
  191. package/dist/utility/wrun/wrun-panel-style.util.js +86 -26
  192. package/dist/utility/wrun/wrun-param-map.util.d.ts +7 -6
  193. package/dist/utility/wrun/wrun-param-map.util.js +8 -5
  194. package/dist/utility/wrun/wrun-param-values.util.d.ts +10 -2
  195. package/dist/utility/wrun/wrun-param-values.util.js +2 -0
  196. package/dist/utility/wrun/wrun-pin-spelling.util.js +19 -10
  197. package/dist/utility/wrun/wrun-prefix-lanes.util.js +2 -2
  198. package/dist/utility/wrun/wrun-refusal.util.js +17 -2
  199. package/dist/utility/wrun/wrun-script-inputs.util.d.ts +20 -0
  200. package/dist/utility/wrun/wrun-script-inputs.util.js +43 -0
  201. package/dist/utility/wrun/wrun-source-rows.util.d.ts +4 -0
  202. package/dist/utility/wrun/wrun-source-rows.util.js +92 -40
  203. package/dist/utility/wrun/wrun-tape-source.util.d.ts +133 -48
  204. package/dist/utility/wrun/wrun-tape-source.util.js +205 -62
  205. package/dist/utility/wrun/wrun-volume-profile-lane.util.d.ts +7 -5
  206. package/dist/utility/wrun/wrun-volume-profile-lane.util.js +8 -6
  207. package/dist/workers/utils/volume-profile.worker.util.d.ts +4 -1
  208. package/dist/workers/utils/volume-profile.worker.util.js +5 -2
  209. package/dist/workers/wrun/wrun-abi-host.js +3 -2
  210. package/package.json +11 -11
@@ -0,0 +1,797 @@
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 most tier buckets the nested proof walks for one read (the gateway's own limit is 15,000 points a request). */
307
+ const NESTED_PROOF_MAX_BUCKETS = 50_000;
308
+ /** Every UTC group width the gateway takes, widest first: the whole minutes that divide a day (contract 3.2: B below a
309
+ * day, or a day on the DAY tier; a width that divides a day keeps the UTC grid whole across days). */
310
+ const NESTED_UTC_WIDTHS_MS = Object.freeze(Array.from({ length: 1440 }, (_, at) => 1440 - at)
311
+ .filter((minutes) => 1440 % minutes === 0)
312
+ .map((minutes) => minutes * MINUTE_MS));
313
+ /**
314
+ * The widest UTC groups a read of `[fromMs, toMs)` at a tier may be summed or picked to so that its answer lands on the
315
+ * chart exactly as the tier's buckets do, where the chart's bars themselves are no grouping the gateway draws (an RTH
316
+ * CME chart's hourly bars open at 13:30Z; a daily bar takes no session pick): the widest whole-minute width that divides
317
+ * a day, divides the host bar (or a day, for a bar of a day or longer), is a multiple of the tier and is a day only on
318
+ * the DAY tier, the window on its boundaries, such that every tier bucket's group opens on a bucket that lands on the
319
+ * bucket's own host bar (`wrunHostBarOf` over the chart's bar grid), or both on none (a Globex night on an RTH chart).
320
+ * One row per group, a few per host bar, never a row that straddles two host bars or a session's edge, so a consumer
321
+ * that lands each host bar on its newest group row lands it where today's buckets land it. Undefined when no width
322
+ * holds or the window cannot be walked (off the tier's grid, more than `NESTED_PROOF_MAX_BUCKETS` buckets). The one
323
+ * proof `options_flow` and the per-bar pick read (option-print-agg-scope.worker.util `wrunOptionsFlowBars`,
324
+ * option-strikes.worker.util `optionLaneBarGrouping`); `wrunOptionFlowGrouping` is the exact decider beside it.
325
+ */
326
+ export function wrunOptionNestedUtcBars(args) {
327
+ const { barMs, barGrid, tierMs, fromMs, toMs } = args;
328
+ if (barMs === undefined || !(barMs > 0) || !(tierMs > 0) || !Number.isFinite(fromMs) || !(toMs > fromMs)) {
329
+ return undefined;
330
+ }
331
+ if (fromMs % tierMs !== 0 || toMs % tierMs !== 0)
332
+ return undefined;
333
+ const count = (toMs - fromMs) / tierMs;
334
+ if (count > NESTED_PROOF_MAX_BUCKETS)
335
+ return undefined;
336
+ const host = new Array(count);
337
+ for (let at = 0; at < count; at += 1)
338
+ host[at] = wrunHostBarOf(fromMs + at * tierMs, barMs, barGrid);
339
+ /** Whether every bucket's group (opening at `ts - ts % width`, a bucket of the window) lands where the bucket does. */
340
+ const nests = (width) => {
341
+ for (let at = 0; at < count; at += 1) {
342
+ const ts = fromMs + at * tierMs;
343
+ const slot = (ts - (ts % width) - fromMs) / tierMs;
344
+ if (!(slot >= 0 && slot <= at && Number.isInteger(slot)) || host[slot] !== host[at])
345
+ return false;
346
+ }
347
+ return true;
348
+ };
349
+ for (const width of NESTED_UTC_WIDTHS_MS) {
350
+ if (width % tierMs !== 0 || (width === DAY_MS && tierMs !== DAY_MS))
351
+ continue;
352
+ if (barMs < DAY_MS && barMs % width !== 0)
353
+ continue;
354
+ if (fromMs % width !== 0 || toMs % width !== 0)
355
+ continue;
356
+ if (nests(width))
357
+ return { barSeconds: width / 1000, barAnchor: WRUN_OPTION_READ_ENUM.anchorUtc };
358
+ }
359
+ return undefined;
360
+ }
361
+ /** The trade-date group a bucket stamped `ts` sums into under the gateway's session (contract 3.4): on RTH the New York
362
+ * date's 09:30 open for a bucket inside the cash session (null outside it), on UTC the UTC date's 00:00Z. */
363
+ export function wrunOptionFlowSessionStampMs(ts, barAnchor) {
364
+ if (!Number.isFinite(ts))
365
+ return null;
366
+ if (barAnchor === WRUN_OPTION_READ_ENUM.anchorUsEquityRth)
367
+ return usEquityAnchoredBucketStartMs(ts, DAY_MS);
368
+ return ts - (((ts % DAY_MS) + DAY_MS) % DAY_MS);
369
+ }
370
+ /**
371
+ * The stamp of the group a bucket stamped `ts` sums into, on the browser's side of a grouping (the fold's): the
372
+ * gateway's bar or session rule (`bars`, `session`), the chart's own bar, or a trade date of the clock stamped at its
373
+ * first instant (`host` with a session span); null for a bucket no group holds (off the cash session on RTH).
374
+ */
375
+ export function wrunOptionFlowGroupStampMs(ts, grouping, bars) {
376
+ if (!Number.isFinite(ts))
377
+ return null;
378
+ switch (grouping.kind) {
379
+ case 'bars': {
380
+ const barMs = grouping.barSeconds * 1000;
381
+ return grouping.barAnchor === WRUN_OPTION_READ_ENUM.anchorUsEquityRth
382
+ ? usEquityAnchoredBucketStartMs(ts, barMs)
383
+ : ts - (((ts % barMs) + barMs) % barMs);
384
+ }
385
+ case 'session':
386
+ return wrunOptionFlowSessionStampMs(ts, grouping.barAnchor);
387
+ case 'host': {
388
+ if (grouping.session) {
389
+ const start = optionTradeDayStartMsByClock(bars.clock, optionTradeDayByClock(bars.clock, ts));
390
+ return Number.isFinite(start) ? start : null;
391
+ }
392
+ return bars.barMs === undefined ? ts : wrunHostBarOf(ts, bars.barMs, bars.barGrid);
393
+ }
394
+ }
395
+ }
396
+ /**
397
+ * The window a session grouping reads: from the first instant of the trade date holding `fromMs` to the first instant
398
+ * of the trade date after the one holding `toMs - 1` (whole sessions, so a session's row sums every bucket of it
399
+ * whichever asked bars hold it), on the clock (the New York date for an RTH session: its midnights sit outside the
400
+ * cash session, a boundary the gateway takes).
401
+ */
402
+ export function wrunOptionFlowSessionWindow(fromMs, toMs, clock) {
403
+ const first = optionTradeDayByClock(clock, fromMs);
404
+ const last = optionTradeDayByClock(clock, toMs - 1);
405
+ if (!Number.isFinite(first) || !Number.isFinite(last))
406
+ return { fromMs, toMs };
407
+ let from = optionTradeDayStartMsByClock(clock, first);
408
+ let to = Number.NaN;
409
+ for (let day = last + 1; day <= last + 3 && !Number.isFinite(to); day += 1) {
410
+ to = optionTradeDayStartMsByClock(clock, day);
411
+ }
412
+ if (!Number.isFinite(from))
413
+ from = fromMs;
414
+ return { fromMs: Math.min(from, fromMs), toMs: Number.isFinite(to) ? Math.max(to, toMs) : toMs };
415
+ }
416
+ /**
417
+ * The part of an ask `[fromMs, toMs)` that `history` "today" reads (both flow classes' worker twins): from the first
418
+ * host bar ending after today's first instant, else from that instant on the tier's grid, to the ask's end. Today's
419
+ * first instant is the request's (`todayFromMs`, wrun-option-contract-flow.util `WRUN_OPTION_FLOW_TODAY_FIELD`): the
420
+ * trade date of the chart's newest bar on the chain's venue clock, which the K control names off the chart's bars
421
+ * (option-flow-bars.util `optionFlowTodayFields`), so a weekend, a holiday or a morning before the first print reads
422
+ * the last session the chart shows. Null when the ask holds nothing of today (an ask of older bars: quiet), and when
423
+ * the request names no today: no clock stands in for the chart's bars (a server clock reads Saturday on a Saturday).
424
+ */
425
+ export function wrunOptionFlowTodayWindow(args) {
426
+ const { toMs, todayFromMs, tierMs, barMs, barGrid } = args;
427
+ if (todayFromMs === undefined || !Number.isFinite(todayFromMs) || !(tierMs > 0))
428
+ return null;
429
+ const first = barMs === undefined
430
+ ? undefined
431
+ : wrunOptionFlowHostBars(args.fromMs, toMs, barMs, barGrid).find((open) => open + barMs > todayFromMs);
432
+ const fromMs = Math.max(args.fromMs, first ?? Math.ceil(todayFromMs / tierMs) * tierMs);
433
+ return toMs > fromMs ? { fromMs, toMs } : null;
434
+ }
435
+ /** The grouping's own fields: its bars, or its session on its anchor. */
436
+ export function wrunOptionFlowGroupingShape(grouping) {
437
+ return grouping.kind === 'bars'
438
+ ? { barSeconds: grouping.barSeconds, barAnchor: grouping.barAnchor }
439
+ : { span: WRUN_OPTION_READ_ENUM.spanSession, barAnchor: grouping.barAnchor };
440
+ }
441
+ /** The `expiryClass` an `expiries` word asks (0DTE or after today), else none. */
442
+ export function wrunOptionFlowExpiryClassOf(expiries) {
443
+ const read = wrunOptionStrikeFlowExpiriesOf(expiries);
444
+ if (read?.kind === '0dte')
445
+ return WRUN_OPTION_READ_ENUM.expiryZeroDte;
446
+ if (read?.kind === 'after_today')
447
+ return WRUN_OPTION_READ_ENUM.expiryAfterToday;
448
+ return undefined;
449
+ }
450
+ /**
451
+ * The `optionRead` of a grouped strike flow read (contract 3.1 and 6.4): the grouping, the expiry class, and the knobs
452
+ * the group's scope takes (STRIKE: the window, the strike rows, the volume floor, the split, the fold; EXPIRY: the
453
+ * nearest expiries and the volume floor; EXPIRY_STRIKE: the nearest expiries, the window, the strike rows and the
454
+ * volume floor). The planner refuses every other combination by name, so each field the read names is taken.
455
+ */
456
+ export function wrunOptionStrikeFlowOptionRead(knobs, grouping) {
457
+ const expiries = wrunOptionStrikeFlowExpiriesOf(knobs.expiries);
458
+ const expiryClass = wrunOptionFlowExpiryClassOf(knobs.expiries);
459
+ const strikes = knobs.group !== 'expiry';
460
+ return {
461
+ ...wrunOptionFlowGroupingShape(grouping),
462
+ ...(expiryClass !== undefined ? { expiryClass } : {}),
463
+ ...(expiries?.kind === 'nearest' && knobs.group !== 'strike' ? { nearestExpiries: expiries.count } : {}),
464
+ ...(strikes && knobs.strikeWindowPct !== undefined ? { strikeWindowPct: knobs.strikeWindowPct } : {}),
465
+ ...(strikes && knobs.strikeRows !== undefined ? { strikeRows: knobs.strikeRows } : {}),
466
+ ...(knobs.minVolume !== undefined ? { minVolume: knobs.minVolume } : {}),
467
+ ...(knobs.group === 'strike' && knobs.splitDte ? { splitDte: true } : {}),
468
+ ...(knobs.group === 'strike' && knobs.foldTypes ? { foldTypes: true } : {}),
469
+ };
470
+ }
471
+ /** The tiers the gateway groups a CONTRACT read at (contract 6.3: the contract tiers at 1m and 5m, the per-contract
472
+ * 30-minute view); an ask at any other tier (the hour, the day) is read as today. */
473
+ export const WRUN_OPTION_CONTRACT_GROUPED_TIERS = Object.freeze(['1m', '5m', '30m']);
474
+ /** The per-contract 30-minute view a session-span CONTRACT read asks (contract 6.3: `option_print_agg_bar_30m`, kept 30
475
+ * days). */
476
+ export const WRUN_OPTION_CONTRACT_SESSION_TIER = Object.freeze({
477
+ key: '30m',
478
+ ms: HALF_HOUR_MS,
479
+ retentionMs: 30 * DAY_MS,
480
+ });
481
+ /** The 30-minute tier of a strike flow group: its coarsest (kept, or 30 days on `expiry_strike`). */
482
+ export function wrunOptionStrikeFlowSessionTierOf(group) {
483
+ const tiers = WRUN_OPTION_STRIKE_FLOW_TIERS[group];
484
+ return tiers[tiers.length - 1];
485
+ }
486
+ /**
487
+ * The tier a grouped read asks (contract 6.8: "span session reads 30m"). A session grouping reads `sessionTier`, the
488
+ * 30-minute view that holds each session whole at the fewest rows (one SPY session, contract section 1: STRIKE 6,564
489
+ * rows at 30m against 23,271 at 5m; CONTRACT 30,239 against 76,740), where that view still holds the window's start
490
+ * (`retentionMs` back from `nowMs`). Any other grouping, and a window older than the view keeps, reads the ask's own
491
+ * tier. A session row is stamped by its anchor whatever tier sums it, so it lands where the ask's tier's would.
492
+ */
493
+ export function wrunOptionFlowGroupedTier(grouping, askTier, sessionTier, fromMs, nowMs) {
494
+ if (grouping.kind !== 'session')
495
+ return askTier;
496
+ const retention = sessionTier.retentionMs;
497
+ return retention === undefined || fromMs >= nowMs - retention ? sessionTier : askTier;
498
+ }
499
+ /**
500
+ * The `optionRead` of a grouped CONTRACT read (contract 3.1 and 6.4: steps 1, 2 and the premium floor of 7): the
501
+ * grouping, the 0DTE class of `expiries` "0dte", and `minBarPremium` from `min_premium` (a contract's group premium, the
502
+ * four sides' sum). Every other knob of `option_contract_flow` stays the fold's, as today.
503
+ */
504
+ export function wrunOptionContractFlowOptionRead(acquisition, grouping) {
505
+ return {
506
+ ...wrunOptionFlowGroupingShape(grouping),
507
+ ...(acquisition.expiries === '0dte' ? { expiryClass: WRUN_OPTION_READ_ENUM.expiryZeroDte } : {}),
508
+ ...(acquisition.minPremium !== undefined ? { minBarPremium: acquisition.minPremium } : {}),
509
+ };
510
+ }
511
+ /**
512
+ * Whether a CONTRACT row is a "0dte" row on today's read of `option_contract_flow` (the grouped read classes rows
513
+ * itself): its expiry falls on the trade date of its bucket on its chain's venue clock (option-trade-date.util, the data
514
+ * plane's `option_venue_clocks`), read at the bucket's middle so a UTC day bucket reads its own session's date.
515
+ */
516
+ export function wrunOptionContractFlowRowIsZeroDte(row, tierMs, chain) {
517
+ const middle = row.bucketMs + Math.floor(Math.max(0, tierMs) / 2);
518
+ return optionExpiresOnTradeDay(chain, row.raw[WRUN_OPTION_CONTRACT_FLOW_RAW.expiry], middle);
519
+ }
520
+ /** A value of a row: a finite number, else 0 (an unset sum). */
521
+ function sumOrZero(value) {
522
+ return typeof value === 'number' && Number.isFinite(value) ? value : 0;
523
+ }
524
+ /** The side a row's option type reads: CALL +1, PUT -1, any other (UNKNOWN, folded) 0. */
525
+ function sideOfType(optionType) {
526
+ if (optionType === WRUN_OPTION_READ_ENUM.call || optionType === 'CALL')
527
+ return 1;
528
+ if (optionType === WRUN_OPTION_READ_ENUM.put || optionType === 'PUT')
529
+ return -1;
530
+ return 0;
531
+ }
532
+ /**
533
+ * One grouped STRIKE, EXPIRY or EXPIRY_STRIKE row as the class's tuple (contract 6.5): `expiry_ms` 0 on a strike row,
534
+ * `strike` 0 on an expiry row, `side_cp` from the series' option type (0 with `fold_types`), `dte_class` from
535
+ * `dte_bucket` (ZERO 1, AFTER_ZERO 2, unset 0), every unset value 0. A row of another scope is dropped.
536
+ */
537
+ export function wrunOptionStrikeFlowTupleOf(record, group) {
538
+ if (record.scope !== WRUN_OPTION_STRIKE_FLOW_SCOPE[group].id)
539
+ return 'scope';
540
+ const strike = group === 'expiry' ? 0 : sumOrZero(record.strike);
541
+ const expiry = group === 'strike' ? 0 : sumOrZero(record.expiryMs);
542
+ if ((group !== 'expiry' && !(strike > 0)) || (group !== 'strike' && !(expiry > 0)))
543
+ return 'value';
544
+ const dte = record.dteBucket === WRUN_OPTION_READ_ENUM.dteZero
545
+ ? WRUN_OPTION_STRIKE_FLOW_DTE_CLASS.zero
546
+ : record.dteBucket === WRUN_OPTION_READ_ENUM.dteAfterZero
547
+ ? WRUN_OPTION_STRIKE_FLOW_DTE_CLASS.later
548
+ : WRUN_OPTION_STRIKE_FLOW_DTE_CLASS.whole;
549
+ return [
550
+ expiry,
551
+ strike,
552
+ sideOfType(record.optionType),
553
+ dte,
554
+ sumOrZero(record.volAsk),
555
+ sumOrZero(record.volBid),
556
+ sumOrZero(record.volMid),
557
+ sumOrZero(record.volNone),
558
+ sumOrZero(record.volAboveAsk),
559
+ sumOrZero(record.volBelowBid),
560
+ sumOrZero(record.premAsk),
561
+ sumOrZero(record.premBid),
562
+ sumOrZero(record.premMid),
563
+ sumOrZero(record.premNone),
564
+ 0,
565
+ ];
566
+ }
567
+ /** The flow columns a group key sums, in the tuple's order (vol_ask .. prem_none). */
568
+ const FLOW_KEYS = [
569
+ 'volAsk',
570
+ 'volBid',
571
+ 'volMid',
572
+ 'volNone',
573
+ 'volAboveAsk',
574
+ 'volBelowBid',
575
+ 'premAsk',
576
+ 'premBid',
577
+ 'premMid',
578
+ 'premNone',
579
+ ];
580
+ /** The columns `fold_types` crosses on a put (contract 6.4 step 8): a put's bid is the bullish side's ask. */
581
+ const PUT_FOLDED = Object.freeze({
582
+ volAsk: 'volBid',
583
+ volBid: 'volAsk',
584
+ volMid: 'volMid',
585
+ volNone: 'volNone',
586
+ volAboveAsk: 'volBelowBid',
587
+ volBelowBid: 'volAboveAsk',
588
+ premAsk: 'premBid',
589
+ premBid: 'premAsk',
590
+ premMid: 'premMid',
591
+ premNone: 'premNone',
592
+ });
593
+ function emptySums() {
594
+ return {
595
+ volAsk: 0,
596
+ volBid: 0,
597
+ volMid: 0,
598
+ volNone: 0,
599
+ volAboveAsk: 0,
600
+ volBelowBid: 0,
601
+ premAsk: 0,
602
+ premBid: 0,
603
+ premMid: 0,
604
+ premNone: 0,
605
+ };
606
+ }
607
+ /**
608
+ * 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
609
+ * gateway's own (tsdb-gateway `option_print_agg_group.go`):
610
+ * 1. the expiry class per row: 0DTE when the contract expires on the trade date of the row's bucket (its middle) on the
611
+ * chain's venue clock (`zero`, computed by the caller: `wrunOptionStrikeFlowZeroDte`); `expiries` "0dte" keeps those,
612
+ * "after_today" the others;
613
+ * 2. the sums per key: (side, strike, class) for the strike group, (side, expiry) for the expiry group, (side, strike,
614
+ * expiry) for both;
615
+ * 3. the spot: the group's sum_spot_size over its size_priced (every kept row: all strikes, expiries and sides), unset
616
+ * when nothing was priced;
617
+ * 4. `nearest:N` (expiry and expiry_strike): the N smallest distinct expiries of the group;
618
+ * 5. `strike_window_pct` (strike and expiry_strike): the strikes within that many percent of the spot;
619
+ * 6. `strike_rows` R: the R distinct strikes nearest the spot after the window (ties: the lower strike); 5 and 6
620
+ * skipped when the spot is unset or not above 0;
621
+ * 7. `min_volume`: a key's contracts at least the floor (on the strike group the side's strike over both classes);
622
+ * 8. the shape: `split_dte` one row per class part, else the parts summed; `fold_types` one row per strike, calls and
623
+ * puts summed with the put's sides crossed (the bullish side in the ask columns).
624
+ * Sorted by expiry, strike, side (calls first), class.
625
+ */
626
+ export function foldWrunOptionStrikeFlowGroup(rows, knobs) {
627
+ const expiries = wrunOptionStrikeFlowExpiriesOf(knobs.expiries) ?? { kind: 'all' };
628
+ const group = knobs.group;
629
+ const keys = new Map();
630
+ let spotSize = 0;
631
+ let sizePriced = 0;
632
+ for (const row of rows) {
633
+ if (expiries.kind === '0dte' && !row.zero)
634
+ continue;
635
+ if (expiries.kind === 'after_today' && row.zero)
636
+ continue;
637
+ spotSize += row.sumSpotSize;
638
+ sizePriced += row.sizePriced;
639
+ const strike = group === 'expiry' ? 0 : row.strike;
640
+ const expiry = group === 'strike' ? 0 : row.expiryMs;
641
+ const zero = group === 'strike' ? row.zero : false;
642
+ const key = `${row.side}|${strike}|${expiry}|${zero ? 1 : 0}`;
643
+ let sum = keys.get(key);
644
+ if (sum === undefined) {
645
+ sum = { side: row.side, strike, expiry, zero, sums: emptySums(), sumSize: 0 };
646
+ keys.set(key, sum);
647
+ }
648
+ for (const column of FLOW_KEYS)
649
+ sum.sums[column] += row[column];
650
+ sum.sumSize += row.sumSize;
651
+ }
652
+ let kept = [...keys.values()];
653
+ const spot = sizePriced > 0 ? spotSize / sizePriced : undefined;
654
+ const judged = spot !== undefined && spot > 0;
655
+ // Step 7's measure on the strike group: the side's strike over both class parts, read before the strike cuts.
656
+ const strikeSize = new Map();
657
+ if (group === 'strike') {
658
+ for (const sum of kept) {
659
+ const key = `${sum.side}|${sum.strike}`;
660
+ strikeSize.set(key, (strikeSize.get(key) ?? 0) + sum.sumSize);
661
+ }
662
+ }
663
+ if (expiries.kind === 'nearest' && group !== 'strike') {
664
+ const nearest = new Set([...new Set(kept.map((sum) => sum.expiry))].sort((a, b) => a - b).slice(0, expiries.count));
665
+ kept = kept.filter((sum) => nearest.has(sum.expiry));
666
+ }
667
+ if (group !== 'expiry' && judged) {
668
+ if (knobs.strikeWindowPct !== undefined) {
669
+ const reach = (spot * knobs.strikeWindowPct) / 100;
670
+ kept = kept.filter((sum) => Math.abs(sum.strike - spot) <= reach);
671
+ }
672
+ if (knobs.strikeRows !== undefined) {
673
+ const nearest = new Set([...new Set(kept.map((sum) => sum.strike))]
674
+ .sort((a, b) => Math.abs(a - spot) - Math.abs(b - spot) || a - b)
675
+ .slice(0, knobs.strikeRows));
676
+ kept = kept.filter((sum) => nearest.has(sum.strike));
677
+ }
678
+ }
679
+ if (knobs.minVolume !== undefined) {
680
+ const floor = knobs.minVolume;
681
+ kept = kept.filter((sum) => group === 'strike' ? (strikeSize.get(`${sum.side}|${sum.strike}`) ?? 0) >= floor : sum.sumSize >= floor);
682
+ }
683
+ const shaped = new Map();
684
+ const C = WRUN_OPTION_STRIKE_FLOW_COLUMN;
685
+ for (const sum of kept) {
686
+ const fold = group === 'strike' && knobs.foldTypes === true;
687
+ const split = group === 'strike' && knobs.splitDte === true;
688
+ const side = fold ? 0 : sum.side;
689
+ const dte = split
690
+ ? sum.zero
691
+ ? WRUN_OPTION_STRIKE_FLOW_DTE_CLASS.zero
692
+ : WRUN_OPTION_STRIKE_FLOW_DTE_CLASS.later
693
+ : 0;
694
+ const key = `${side}|${sum.strike}|${sum.expiry}|${dte}`;
695
+ let tuple = shaped.get(key);
696
+ if (tuple === undefined) {
697
+ tuple = new Array(WRUN_OPTION_STRIKE_FLOW_WIDTH).fill(0);
698
+ tuple[C.expiry] = sum.expiry;
699
+ tuple[C.strike] = sum.strike;
700
+ tuple[C.side] = side;
701
+ tuple[C.dteClass] = dte;
702
+ shaped.set(key, tuple);
703
+ }
704
+ FLOW_KEYS.forEach((column, at) => {
705
+ const from = fold && sum.side < 0 ? PUT_FOLDED[column] : column;
706
+ tuple[C.volAsk + at] += sum.sums[from];
707
+ });
708
+ }
709
+ return [...shaped.values()].sort(compareWrunOptionStrikeFlowTuples);
710
+ }
711
+ /** Whether a CONTRACT row is a 0DTE row: its expiry trades on the trade date of its bucket's middle (a UTC day bucket
712
+ * reads its own session's date) on the chain's venue clock. */
713
+ export function wrunOptionStrikeFlowZeroDte(row, tierMs, clock) {
714
+ const day = optionTradeDayByClock(clock, row.expiryMs);
715
+ return (Number.isFinite(day) && day === optionTradeDayByClock(clock, row.bucketMs + Math.floor(Math.max(0, tierMs) / 2)));
716
+ }
717
+ /**
718
+ * Today's ask for one strike flow ask's host bars, before any fetch, as the `option_contract_flow` lane plans its own
719
+ * (the read the class is folded from while the gateway does not group it): each bar's coarsest contract tier that fits,
720
+ * retains and already serves it (`WRUN_OPTION_PRINT_AGG_TIERS`, the bars' session grid), and the NEWEST bars whose
721
+ * projected contract rows (`wrunOptionContractFlowBarRows`, the chain's plane) fit the source answer budget, counted
722
+ * from the clock: the bars after the ask (a later ask's) are counted first, so every ask of one window keeps the same
723
+ * bars. A newest bar that cannot fit alone is skipped (a forming day read from minutes); from the first bar that fits,
724
+ * a bar that would pass the budget stops the walk. The kept bars are read per run of one tier (`reads`); every asked
725
+ * bar outside them is partial. `newerBarOpens` are the host bars after the ask, up to the clock.
726
+ */
727
+ export function wrunOptionStrikeFlowFoldPlan(args) {
728
+ const { barOpens, barMs, barGrid, nowMs } = args;
729
+ const all = [...new Set([...barOpens, ...args.newerBarOpens])].sort((a, b) => a - b);
730
+ const tiers = wrunBarTiers({
731
+ tiers: WRUN_OPTION_PRINT_AGG_TIERS,
732
+ barOpens: all,
733
+ barMs,
734
+ nowMs,
735
+ choice: 'coarsest',
736
+ sessionGrid: barGrid ?? null,
737
+ });
738
+ // The per-contract read weighs as `option_contract_flow`'s raw rows do: the same read, the same budget.
739
+ const budget = kScriptSourceAnswerRows(WRUN_OPTION_CONTRACT_FLOW_RAW_WIDTH);
740
+ let rows = 0;
741
+ let keptFromMs = Number.POSITIVE_INFINITY;
742
+ let keptToMs = Number.NEGATIVE_INFINITY;
743
+ for (let at = tiers.length - 1; at >= 0; at -= 1) {
744
+ const bar = tiers[at];
745
+ if (bar.partial || bar.tier === undefined) {
746
+ if (keptToMs !== Number.NEGATIVE_INFINITY)
747
+ break;
748
+ continue;
749
+ }
750
+ const span = bar.span ?? wrunHostBarSpanOf(bar.barOpenMs, barMs, barGrid ?? null);
751
+ const projected = wrunOptionContractFlowBarRows({ openMs: span.fromMs, endMs: span.toMs, tier: bar.tier }, nowMs, args.acquisition);
752
+ const barRows = Number.isFinite(projected) && projected > 0 ? projected : 0;
753
+ if (keptToMs === Number.NEGATIVE_INFINITY && barRows > budget)
754
+ continue;
755
+ if (rows + barRows > budget)
756
+ break;
757
+ rows += barRows;
758
+ keptFromMs = bar.barOpenMs;
759
+ if (keptToMs === Number.NEGATIVE_INFINITY)
760
+ keptToMs = bar.barOpenMs;
761
+ }
762
+ const asked = new Set(barOpens);
763
+ const keptBars = tiers.filter((bar) => asked.has(bar.barOpenMs) && !bar.partial && bar.barOpenMs >= keptFromMs && bar.barOpenMs <= keptToMs);
764
+ const keptSet = new Set(keptBars.map((bar) => bar.barOpenMs));
765
+ return {
766
+ reads: wrunTierSegments(keptBars, barMs),
767
+ partialBars: barOpens.filter((open) => !keptSet.has(open)),
768
+ keptFromMs,
769
+ keptToMs,
770
+ };
771
+ }
772
+ /** The host bars `[fromMs, toMs)` holds on the chart's grid, ascending (`liveBucketStartsInRange` over the grid). */
773
+ export function wrunOptionFlowHostBars(fromMs, toMs, barMs, barGrid) {
774
+ if (!(toMs > fromMs) || !(barMs > 0))
775
+ return [];
776
+ return liveBucketStartsInRange(fromMs, toMs - 1, barMs, barGrid ?? null).filter((open) => open < toMs);
777
+ }
778
+ // ---------------------------------------------------------------------------
779
+ // The answer: packed blocks (the lane's fold of a host bar is the lane module's).
780
+ // ---------------------------------------------------------------------------
781
+ /** A stamp's tuples packed as the worker hands them over: one Float64Array of `count x WIDTH` values. */
782
+ export function packWrunOptionStrikeFlowTuples(tuples) {
783
+ const block = new Float64Array(tuples.length * WRUN_OPTION_STRIKE_FLOW_WIDTH);
784
+ let at = 0;
785
+ for (const tuple of tuples) {
786
+ for (let column = 0; column < WRUN_OPTION_STRIKE_FLOW_WIDTH; column += 1)
787
+ block[at + column] = tuple[column];
788
+ at += WRUN_OPTION_STRIKE_FLOW_WIDTH;
789
+ }
790
+ return block;
791
+ }
792
+ /** The marker of a partial bar holding no tuple (every value 0, bit 14 of `present`). */
793
+ export function wrunOptionStrikeFlowPartialMarker() {
794
+ return wrunPartialMarkerTuple(WRUN_OPTION_STRIKE_FLOW_WIDTH);
795
+ }
796
+ /** The bytes one answered tuple weighs in every estimate of a source answer. */
797
+ export const WRUN_OPTION_STRIKE_FLOW_TUPLE_BYTES = WRUN_OPTION_STRIKE_FLOW_WIDTH * KSCRIPT_SOURCE_CELL_BYTES;