@orangecharts/wrun-chart-host 0.19.0 → 0.20.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 (55) hide show
  1. package/README.md +2 -0
  2. package/dist/index.d.ts +1 -0
  3. package/dist/index.js +1 -0
  4. package/dist/settings-templates/frvp-fields.js +9 -3
  5. package/dist/settings-templates/index.d.ts +36 -3
  6. package/dist/settings-templates/index.js +111 -27
  7. package/dist/settings-templates/indicator-fields.d.ts +11 -0
  8. package/dist/settings-templates/indicator-fields.js +5 -4
  9. package/dist/settings-templates/market-bound.d.ts +93 -19
  10. package/dist/settings-templates/market-bound.js +235 -30
  11. package/dist/settings-templates/tool-rules.d.ts +197 -18
  12. package/dist/settings-templates/tool-rules.js +98 -4
  13. package/dist/settings-templates/tool-tables.generated.d.ts +2 -0
  14. package/dist/settings-templates/tool-tables.generated.js +194 -11
  15. package/dist/utility/chart/calendar-interval.util.d.ts +7 -0
  16. package/dist/utility/chart/calendar-interval.util.js +9 -0
  17. package/dist/utility/chart/index-mode.util.d.ts +11 -0
  18. package/dist/utility/chart/index-mode.util.js +24 -0
  19. package/dist/utility/chart/indicator-run-interval.util.d.ts +7 -3
  20. package/dist/utility/chart/indicator-run-interval.util.js +16 -5
  21. package/dist/utility/chart/market-session-schedule.util.d.ts +2 -0
  22. package/dist/utility/chart/market-session-schedule.util.js +2 -0
  23. package/dist/utility/chart/run-interval-warmup.leaf.d.ts +16 -1
  24. package/dist/utility/chart/run-interval-warmup.leaf.js +28 -2
  25. package/dist/utility/options/option-contract-market.leaf.d.ts +2 -0
  26. package/dist/utility/options/option-contract-market.leaf.js +21 -0
  27. package/dist/utility/options/option-trade-units.util.d.ts +35 -5
  28. package/dist/utility/options/option-trade-units.util.js +31 -5
  29. package/dist/utility/wrun/wrun-chart-market-facts.util.js +3 -3
  30. package/dist/utility/wrun/wrun-color-settings.util.d.ts +2 -13
  31. package/dist/utility/wrun/wrun-color-settings.util.js +3 -29
  32. package/dist/utility/wrun/wrun-lane-warmup.util.d.ts +1 -1
  33. package/dist/utility/wrun/wrun-lane-warmup.util.js +8 -3
  34. package/dist/utility/wrun/wrun-live-intake.util.js +13 -6
  35. package/dist/utility/wrun/wrun-live-tick.util.js +35 -18
  36. package/dist/utility/wrun/wrun-market-size-defaults.leaf.d.ts +34 -1
  37. package/dist/utility/wrun/wrun-market-size-defaults.leaf.js +57 -0
  38. package/dist/utility/wrun/wrun-market-size-defaults.util.d.ts +76 -13
  39. package/dist/utility/wrun/wrun-market-size-defaults.util.js +286 -45
  40. package/dist/utility/wrun/wrun-market-size-rank.leaf.d.ts +75 -0
  41. package/dist/utility/wrun/wrun-market-size-rank.leaf.js +154 -0
  42. package/dist/utility/wrun/wrun-overlay-run.util.js +124 -21
  43. package/dist/utility/wrun/wrun-param-values.util.d.ts +2 -1
  44. package/dist/utility/wrun/wrun-param-values.util.js +3 -9
  45. package/dist/utility/wrun/wrun-row-scalars.leaf.d.ts +30 -0
  46. package/dist/utility/wrun/wrun-row-scalars.leaf.js +73 -0
  47. package/dist/utility/wrun/wrun-run-health.util.d.ts +24 -2
  48. package/dist/utility/wrun/wrun-run-health.util.js +39 -7
  49. package/dist/utility/wrun/wrun-run-interval-session.util.d.ts +18 -0
  50. package/dist/utility/wrun/wrun-run-interval-session.util.js +25 -0
  51. package/dist/utility/wrun/wrun-run-interval.util.d.ts +52 -5
  52. package/dist/utility/wrun/wrun-run-interval.util.js +88 -7
  53. package/dist/utility/wrun/wrun-script-inputs.util.d.ts +4 -7
  54. package/dist/utility/wrun/wrun-script-inputs.util.js +6 -33
  55. package/package.json +1 -1
@@ -68,12 +68,13 @@ import { normalizeTransformations, selfTransformationToken } from '../common/tra
68
68
  import { wrunChartIntervalMsOf } from './wrun-chart-context.util.js';
69
69
  import { warmWrunMarketDollarFacts, warmWrunMarketStoredUnit, wrunChartSizeUnit, wrunMarketDollarUnit, wrunMarketStoredUnitDollars, } from './wrun-chart-market-facts.util.js';
70
70
  import { tradesCmeProductRoot } from '../../kscript-data/controls/live-trades-merge.util.js';
71
- import { isWrunMarketScaledRow, wrunCarriedDollarValue, wrunCarryKeepsRawValue, wrunMarketContractsVerdict, wrunMarketDefaultWithinRow, wrunMarketOptionVerdict, wrunMarketScaledFamilies, wrunMarketScaledParamsOf, wrunMarketScaledRulesOfSheet, wrunMarketSizeVerdict, } from './wrun-market-size-defaults.leaf.js';
71
+ import { isWrunMarketScaledRow, wrunMarketScaledRowChanged, wrunCarriedDollarValue, wrunCarryKeepsRawValue, wrunMarketContractsVerdict, wrunMarketDefaultWithinRow, wrunMarketOptionVerdict, wrunMarketScaledFamilies, wrunMarketScaledParamsOf, wrunMarketScaledRulesOfSheet, wrunMarketSizeVerdict, wrunTimesDefaultOverChosenBase, } from './wrun-market-size-defaults.leaf.js';
72
72
  import { WRUN_CONTRACT_CARRY_PENDING, wrunContractCarryPatch, wrunContractCarrySettles, wrunPendingContractCarries, } from './wrun-market-size-contract-carry.leaf.js';
73
+ import { wrunRankedCutoffs, wrunTapeOrderSizes, wrunTapeRankedParamsOf, } from './wrun-market-size-rank.leaf.js';
73
74
  import { wrunChartMarketIdentity } from './wrun-overlay-drivers.util.js';
74
75
  import { wrunRegistryRefOf } from './wrun-overlay-identity.util.js';
75
76
  import { wrunTapePerOrder } from './wrun-tape-per-order.util.js';
76
- import { wrunRowValue, wrunRowValuesEqual, wrunValuesEqual, } from './wrun-script-inputs.util.js';
77
+ import { wrunRowValue, wrunValuesEqual } from './wrun-script-inputs.util.js';
77
78
  import { wrunChartCandleRows } from './wrun-source-rows.util.js';
78
79
  function isRecord(value) {
79
80
  return value !== null && typeof value === 'object' && !Array.isArray(value);
@@ -82,19 +83,9 @@ function isRecord(value) {
82
83
  function withPatch(settings, patch) {
83
84
  return { ...(isRecord(settings) ? settings : {}), ...(patch ?? {}) };
84
85
  }
85
- /**
86
- * Whether a market-scaled row holds a value the user chose (the market defaults never move it): a value off its row's
87
- * default (the settings panel's reset test, `wrunRowValuesEqual` over `wrunRowValue`), or the value a carry priced into
88
- * it (`carriedValue`, C-DOLLAR), which counts as chosen even where it equals the row's default: a 0.5.0 Min size of
89
- * 5,000 Binance delivery contracts of $100 carries $500,000, the sheet's default, and must not follow the next market's
90
- * default. Pure.
91
- */
92
- export function wrunMarketScaledRowChanged(record, row) {
93
- const value = wrunRowValue(record, row);
94
- if (!wrunRowValuesEqual(row, value, row.defaultValue))
95
- return true;
96
- return typeof row.carriedValue === 'number' && wrunRowValuesEqual(row, value, row.carriedValue);
97
- }
86
+ // The one "typed" test lives in the market size leaf, so settings-templates/market-bound shares it without importing
87
+ // this run head or the script inputs module; re-exported here for the callers that import it from this file.
88
+ export { wrunMarketScaledRowChanged };
98
89
  /**
99
90
  * The patch that moves a record (`settings`: its `scriptInputs` rows and each value flat under its row's name) to a
100
91
  * market's `defaults`: every scaled row whose value the user never chose (`wrunMarketScaledRowChanged`) takes the
@@ -105,7 +96,9 @@ export function wrunMarketScaledRowChanged(record, row) {
105
96
  * as never changed on the first market whose default equals it, and the next market would move it (SOL 200, then ETH
106
97
  * whose default is 200, then SOL reset it to 1000). Its reset goes to the default of the market where the user changed
107
98
  * it, a save whose run head then moves the unchanged value on. A carried value (`carriedValue`) is a changed one too,
108
- * whatever its row's default. Undefined when the record already reads the defaults. Pure.
99
+ * whatever its row's default. An untouched `times` row (a Whale) whose base row (its Min) the user chose takes its
100
+ * default lifted over that value (`wrunTimesDefaultOverChosenBase`, Q-0166; read off `rules`). Undefined when the
101
+ * record already reads the defaults. Pure.
109
102
  */
110
103
  export function wrunMarketSizeSettingsPatch(settings, defaults, rules) {
111
104
  const record = isRecord(settings) ? settings : {};
@@ -119,7 +112,7 @@ export function wrunMarketSizeSettingsPatch(settings, defaults, rules) {
119
112
  const row = held;
120
113
  if (!isWrunMarketScaledRow(row, rules?.[row.name]))
121
114
  return held;
122
- const target = wrunMarketDefaultWithinRow(row, defaults[row.name]);
115
+ const target = wrunMarketDefaultWithinRow(row, wrunDefaultInForce(record, rules?.[row.name], defaults[row.name]));
123
116
  if (target === undefined)
124
117
  return held;
125
118
  if (wrunMarketScaledRowChanged(record, row))
@@ -135,6 +128,19 @@ export function wrunMarketSizeSettingsPatch(settings, defaults, rules) {
135
128
  patch.scriptInputs = scriptInputs;
136
129
  return Object.keys(patch).length > 0 ? patch : undefined;
137
130
  }
131
+ /** A row's market default as the record's chosen values hold it: a `times` row's lifted over its base row's value
132
+ * where the user chose that one (`wrunTimesDefaultOverChosenBase`), any other default as given. */
133
+ function wrunDefaultInForce(record, rule, marketDefault) {
134
+ if (rule?.kind !== 'times' || typeof marketDefault !== 'number')
135
+ return marketDefault;
136
+ const baseRow = wrunRecordRowOf(record, rule.param);
137
+ if (baseRow === undefined || !wrunMarketScaledRowChanged(record, baseRow))
138
+ return marketDefault;
139
+ const chosen = Number(wrunRowValue(record, baseRow));
140
+ return Number.isFinite(chosen) && chosen > 0
141
+ ? wrunTimesDefaultOverChosenBase(marketDefault, rule.factor, chosen)
142
+ : marketDefault;
143
+ }
138
144
  /** Whether a record's dollar row `name` holds a carried mark (`carriedValue`: a carry already priced into it). */
139
145
  function wrunRowHoldsCarriedMark(record, name) {
140
146
  const rows = Array.isArray(record.scriptInputs) ? record.scriptInputs : [];
@@ -237,11 +243,82 @@ function wrunMarketSizeUnprovenFacts(families) {
237
243
  ...(families.options !== undefined ? { optionVerdict: WRUN_MARKET_SIZE_UNPROVEN } : {}),
238
244
  };
239
245
  }
246
+ /** Each mount's ranked values, by run market (`market.identity`), replay or live, and floor param: fixed for that
247
+ * market and candle size inside the page session. */
248
+ const wrunMarketSizeRankedByMount = new WeakMap();
249
+ /** The script input row a record declares under `name`. */
250
+ function wrunRecordRowOf(record, name) {
251
+ const rows = Array.isArray(record.scriptInputs) ? record.scriptInputs : [];
252
+ return rows.find((row) => isRecord(row) && row.name === name);
253
+ }
254
+ /** Whether `name`'s row in `record` exists and reads untouched (`wrunMarketScaledRowChanged` false). */
255
+ function wrunRowUntouched(record, name) {
256
+ const row = wrunRecordRowOf(record, name);
257
+ return row !== undefined && !wrunMarketScaledRowChanged(record, row);
258
+ }
259
+ /**
260
+ * The rank step of a run that holds a ticket (pure): the orders the tape rows hold inside the candles the tape
261
+ * covers, ranked against the floor param the acquisition asked with. `servedFromMs` is the first stamp the tape ask
262
+ * serves (its history counted back from its as-of, `tradesServedStartMs`); the span runs from the later of it and the
263
+ * chart's first candle to the close of its last, so a replay's runway and a warm-up head before the first candle never
264
+ * count, and `candles` counts the chart's candles inside it (never the tape's dense grid). Coins rank each dollar
265
+ * cell over `price x valuePerUnit` (the tape is asked in dollars); dollars and contracts rank the cell as served.
266
+ * Undefined when there is nothing to rank: the param is no ticket floor (touched, no base) or its memo held a value, no
267
+ * candle lies in the span, or a coins tape has no proven unit.
268
+ */
269
+ export function wrunMarketSizeRankOf(input) {
270
+ const { ticket, floorParam, chartRows, chartIntervalMs } = input;
271
+ if (floorParam === undefined || chartRows.length === 0)
272
+ return undefined;
273
+ const base = ticket.base[floorParam];
274
+ const param = wrunTapeRankedParamsOf(ticket.packageName)?.[floorParam];
275
+ if (base === undefined || param === undefined || ticket.memo[floorParam] === true)
276
+ return undefined;
277
+ if (param.unit === 'coins' && !(Number.isFinite(input.valuePerUnit) && input.valuePerUnit > 0)) {
278
+ return undefined;
279
+ }
280
+ const fromMs = Math.max(Number(chartRows[0][0]), Number.isFinite(input.servedFromMs) ? input.servedFromMs : -Infinity);
281
+ const toMs = Number(chartRows[chartRows.length - 1][0]) + chartIntervalMs;
282
+ let candles = 0;
283
+ for (const row of chartRows)
284
+ if (Number(row[0]) >= fromMs && Number(row[0]) < toMs)
285
+ candles += 1;
286
+ if (candles < 1)
287
+ return undefined;
288
+ const sizes = wrunTapeOrderSizes(input.rows ?? [], { fromMs, toMs }, param.unit, input.valuePerUnit ?? 1);
289
+ const cutoffs = wrunRankedCutoffs({
290
+ sizes,
291
+ candles,
292
+ base: base.min,
293
+ ...(base.whale !== undefined ? { baseWhale: base.whale } : {}),
294
+ whole: param.unit === 'contracts',
295
+ ...(ticket.held[floorParam] !== undefined ? { held: ticket.held[floorParam] } : {}),
296
+ });
297
+ if (cutoffs === undefined)
298
+ return undefined;
299
+ return {
300
+ [floorParam]: {
301
+ min: cutoffs.min,
302
+ whale: cutoffs.whale,
303
+ source: cutoffs.source,
304
+ n: cutoffs.n,
305
+ orders: sizes.length,
306
+ candles,
307
+ },
308
+ };
309
+ }
240
310
  /**
241
311
  * Move an overlay's record to its chart market's scaled defaults (above), at the head of a full run, before the
242
312
  * lanes read the settings. Resolves once the engine copy reads the defaults (the persist is the routing's own); a
243
313
  * package that scales nothing returns at once, and nothing here ever throws over the run.
244
314
  *
315
+ * `ranks` (a run whose rows this browser computes, the sandbox source): a package with ranked tape floors
316
+ * (wrun-market-size-rank.leaf `WRUN_TAPE_RANKED_PARAMS`) the sheet declares gets a ticket back
317
+ * (`WrunMarketSizeTicket`). The head still writes the engine copy, an untouched ranked floor at the ranked memo's value
318
+ * for this market (`replay` keys a replay apart), else at the base; the workspace row and its persist wait for the
319
+ * ticket's `commit`. Without `ranks` (a record the server computes: it receives literal numbers) the head writes both
320
+ * as it always did and returns undefined.
321
+ *
245
322
  * Every fact is proven the keyed market's before it is kept or written: `market` is the market the run computes for
246
323
  * (C4: the chart's market identity at the run head, `wrunChartMarketIdentity`, and the reader of the chart's metadata
247
324
  * now), and `isCurrent` says the run is still the overlay's own (its chart and mount stand). After each await, in the
@@ -256,18 +333,21 @@ export async function reconcileWrunMarketSizeDefaults(args) {
256
333
  const packageName = wrunRegistryRefOf(meta.settings)?.package;
257
334
  const rules = wrunMarketScaledRulesOfSheet(wrunMarketScaledParamsOf(packageName), sheetParams);
258
335
  if (rules === undefined)
259
- return;
336
+ return undefined;
337
+ // The ranked tape floors the sheet declares, on a run whose rows this browser computes.
338
+ const rankedParams = args.ranks === true ? wrunTapeRankedParamsOf(packageName) : undefined;
339
+ const rankedFloors = Object.keys(rankedParams ?? {}).filter((name) => sheetParams.has(name) && Object.hasOwn(rules, name));
260
340
  // The volume rules and the option rules resolve apart: each its own verdict, memo key and ring line.
261
341
  const families = wrunMarketScaledFamilies(rules);
262
342
  const keyed = () => isCurrent() && wrunChartMarketIdentity(market.read()) === market.identity;
263
343
  try {
264
344
  if (!keyed())
265
- return;
345
+ return undefined;
266
346
  const chartMetadata = market.read() ?? undefined;
267
347
  const exchange = typeof chartMetadata?.exchange === 'string' ? chartMetadata.exchange : '';
268
348
  const symbol = typeof chartMetadata?.symbol === 'string' ? chartMetadata.symbol : '';
269
349
  if (exchange === '' || symbol === '')
270
- return;
350
+ return undefined;
271
351
  const transformations = typeof chartMetadata?.transformations === 'string' ? chartMetadata.transformations : '';
272
352
  const formula = wrunChartFormulaOf(exchange, symbol, transformations);
273
353
  const family = families.volume === undefined ? undefined : Object.keys(families.volume).sort().join(',');
@@ -368,7 +448,7 @@ export async function reconcileWrunMarketSizeDefaults(args) {
368
448
  contractsDefaults = resolve(contractsKey, verdict, families.contracts, 'wrun-market-size-contracts-defaults', 'contracts');
369
449
  }
370
450
  if (!keyed())
371
- return;
451
+ return undefined;
372
452
  // The carries first (each value a marked changed one, `carriedValue`, so the move below keeps it): the contracts
373
453
  // carry, then the dollar carry over what it left; then the market's defaults, both families' in one patch.
374
454
  const storedUnit = headFacts?.storedUnit;
@@ -431,39 +511,200 @@ export async function reconcileWrunMarketSizeDefaults(args) {
431
511
  ...withPatch(settings, contractCarry),
432
512
  ...(carry ?? {}),
433
513
  });
434
- const movePatch = defaults === undefined ? undefined : wrunMarketSizeSettingsPatch(settingsOf(meta.settings), defaults, rules);
514
+ // The ranked floors (a ticketed run): each untouched one's base, the value it held before this head, and the
515
+ // ranked memo's value for this market and candle size, which the engine copy takes in place of the base. A carried
516
+ // value is a changed one (`wrunMarketScaledRowChanged`): it has no base and never ranks.
517
+ const headSettings = settingsOf(meta.settings);
518
+ const ranked = rankedFloors.length === 0 || packageName === undefined
519
+ ? undefined
520
+ : wrunMarketSizeRankedHead({
521
+ floors: rankedFloors,
522
+ params: rankedParams ?? {},
523
+ settings: headSettings,
524
+ defaults,
525
+ memo: wrunMarketSizeRankedByMount.get(meta),
526
+ memoKey: (floor) => `${market.identity}|${args.replay === true ? 'replay' : 'live'}|${floor}`,
527
+ });
528
+ const headDefaults = ranked === undefined ? defaults : ranked.engineDefaults;
529
+ const movePatch = headDefaults === undefined ? undefined : wrunMarketSizeSettingsPatch(headSettings, headDefaults, rules);
435
530
  const enginePatch = settled === undefined && contractCarry === undefined && carry === undefined && movePatch === undefined
436
531
  ? undefined
437
532
  : { ...(settled ?? {}), ...(contractCarry ?? {}), ...(carry ?? {}), ...(movePatch ?? {}) };
438
- if (enginePatch === undefined)
439
- return;
440
533
  const chart = tc;
441
- if (typeof chart?.updateSettings === 'function')
442
- chart.updateSettings(indicatorId, enginePatch);
443
- else
444
- meta.settings = { ...(isRecord(meta.settings) ? meta.settings : {}), ...enginePatch };
445
- const { persistChart, resolveChart } = await wrunChartHostEnv().chart.loadChartRouting();
446
- if (!keyed())
447
- return;
448
- const document = resolveChart(chartIndex);
449
- const row = [...(document?.onchart ?? []), ...(document?.offchart ?? [])].find((candidate) => candidate?.id === indicatorId);
450
- if (row === undefined)
451
- return;
452
- const rowContractCarry = contractCarry === undefined ? undefined : wrunContractCarryPatch(row.settings, contractPending, perContract);
453
- const rowCarry = carry === undefined
454
- ? undefined
455
- : wrunDollarCarryPatch(withPatch(row.settings, rowContractCarry), pending, storedUnit, sizeUnit);
456
- const rowSettings = { ...withPatch(row.settings, rowContractCarry), ...(rowCarry ?? {}) };
457
- const rowMove = defaults === undefined ? undefined : wrunMarketSizeSettingsPatch(rowSettings, defaults, rules);
458
- if (settled === undefined && rowContractCarry === undefined && rowCarry === undefined && rowMove === undefined) {
459
- return;
534
+ const writeEngine = (patch) => {
535
+ if (typeof chart?.updateSettings === 'function')
536
+ chart.updateSettings(indicatorId, patch);
537
+ else
538
+ meta.settings = { ...(isRecord(meta.settings) ? meta.settings : {}), ...patch };
539
+ };
540
+ if (enginePatch !== undefined)
541
+ writeEngine(enginePatch);
542
+ /** The workspace row's write, one reconcile persist when it changes: the carries and the stamp the head read,
543
+ * priced again over the row's own values, then `rowDefaults` moved onto its untouched rows. */
544
+ const writeRow = async (rowDefaults, withCarries = true) => {
545
+ const { persistChart, resolveChart } = await wrunChartHostEnv().chart.loadChartRouting();
546
+ if (!keyed())
547
+ return;
548
+ const document = resolveChart(chartIndex);
549
+ const row = [...(document?.onchart ?? []), ...(document?.offchart ?? [])].find((candidate) => candidate?.id === indicatorId);
550
+ if (row === undefined)
551
+ return;
552
+ const rowContractCarry = contractCarry === undefined || !withCarries
553
+ ? undefined
554
+ : wrunContractCarryPatch(row.settings, contractPending, perContract);
555
+ const rowCarry = carry === undefined || !withCarries
556
+ ? undefined
557
+ : wrunDollarCarryPatch(withPatch(row.settings, rowContractCarry), pending, storedUnit, sizeUnit);
558
+ const rowSettings = { ...withPatch(row.settings, rowContractCarry), ...(rowCarry ?? {}) };
559
+ const rowMove = rowDefaults === undefined ? undefined : wrunMarketSizeSettingsPatch(rowSettings, rowDefaults, rules);
560
+ const rowSettled = withCarries ? settled : undefined;
561
+ if (rowSettled === undefined &&
562
+ rowContractCarry === undefined &&
563
+ rowCarry === undefined &&
564
+ rowMove === undefined) {
565
+ return;
566
+ }
567
+ row.settings = { ...rowSettings, ...(rowMove ?? {}), ...(rowSettled ?? {}) };
568
+ persistChart(chartIndex, 'reconcile');
569
+ };
570
+ if (ranked === undefined) {
571
+ // Today's path: the row and its persist at the head, only when the engine copy moved.
572
+ if (enginePatch !== undefined)
573
+ await writeRow(defaults);
574
+ return undefined;
460
575
  }
461
- row.settings = { ...rowSettings, ...(rowMove ?? {}), ...(settled ?? {}) };
462
- persistChart(chartIndex, 'reconcile');
576
+ // A carry or the settle stamp reaches the row at the head, as it always did: the engine copy already took it, so a
577
+ // commit that finds the chart gone would leave the row with the old name and the stamp for good (the next head
578
+ // sees nothing pending). Only the ranked floor moves wait for the commit.
579
+ const carriesWritten = contractCarry !== undefined || carry !== undefined || settled !== undefined;
580
+ if (carriesWritten)
581
+ await writeRow(headDefaults);
582
+ const { base, held, memo } = ranked;
583
+ let committed;
584
+ const commitOnce = async (rankedValues) => {
585
+ try {
586
+ if (!keyed())
587
+ return;
588
+ let rowDefaults = headDefaults;
589
+ if (rankedValues !== undefined) {
590
+ const moves = {};
591
+ let mountMemo = wrunMarketSizeRankedByMount.get(meta);
592
+ const now = market.read() ?? undefined;
593
+ for (const [floor, value] of Object.entries(rankedValues)) {
594
+ const floorBase = base[floor];
595
+ if (floorBase === undefined || memo[floor] === true)
596
+ continue;
597
+ const whaleParam = rankedParams?.[floor]?.whale;
598
+ moves[floor] = value.min;
599
+ if (floorBase.writesWhale && whaleParam !== undefined)
600
+ moves[whaleParam] = value.whale;
601
+ if (mountMemo === undefined) {
602
+ mountMemo = new Map();
603
+ wrunMarketSizeRankedByMount.set(meta, mountMemo);
604
+ }
605
+ mountMemo.set(ranked.memoKeyOf(floor), { min: value.min, whale: value.whale });
606
+ if (wrunChartHostEnv().diagnostics.debugEnabled()) {
607
+ wrunChartHostEnv().diagnostics.debug('wrun-market-size-ranked', {
608
+ chartIndex,
609
+ indicatorId,
610
+ packageName,
611
+ param: floor,
612
+ exchange: typeof now?.exchange === 'string' ? now.exchange : exchange,
613
+ symbol: typeof now?.symbol === 'string' ? now.symbol : symbol,
614
+ interval: typeof now?.interval === 'string' ? now.interval : null,
615
+ base: floorBase.min,
616
+ value: value.min,
617
+ whale: value.whale,
618
+ source: value.source ?? 'ranked',
619
+ n: value.n ?? null,
620
+ orders: value.orders ?? null,
621
+ candles: value.candles ?? null,
622
+ });
623
+ }
624
+ }
625
+ if (Object.keys(moves).length > 0) {
626
+ rowDefaults = { ...(headDefaults ?? {}), ...moves };
627
+ // Value and default together (the row reads untouched, the reset goes to the same number).
628
+ const rankPatch = wrunMarketSizeSettingsPatch(meta.settings, moves, rules);
629
+ if (rankPatch !== undefined)
630
+ writeEngine(rankPatch);
631
+ }
632
+ }
633
+ await writeRow(rowDefaults, !carriesWritten);
634
+ }
635
+ catch (error) {
636
+ console.warn(`[wrun] the market size defaults of '${indicatorId}' were not committed:`, error);
637
+ }
638
+ };
639
+ return {
640
+ packageName: packageName,
641
+ base,
642
+ held,
643
+ memo,
644
+ askFloors: (settings) => {
645
+ const record = isRecord(settings) ? settings : {};
646
+ const floors = {};
647
+ for (const [floor, floorBase] of Object.entries(base)) {
648
+ if (wrunRowUntouched(record, floor))
649
+ floors[floor] = floorBase.min;
650
+ }
651
+ return floors;
652
+ },
653
+ commit: (rankedValues) => (committed ??= commitOnce(rankedValues)),
654
+ };
463
655
  }
464
656
  catch (error) {
465
657
  console.warn(`[wrun] the market size defaults of '${indicatorId}' were not applied:`, error);
466
658
  }
659
+ return undefined;
660
+ }
661
+ /**
662
+ * The head's read of a ticketed run's ranked floors (pure): for each floor whose row is untouched in `settings` (the
663
+ * record after the carries) and whose market default is resolved, its base (the default held to its row), its whale
664
+ * param's where that row is untouched too, the value the record held, and the memo's value for this market when it
665
+ * holds one. `engineDefaults` is `defaults` with each memo value in place of its base.
666
+ */
667
+ function wrunMarketSizeRankedHead(input) {
668
+ const { settings, defaults } = input;
669
+ const base = {};
670
+ const held = {};
671
+ const memo = {};
672
+ const overrides = {};
673
+ /** The market default of `name` held to its row, and whether that row is untouched. */
674
+ const within = (name) => {
675
+ const row = wrunRecordRowOf(settings, name);
676
+ if (row === undefined || defaults === undefined || !Object.hasOwn(defaults, name))
677
+ return undefined;
678
+ const value = wrunMarketDefaultWithinRow(row, defaults[name]);
679
+ return typeof value === 'number' ? { value, untouched: !wrunMarketScaledRowChanged(settings, row) } : undefined;
680
+ };
681
+ for (const floor of input.floors) {
682
+ const floorDefault = within(floor);
683
+ if (floorDefault === undefined || !floorDefault.untouched)
684
+ continue;
685
+ const min = floorDefault.value;
686
+ const whaleParam = input.params[floor]?.whale;
687
+ const whaleDefault = whaleParam === undefined ? undefined : within(whaleParam);
688
+ const writesWhale = whaleDefault?.untouched === true;
689
+ base[floor] = whaleDefault === undefined ? { min, writesWhale } : { min, whale: whaleDefault.value, writesWhale };
690
+ const was = settings[floor];
691
+ if (typeof was === 'number' && Number.isFinite(was))
692
+ held[floor] = was;
693
+ const remembered = input.memo?.get(input.memoKey(floor));
694
+ memo[floor] = remembered !== undefined;
695
+ if (remembered !== undefined) {
696
+ overrides[floor] = remembered.min;
697
+ if (writesWhale && whaleParam !== undefined)
698
+ overrides[whaleParam] = remembered.whale;
699
+ }
700
+ }
701
+ return {
702
+ base,
703
+ held,
704
+ memo,
705
+ engineDefaults: defaults === undefined ? undefined : { ...defaults, ...overrides },
706
+ memoKeyOf: input.memoKey,
707
+ };
467
708
  }
468
709
  /** The formula a chart's candles are computed from (normalized), or undefined for a chart of the market's own candles
469
710
  * (no transformations, or the market's own token). */
@@ -0,0 +1,75 @@
1
+ /**
2
+ * The ranked default of a tape floor: keep the biggest orders the chart's loaded candles hold, about one per five
3
+ * candles. The market default (wrun-market-size-defaults.leaf) reads one number per market, and the count of orders
4
+ * that clear one number per candle grows with the candle length, so on larger candles the package's cap of 5 bubbles
5
+ * per candle is the only limit and it is reached on almost every candle. Measured 2026-11-18 on Binance futures
6
+ * BTCUSDT at its $1M default: 246 bubbles per 200 candles on 1m, 774 on 15m, 832 on 1h. The market default stays the
7
+ * floor the tape is asked at (the base); this leaf ranks the rows that floor brings back and names the cutoff that
8
+ * keeps the biggest N of them, rounded down on a clean ladder and never below the base.
9
+ *
10
+ * Pure: the run (wrun-overlay-run.util) asks the tape at the base, hands the rows here, and commits the result once.
11
+ */
12
+ /** The unit a tape floor counts its prints in: a print's dollar value, its coins, or its contracts (CME). */
13
+ export type WrunTapeRankedUnit = 'dollars' | 'coins' | 'contracts';
14
+ /** A ranked tape floor: the whale param that follows it and the unit both count in. */
15
+ export interface WrunTapeRankedParam {
16
+ readonly whale: string;
17
+ readonly unit: WrunTapeRankedUnit;
18
+ }
19
+ /**
20
+ * The tape floors whose untouched default is ranked, by package name, then floor param (the sheet's own names). A
21
+ * built-in twin whose sheet binds a param to a tape floor lists it here or in the guard's exemptions with a reason
22
+ * (tests/utility/wrun/wrun-market-size-defaults.twins.spec.ts walks every proven twin's frozen sheet).
23
+ */
24
+ export declare const WRUN_TAPE_RANKED_PARAMS: Readonly<Record<string, Readonly<Record<string, WrunTapeRankedParam>>>>;
25
+ /** The ranked tape floors of a package, or undefined for a package that ranks none. */
26
+ export declare function wrunTapeRankedParamsOf(packageName: string | undefined): Readonly<Record<string, WrunTapeRankedParam>> | undefined;
27
+ /**
28
+ * The largest of 1, 1.2, 1.5, 2, 2.5, 3, 4, 5, 6 or 8 times a power of ten at or below `value`, as a clean decimal;
29
+ * undefined for a value that is not finite and above zero.
30
+ */
31
+ export declare function wrunLadderFloor(value: number): number | undefined;
32
+ /** The chart's loaded candles in ms: a tape row counts when its bar key lies in `fromMs <= barTs < toMs` (toMs is the
33
+ * last candle's close), the rule the caller counts the candles by, so a candle keyed away from its opening instant
34
+ * (a CME daily candle keyed 00:00 UTC opens the evening before) counts its orders exactly when it counts itself. */
35
+ export interface WrunTapeSpan {
36
+ readonly fromMs: number;
37
+ readonly toMs: number;
38
+ }
39
+ /**
40
+ * The size of every order the tape rows whose bar key lies inside `span` hold. A row is `[barTs, ...cells]`, a cell
41
+ * `[offsetMs, price, size, side]` (the offset exact to the microsecond, side +1 or -1); `size` is the print's dollar
42
+ * value under a dollar floor and its stored amount (contracts on CME) under a raw floor. One ORDER is the cells of one
43
+ * bar with the same exact offset and side (the CME per-order read keeps every fill of a qualifying order), their sizes
44
+ * summed, so three orders a millisecond apart stay three (Discord ticket #683: 51, 25 and 77 contracts, never 153).
45
+ * In 'coins' each fill counts `size / (price x valuePerUnit)` (a fill with no positive price is skipped). Quiet bars
46
+ * and malformed cells are skipped. Sizes come back in no particular order.
47
+ */
48
+ export declare function wrunTapeOrderSizes(rows: ReadonlyArray<ArrayLike<unknown>>, span: WrunTapeSpan, unit: WrunTapeRankedUnit, valuePerUnit?: number): number[];
49
+ /** What the ranked cutoffs read: the order sizes, the loaded candle count, the market default and its whale, whole
50
+ * contracts, and the value a previous run stored untouched. */
51
+ export interface WrunRankedCutoffsInput {
52
+ readonly sizes: readonly number[];
53
+ readonly candles: number;
54
+ readonly base: number;
55
+ readonly baseWhale?: number;
56
+ readonly whole?: boolean;
57
+ readonly held?: number;
58
+ }
59
+ /** The ranked Min and Whale, the N they aimed at, the orders Min keeps, and where Min came from. */
60
+ export interface WrunRankedCutoffs {
61
+ readonly min: number;
62
+ readonly whale: number;
63
+ readonly n: number;
64
+ readonly kept: number;
65
+ readonly source: 'ranked' | 'held' | 'base';
66
+ }
67
+ /**
68
+ * The cutoffs that keep the biggest N = max(10, round(candles / 5)) orders. Min is the Nth biggest order's size
69
+ * rounded down on the ladder, never below the base. Fewer than N orders at the base keeps the base first, whatever a
70
+ * held value would keep. Else a `held` value (a previous run's stored untouched value) stays while it still keeps
71
+ * N / 2 to 2N orders, so a refresh moves the number only once it drifted out of that band. Whale keeps one in ten of
72
+ * the N: the (N / 10)th biggest order rounded down on the ladder, never below Min or the market's whale default.
73
+ * Undefined for a base that is not finite and above zero or fewer than one candle.
74
+ */
75
+ export declare function wrunRankedCutoffs(input: WrunRankedCutoffsInput): WrunRankedCutoffs | undefined;
@@ -0,0 +1,154 @@
1
+ /**
2
+ * The ranked default of a tape floor: keep the biggest orders the chart's loaded candles hold, about one per five
3
+ * candles. The market default (wrun-market-size-defaults.leaf) reads one number per market, and the count of orders
4
+ * that clear one number per candle grows with the candle length, so on larger candles the package's cap of 5 bubbles
5
+ * per candle is the only limit and it is reached on almost every candle. Measured 2026-11-18 on Binance futures
6
+ * BTCUSDT at its $1M default: 246 bubbles per 200 candles on 1m, 774 on 15m, 832 on 1h. The market default stays the
7
+ * floor the tape is asked at (the base); this leaf ranks the rows that floor brings back and names the cutoff that
8
+ * keeps the biggest N of them, rounded down on a clean ladder and never below the base.
9
+ *
10
+ * Pure: the run (wrun-overlay-run.util) asks the tape at the base, hands the rows here, and commits the result once.
11
+ */
12
+ /**
13
+ * The tape floors whose untouched default is ranked, by package name, then floor param (the sheet's own names). A
14
+ * built-in twin whose sheet binds a param to a tape floor lists it here or in the guard's exemptions with a reason
15
+ * (tests/utility/wrun/wrun-market-size-defaults.twins.spec.ts walks every proven twin's frozen sheet).
16
+ */
17
+ export const WRUN_TAPE_RANKED_PARAMS = Object.freeze({
18
+ '@om-core/big-trades': Object.freeze({
19
+ // 0.6.0 on: the dollar tape's floor (Min value) and Whale value.
20
+ min_value: Object.freeze({ whale: 'whale_value', unit: 'dollars' }),
21
+ // 0.10.0 on: the coins tape's floor (Min size in Coins mode) and its Whale size.
22
+ min_coins: Object.freeze({ whale: 'whale_coins', unit: 'coins' }),
23
+ // 0.8.0 on: the contracts tape's floor (Min size on CME, judged per order) and its Whale size.
24
+ min_contracts: Object.freeze({ whale: 'whale_contracts', unit: 'contracts' }),
25
+ }),
26
+ });
27
+ /** The ranked tape floors of a package, or undefined for a package that ranks none. */
28
+ export function wrunTapeRankedParamsOf(packageName) {
29
+ if (packageName === undefined || !Object.hasOwn(WRUN_TAPE_RANKED_PARAMS, packageName))
30
+ return undefined;
31
+ return WRUN_TAPE_RANKED_PARAMS[packageName];
32
+ }
33
+ /** The ladder's steps inside one power of ten: finer than the market default's 1, 2, 5, so a ranked cutoff lands
34
+ * close to the Nth order (a 1, 2, 5 floor can drop as much as 60% under it and double the count kept). */
35
+ const LADDER = [1, 1.2, 1.5, 2, 2.5, 3, 4, 5, 6, 8];
36
+ /**
37
+ * The largest of 1, 1.2, 1.5, 2, 2.5, 3, 4, 5, 6 or 8 times a power of ten at or below `value`, as a clean decimal;
38
+ * undefined for a value that is not finite and above zero.
39
+ */
40
+ export function wrunLadderFloor(value) {
41
+ if (!Number.isFinite(value) || value <= 0)
42
+ return undefined;
43
+ const scale = 10 ** Math.floor(Math.log10(value));
44
+ // A hair over the float quotient: 0.6 / 0.1 reads 5.999999999999999, and log10 can land a power of ten one
45
+ // exponent low (the mantissa then reads 10).
46
+ const mantissa = (value / scale) * (1 + 1e-9);
47
+ let step = mantissa >= 10 ? 10 : 1;
48
+ if (mantissa < 10)
49
+ for (const candidate of LADDER)
50
+ if (candidate <= mantissa)
51
+ step = candidate;
52
+ const rung = Number((step * scale).toPrecision(2));
53
+ if (rung <= value)
54
+ return rung;
55
+ // The hair lifted a value a hair under a rung onto it (999999.9995 read 1,000,000): one rung down, never up, so the
56
+ // package's exact `size >= min` keeps the order the rank counted.
57
+ const at = LADDER.indexOf(step);
58
+ return at > 0
59
+ ? Number((LADDER[at - 1] * scale).toPrecision(2))
60
+ : Number((LADDER[LADDER.length - 1] * (step === 10 ? scale : scale / 10)).toPrecision(2));
61
+ }
62
+ /**
63
+ * The size of every order the tape rows whose bar key lies inside `span` hold. A row is `[barTs, ...cells]`, a cell
64
+ * `[offsetMs, price, size, side]` (the offset exact to the microsecond, side +1 or -1); `size` is the print's dollar
65
+ * value under a dollar floor and its stored amount (contracts on CME) under a raw floor. One ORDER is the cells of one
66
+ * bar with the same exact offset and side (the CME per-order read keeps every fill of a qualifying order), their sizes
67
+ * summed, so three orders a millisecond apart stay three (Discord ticket #683: 51, 25 and 77 contracts, never 153).
68
+ * In 'coins' each fill counts `size / (price x valuePerUnit)` (a fill with no positive price is skipped). Quiet bars
69
+ * and malformed cells are skipped. Sizes come back in no particular order.
70
+ */
71
+ export function wrunTapeOrderSizes(rows, span, unit, valuePerUnit = 1) {
72
+ const orders = new Map();
73
+ for (const row of rows) {
74
+ if (row === null || typeof row !== 'object' || row.length < 2)
75
+ continue;
76
+ const barTs = row[0];
77
+ if (typeof barTs !== 'number' || !Number.isFinite(barTs))
78
+ continue;
79
+ if (barTs < span.fromMs || barTs >= span.toMs)
80
+ continue;
81
+ for (let at = 1; at < row.length; at += 1) {
82
+ const cell = row[at];
83
+ if (cell === null || typeof cell !== 'object' || cell.length < 4)
84
+ continue;
85
+ const [offset, price, size, side] = [cell[0], cell[1], cell[2], cell[3]];
86
+ if (typeof offset !== 'number' || !Number.isFinite(offset))
87
+ continue;
88
+ if (typeof size !== 'number' || !Number.isFinite(size) || size <= 0)
89
+ continue;
90
+ if (side !== 1 && side !== -1)
91
+ continue;
92
+ let amount = size;
93
+ if (unit === 'coins') {
94
+ if (typeof price !== 'number' || !Number.isFinite(price) || price <= 0)
95
+ continue;
96
+ amount = size / (price * valuePerUnit);
97
+ }
98
+ const key = `${barTs}|${offset}|${side}`;
99
+ orders.set(key, (orders.get(key) ?? 0) + amount);
100
+ }
101
+ }
102
+ return [...orders.values()];
103
+ }
104
+ /** One bubble per five candles, never under 10: a 1d chart would otherwise draw one or two a week. */
105
+ const CANDLES_PER_ORDER = 5;
106
+ const MIN_ORDERS = 10;
107
+ /** The ladder value at or below `value`, a whole number of at least 1 for contracts. */
108
+ function rungAtOrBelow(value, whole) {
109
+ const rung = wrunLadderFloor(value);
110
+ if (rung === undefined)
111
+ return undefined;
112
+ return whole ? Math.max(1, Math.floor(rung)) : rung;
113
+ }
114
+ /**
115
+ * The cutoffs that keep the biggest N = max(10, round(candles / 5)) orders. Min is the Nth biggest order's size
116
+ * rounded down on the ladder, never below the base. Fewer than N orders at the base keeps the base first, whatever a
117
+ * held value would keep. Else a `held` value (a previous run's stored untouched value) stays while it still keeps
118
+ * N / 2 to 2N orders, so a refresh moves the number only once it drifted out of that band. Whale keeps one in ten of
119
+ * the N: the (N / 10)th biggest order rounded down on the ladder, never below Min or the market's whale default.
120
+ * Undefined for a base that is not finite and above zero or fewer than one candle.
121
+ */
122
+ export function wrunRankedCutoffs(input) {
123
+ const { candles, base, baseWhale, held } = input;
124
+ const whole = input.whole === true;
125
+ if (!Number.isFinite(base) || base <= 0 || !Number.isFinite(candles) || candles < 1)
126
+ return undefined;
127
+ const n = Math.max(MIN_ORDERS, Math.round(candles / CANDLES_PER_ORDER));
128
+ const ranked = input.sizes.filter((size) => Number.isFinite(size) && size >= base).sort((a, b) => b - a);
129
+ const count = (floor) => ranked.filter((size) => size >= floor).length;
130
+ let min;
131
+ let source;
132
+ if (ranked.length < n) {
133
+ min = base;
134
+ source = 'base';
135
+ }
136
+ else if (held !== undefined &&
137
+ Number.isFinite(held) &&
138
+ held >= base &&
139
+ count(held) >= n / 2 &&
140
+ count(held) <= 2 * n) {
141
+ min = held;
142
+ source = 'held';
143
+ }
144
+ else {
145
+ min = Math.max(base, rungAtOrBelow(ranked[n - 1], whole) ?? base);
146
+ source = 'ranked';
147
+ }
148
+ const kept = count(min);
149
+ if (source === 'base')
150
+ return { min, whale: Math.max(min, baseWhale ?? base * 10), n, kept, source };
151
+ const tenth = ranked.filter((size) => size >= min)[Math.max(1, Math.round(n / 10)) - 1];
152
+ const topTenth = tenth === undefined ? 0 : (rungAtOrBelow(tenth, whole) ?? 0);
153
+ return { min, whale: Math.max(min, baseWhale ?? 0, topTenth), n, kept, source };
154
+ }