dexbot 1.6.17 → 1.7.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 (156) hide show
  1. package/CHANGELOG.md +58 -0
  2. package/README.md +24 -18
  3. package/analysis/README.md +105 -12
  4. package/analysis/ama_fitting/README.md +2 -2
  5. package/analysis/bot_fitting/README.md +3 -3
  6. package/claw/package.json +1 -1
  7. package/claw/runtimes/openclaw-plugin/openclaw.plugin.json +1 -1
  8. package/claw/runtimes/openclaw-plugin/package.json +1 -1
  9. package/dist/analysis/analyze_args.d.ts +2 -1
  10. package/dist/analysis/analyze_dynamic_weight.js +2 -1
  11. package/dist/analysis/analyze_kalman.js +3 -2
  12. package/dist/analysis/analyze_liquidity.d.ts +17 -0
  13. package/dist/analysis/analyze_liquidity.js +325 -0
  14. package/dist/analysis/analyze_regime.js +3 -2
  15. package/dist/analysis/analyze_regime_windows.js +3 -2
  16. package/dist/analysis/analyze_volatility.js +3 -2
  17. package/dist/analysis/fills_source.d.ts +1 -8
  18. package/dist/analysis/fills_source.js +1 -1
  19. package/dist/analysis/grid_correction_check.d.ts +9 -6
  20. package/dist/analysis/grid_correction_check.js +56 -64
  21. package/dist/analysis/liquidity/liquidity_chain.d.ts +66 -0
  22. package/dist/analysis/liquidity/liquidity_chain.js +178 -0
  23. package/dist/analysis/liquidity/liquidity_chart_generator.d.ts +19 -0
  24. package/dist/analysis/liquidity/liquidity_chart_generator.js +523 -0
  25. package/dist/analysis/liquidity/liquidity_depth_model.d.ts +141 -0
  26. package/dist/analysis/liquidity/liquidity_depth_model.js +230 -0
  27. package/dist/analysis/liquidity/liquidity_view.d.ts +38 -0
  28. package/dist/analysis/liquidity/liquidity_view.js +55 -0
  29. package/dist/analysis/math_utils.d.ts +1 -1
  30. package/dist/analysis/trade_profitability.d.ts +1 -1
  31. package/dist/analysis/trade_profitability.js +2 -1
  32. package/dist/analysis/tradingview/analyze_tradingview.js +2 -1
  33. package/dist/analysis/tradingview/tradingview_uplot_chart_generator.js +3 -3
  34. package/dist/analysis/trend_detection/huber_scale_variants.d.ts +4 -3
  35. package/dist/dexbot.js +74 -169
  36. package/dist/market_adapter/cli_args.d.ts +6 -1
  37. package/dist/market_adapter/cli_args.js +16 -2
  38. package/dist/market_adapter/core/kibana_candles.d.ts +5 -1
  39. package/dist/market_adapter/core/kibana_candles.js +3 -1
  40. package/dist/market_adapter/core/strategies/regime_gate.d.ts +7 -1
  41. package/dist/market_adapter/core/strategies/regime_gate.js +3 -1
  42. package/dist/market_adapter/inputs/cex_candle_parsing.d.ts +7 -2
  43. package/dist/market_adapter/inputs/cex_candle_parsing.js +3 -1
  44. package/dist/market_adapter/inputs/fetch_book_data.d.ts +7 -1
  45. package/dist/market_adapter/inputs/fetch_book_data.js +3 -1
  46. package/dist/market_adapter/inputs/fetch_cex_synthetic_data.js +2 -11
  47. package/dist/market_adapter/inputs/fetch_lp_data.d.ts +26 -1
  48. package/dist/market_adapter/inputs/fetch_lp_data.js +62 -52
  49. package/dist/market_adapter/inputs/kibana_feed_source.d.ts +14 -2
  50. package/dist/market_adapter/inputs/kibana_feed_source.js +14 -1
  51. package/dist/market_adapter/inputs/window_cache.d.ts +14 -3
  52. package/dist/market_adapter/inputs/window_cache.js +14 -1
  53. package/dist/market_adapter/lp_chart_runner.d.ts +12 -9
  54. package/dist/market_adapter/lp_chart_runner.js +3 -1
  55. package/dist/market_adapter/lp_chart_strategy_loader.d.ts +5 -1
  56. package/dist/market_adapter/lp_chart_strategy_loader.js +3 -1
  57. package/dist/market_adapter/market_adapter.d.ts +10 -2
  58. package/dist/market_adapter/market_adapter.js +10 -11
  59. package/dist/market_adapter/utils/chain.d.ts +2 -3
  60. package/dist/market_adapter/utils/file_json_cache.d.ts +5 -1
  61. package/dist/market_adapter/utils/file_json_cache.js +3 -1
  62. package/dist/market_adapter/utils/file_lock.js +1 -1
  63. package/dist/market_adapter/utils/native_history.d.ts +7 -3
  64. package/dist/market_adapter/utils/native_history.js +3 -1
  65. package/dist/market_adapter/utils/pair_orientation.d.ts +2 -2
  66. package/dist/modules/asset_lookup.d.ts +25 -0
  67. package/dist/modules/asset_lookup.js +75 -0
  68. package/dist/modules/bots_file_lock.d.ts +2 -2
  69. package/dist/modules/bots_file_lock.js +2 -2
  70. package/dist/modules/chain_scan.d.ts +64 -0
  71. package/dist/modules/chain_scan.js +80 -0
  72. package/dist/modules/cli_colors.d.ts +5 -0
  73. package/dist/modules/cli_colors.js +7 -0
  74. package/dist/modules/cli_progress.d.ts +51 -0
  75. package/dist/modules/cli_progress.js +113 -0
  76. package/dist/modules/constants.js +6 -3
  77. package/dist/modules/dexbot_class.d.ts +8 -0
  78. package/dist/modules/dexbot_class.js +10 -0
  79. package/dist/modules/dexbot_cow_runtime.d.ts +62 -1
  80. package/dist/modules/dexbot_cow_runtime.js +475 -47
  81. package/dist/modules/dexbot_credential_client.d.ts +5 -0
  82. package/dist/modules/dexbot_fill_runtime.js +20 -0
  83. package/dist/modules/dexbot_maintenance_runtime.js +71 -9
  84. package/dist/modules/dexbot_startup_runtime.js +7 -1
  85. package/dist/modules/graceful_shutdown.d.ts +2 -2
  86. package/dist/modules/graceful_shutdown.js +2 -2
  87. package/dist/modules/launcher/runtime_entry.d.ts +21 -1
  88. package/dist/modules/launcher/runtime_entry.js +36 -1
  89. package/dist/modules/launcher/runtime_mode.d.ts +4 -3
  90. package/dist/modules/liquidity_pool_ref.d.ts +32 -0
  91. package/dist/modules/liquidity_pool_ref.js +116 -0
  92. package/dist/modules/node_manager.d.ts +1 -1
  93. package/dist/modules/node_manager.js +1 -1
  94. package/dist/modules/order/accounting.js +2 -1
  95. package/dist/modules/order/export.d.ts +2 -2
  96. package/dist/modules/order/export.js +2 -2
  97. package/dist/modules/order/grid.d.ts +19 -14
  98. package/dist/modules/order/grid.js +269 -61
  99. package/dist/modules/order/grid_reconcile.js +27 -2
  100. package/dist/modules/order/grid_reconcile_internal.js +94 -15
  101. package/dist/modules/order/index.d.ts +24 -4
  102. package/dist/modules/order/manager.d.ts +12 -0
  103. package/dist/modules/order/manager.js +44 -11
  104. package/dist/modules/order/strategy.js +22 -2
  105. package/dist/modules/order/sync_engine.d.ts +32 -1
  106. package/dist/modules/order/sync_engine.js +209 -26
  107. package/dist/modules/order/utils/math.d.ts +26 -10
  108. package/dist/modules/order/utils/math.js +54 -14
  109. package/dist/modules/order/utils/order.d.ts +158 -11
  110. package/dist/modules/order/utils/order.js +434 -21
  111. package/dist/modules/order/utils/system.d.ts +136 -30
  112. package/dist/modules/order/utils/system.js +465 -63
  113. package/dist/modules/order/utils/validate.d.ts +1 -0
  114. package/dist/modules/order/utils/validate.js +37 -3
  115. package/dist/modules/storage/index.d.ts +3 -2
  116. package/dist/modules/storage/index.js +3 -2
  117. package/dist/modules/types.d.ts +14 -0
  118. package/dist/modules/utils/asset_symbols.d.ts +13 -2
  119. package/dist/modules/utils/asset_symbols.js +21 -2
  120. package/dist/scripts/analysis_runner.d.ts +10 -0
  121. package/dist/scripts/analysis_runner.js +33 -0
  122. package/dist/scripts/analyze-orders.js +2 -1
  123. package/dist/scripts/asset.d.ts +26 -0
  124. package/dist/scripts/asset.js +165 -0
  125. package/dist/scripts/bts_distribution.d.ts +1 -0
  126. package/dist/scripts/bts_distribution.js +194 -142
  127. package/dist/scripts/chart_command.d.ts +1 -1
  128. package/dist/scripts/chart_command.js +60 -86
  129. package/dist/scripts/chart_targets.d.ts +18 -0
  130. package/dist/scripts/chart_targets.js +52 -0
  131. package/dist/scripts/dw.js +1 -1
  132. package/dist/scripts/liquid.d.ts +24 -0
  133. package/dist/scripts/liquid.js +134 -0
  134. package/dist/scripts/rich_list.js +12 -16
  135. package/dist/scripts/token_distribution.d.ts +2 -0
  136. package/dist/scripts/token_distribution.js +132 -108
  137. package/dist/scripts/tv.js +1 -1
  138. package/dist/scripts/verify-browser-bundle.js +18 -0
  139. package/docs/COPY_ON_WRITE_MASTER_PLAN.md +1 -1
  140. package/docs/COW_INVARIANTS.md +21 -11
  141. package/docs/DEXBOT_COMPARISON.md +6 -6
  142. package/docs/EVOLUTION.md +10 -8
  143. package/docs/FUND_MOVEMENT_AND_ACCOUNTING.md +11 -11
  144. package/docs/GRID_PRICE_INVARIANT.md +28 -5
  145. package/docs/GRID_RECONCILE.md +25 -5
  146. package/docs/LIFECYCLE.md +11 -11
  147. package/docs/LOGGING.md +37 -2
  148. package/docs/ORDER_ENGINE_POST_1.0_RETROSPECTIVE.md +124 -36
  149. package/docs/README.md +1 -1
  150. package/docs/WORKFLOW.md +3 -1
  151. package/docs/architecture.md +115 -13
  152. package/docs/developer_guide.md +12 -0
  153. package/market_adapter/README.md +9 -4
  154. package/modules/README.md +23 -15
  155. package/package.json +6 -3
  156. package/scripts/README.md +23 -7
@@ -0,0 +1,64 @@
1
+ /**
2
+ * CHAIN OBJECT-ID SCAN
3
+ *
4
+ * Some object types have no list API: legacy 1.15.x balance objects and 1.13.x
5
+ * vesting balances can only be enumerated by probing ids with `get_objects`,
6
+ * which answers `null` for holes. Ids are allocated monotonically and never
7
+ * reused, so a range is "dense-ish" — walking from 0 and stopping after `gap`
8
+ * consecutive misses finds every live object without knowing where the range
9
+ * ends.
10
+ *
11
+ * Two details keep that affordable on every report:
12
+ * - one large `get_objects` batch per round trip (1000 ids measurably beats
13
+ * 100 by ~4x because the per-call overhead dominates), with an automatic
14
+ * halving fallback for nodes that refuse big batches, and
15
+ * - no filtering here: callers filter the objects they need (e.g. by
16
+ * `balance.asset_id`), because the node exposes no per-asset index for
17
+ * these types.
18
+ *
19
+ * The module is pure (the reader is injected), so it stays browser-safe.
20
+ */
21
+ /** Ids per `get_objects` call; all public nodes accept this batch size. */
22
+ declare const DEFAULT_SCAN_BATCH = 1000;
23
+ /** Never fall below this when backing off, so a refusal cannot loop forever. */
24
+ declare const MIN_SCAN_BATCH = 100;
25
+ /**
26
+ * Trailing miss budget for the dense implementation spaces (2.3.x, 2.4.x, 1.3.x,
27
+ * 1.16.x): one object per asset / smart asset, ids never reused, holes measured
28
+ * in single digits. The legacy spaces (1.13.x vesting, 1.15.x balances) have
29
+ * real holes and keep the larger `--gap` default.
30
+ */
31
+ declare const DENSE_SPACE_GAP = 2000;
32
+ interface ChainScanOptions {
33
+ /** Database reader; `read('get_objects', [ids])` must resolve to `(T|null)[]`. */
34
+ read: (method: string, args: unknown[]) => Promise<unknown>;
35
+ /** Object id prefix, e.g. `'1.15'`. */
36
+ prefix: string;
37
+ /** Highest id to probe (the walk always starts at 0). */
38
+ maxId: number;
39
+ /** Stop after this many consecutive missing ids. */
40
+ gap: number;
41
+ /**
42
+ * Ids per call (default 1000). An explicit smaller value is honoured as-is;
43
+ * a node error halves the batch down to `MIN_SCAN_BATCH`.
44
+ */
45
+ batchSize?: number;
46
+ /** Called after each batch with the number of ids walked so far. */
47
+ onProgress?: (scanned: number) => void;
48
+ }
49
+ interface ChainScanResult<T> {
50
+ objects: T[];
51
+ /** Number of ids walked (exclusive upper bound of the scanned range). */
52
+ scannedTo: number;
53
+ /** True when the walk stopped at `maxId`, so the range may be truncated. */
54
+ hitLimit: boolean;
55
+ }
56
+ /**
57
+ * Walk `prefix.0 … prefix.maxId` in batches and collect every live object.
58
+ *
59
+ * @throws when `get_objects` keeps failing even at `MIN_SCAN_BATCH`.
60
+ */
61
+ declare function scanIdRange<T>(options: ChainScanOptions): Promise<ChainScanResult<T>>;
62
+ export { scanIdRange, DEFAULT_SCAN_BATCH, DENSE_SPACE_GAP, MIN_SCAN_BATCH };
63
+ export type { ChainScanOptions, ChainScanResult };
64
+ //# sourceMappingURL=chain_scan.d.ts.map
@@ -0,0 +1,80 @@
1
+ 'use strict';
2
+ /**
3
+ * CHAIN OBJECT-ID SCAN
4
+ *
5
+ * Some object types have no list API: legacy 1.15.x balance objects and 1.13.x
6
+ * vesting balances can only be enumerated by probing ids with `get_objects`,
7
+ * which answers `null` for holes. Ids are allocated monotonically and never
8
+ * reused, so a range is "dense-ish" — walking from 0 and stopping after `gap`
9
+ * consecutive misses finds every live object without knowing where the range
10
+ * ends.
11
+ *
12
+ * Two details keep that affordable on every report:
13
+ * - one large `get_objects` batch per round trip (1000 ids measurably beats
14
+ * 100 by ~4x because the per-call overhead dominates), with an automatic
15
+ * halving fallback for nodes that refuse big batches, and
16
+ * - no filtering here: callers filter the objects they need (e.g. by
17
+ * `balance.asset_id`), because the node exposes no per-asset index for
18
+ * these types.
19
+ *
20
+ * The module is pure (the reader is injected), so it stays browser-safe.
21
+ */
22
+ /** Ids per `get_objects` call; all public nodes accept this batch size. */
23
+ const DEFAULT_SCAN_BATCH = 1000;
24
+ /** Never fall below this when backing off, so a refusal cannot loop forever. */
25
+ const MIN_SCAN_BATCH = 100;
26
+ /**
27
+ * Trailing miss budget for the dense implementation spaces (2.3.x, 2.4.x, 1.3.x,
28
+ * 1.16.x): one object per asset / smart asset, ids never reused, holes measured
29
+ * in single digits. The legacy spaces (1.13.x vesting, 1.15.x balances) have
30
+ * real holes and keep the larger `--gap` default.
31
+ */
32
+ const DENSE_SPACE_GAP = 2_000;
33
+ /**
34
+ * Walk `prefix.0 … prefix.maxId` in batches and collect every live object.
35
+ *
36
+ * @throws when `get_objects` keeps failing even at `MIN_SCAN_BATCH`.
37
+ */
38
+ async function scanIdRange(options) {
39
+ const { read, prefix, maxId, gap, onProgress } = options;
40
+ let batch = Math.max(1, Math.floor(options.batchSize ?? DEFAULT_SCAN_BATCH));
41
+ const objects = [];
42
+ let index = 0;
43
+ let lastSeen = -1;
44
+ // `gap` means exactly "gap consecutive missing ids": after the last live
45
+ // object only ids up to lastSeen+gap are worth probing. Clipping the batch
46
+ // to that bound makes the walk independent of the batch size — without it a
47
+ // larger batch probes (and reports) further than the documented --gap.
48
+ while (index <= maxId) {
49
+ const limit = Math.min(maxId, lastSeen + gap);
50
+ if (index > limit)
51
+ break;
52
+ const count = Math.min(batch, limit - index + 1);
53
+ const ids = Array.from({ length: count }, (_, i) => `${prefix}.${index + i}`);
54
+ let page;
55
+ try {
56
+ page = await read('get_objects', [ids]);
57
+ }
58
+ catch (err) {
59
+ // A node may cap the batch size; retry the same window smaller
60
+ // instead of failing the whole report.
61
+ if (batch > MIN_SCAN_BATCH) {
62
+ batch = Math.max(MIN_SCAN_BATCH, Math.floor(batch / 2));
63
+ continue;
64
+ }
65
+ throw err;
66
+ }
67
+ for (let j = 0; j < count; j++) {
68
+ const obj = page?.[j];
69
+ if (obj) {
70
+ lastSeen = index + j;
71
+ objects.push(obj);
72
+ }
73
+ }
74
+ index += count;
75
+ onProgress?.(index);
76
+ }
77
+ return { objects, scannedTo: index, hitLimit: index > maxId };
78
+ }
79
+ export { scanIdRange, DEFAULT_SCAN_BATCH, DENSE_SPACE_GAP, MIN_SCAN_BATCH };
80
+ //# sourceMappingURL=chain_scan.js.map
@@ -35,4 +35,9 @@ export declare const CLI_COLORS: {
35
35
  readonly silver: "\u001B[38;5;250m";
36
36
  readonly greenBold: "\u001B[1;32m";
37
37
  };
38
+ /**
39
+ * Wrap text in one of the {@link CLI_COLORS} codes and reset afterwards —
40
+ * the `c(colors.x, text)` helper each CLI used to declare locally.
41
+ */
42
+ export declare function colorize(code: string, text: string): string;
38
43
  //# sourceMappingURL=cli_colors.d.ts.map
@@ -39,4 +39,11 @@ export const CLI_COLORS = {
39
39
  silver: '\x1b[38;5;250m', // light silver grey (bots editor)
40
40
  greenBold: '\x1b[1;32m', // bold green (bots editor)
41
41
  };
42
+ /**
43
+ * Wrap text in one of the {@link CLI_COLORS} codes and reset afterwards —
44
+ * the `c(colors.x, text)` helper each CLI used to declare locally.
45
+ */
46
+ export function colorize(code, text) {
47
+ return `${code}${text}${CLI_COLORS.reset}`;
48
+ }
42
49
  //# sourceMappingURL=cli_colors.js.map
@@ -0,0 +1,51 @@
1
+ /** Console tags for the read-only analysis commands. */
2
+ export declare const CLI_TAGS: {
3
+ readonly assets: "[Assets]";
4
+ readonly liquidity: "[Liquidity]";
5
+ readonly tradingView: "[TradingView]";
6
+ readonly dynamicWeight: "[DynamicWeight]";
7
+ readonly pnl: "[PnL]";
8
+ readonly orders: "[Order]";
9
+ readonly volatility: "[Volatility]";
10
+ readonly regime: "[Regime]";
11
+ readonly regimeWindows: "[RegimeWindows]";
12
+ readonly kalman: "[Kalman]";
13
+ readonly derivatives: "[Derivatives]";
14
+ };
15
+ /**
16
+ * Write (or overwrite) a transient `[Tag] message` progress line.
17
+ * Silenced when `enabled` is false, when stderr is not a TTY, or in a browser.
18
+ */
19
+ export declare function progressLine(tag: string, enabled: boolean, message: string): void;
20
+ /** Erase the transient progress line before the report is printed. */
21
+ export declare function clearProgressLine(enabled?: boolean): void;
22
+ /**
23
+ * Bind {@link progressLine} to one tag, so a script keeps its short
24
+ * `progress(enabled, message)` call sites while the format stays centralized.
25
+ */
26
+ export declare function taggedProgress(tag: string): (enabled: boolean, message: string) => void;
27
+ /**
28
+ * Trailer printed after a report is written, e.g.
29
+ * `[Assets] ✓ Report saved. Open report: (file:///…/bts-distribution.html)`.
30
+ * The caller supplies the file URL (analysis/chart_utils.toFileUrl); `kind`
31
+ * overrides the lowercased label in the "Open …" half (`'PnL report'` →
32
+ * `'report'`).
33
+ */
34
+ export declare function savedLine(tag: string, label: string, fileUrl: string, kind?: string): string;
35
+ /** Persistent `[Tag] message` line, e.g. `[Assets] Loading … from chain...`. */
36
+ export declare function loadingLine(tag: string, message: string): string;
37
+ /**
38
+ * Report section header block (leading blank line included):
39
+ * `\n ── Title ─────────────────────────────…`, bold amber.
40
+ */
41
+ export declare function section(title: string, width?: number): string;
42
+ /** Warning bullets (` • text`, red), one per entry. */
43
+ export declare function warningLines(warnings: readonly string[]): string[];
44
+ /**
45
+ * A section header plus its warning bullets, or '' when there is nothing to
46
+ * report. Every report command prints warnings the same way through this.
47
+ */
48
+ export declare function warningsBlock(warnings: readonly string[], width?: number): string;
49
+ /** Muted trailing summary line, printed just above the saved-file link. */
50
+ export declare function summaryLine(text: string): string;
51
+ //# sourceMappingURL=cli_progress.d.ts.map
@@ -0,0 +1,113 @@
1
+ 'use strict';
2
+ /**
3
+ * modules/cli_progress.ts - Shared terminal status style for CLI commands.
4
+ *
5
+ * One place for the `[Tag] …` line style used by the analysis commands
6
+ * (`dexbot liq`, the chart exporters, the supply distribution analyzers):
7
+ *
8
+ * [Tag] Loading … caller's console.log (persistent)
9
+ * [Tag] scanning 1.13.x … progressLine() - transient, stderr, TTY only
10
+ * [Tag] ✓ Report saved … savedLine() (persistent, clickable file:// link)
11
+ *
12
+ * Keeping the tag, the clear-line escape and the trailer wording here is what
13
+ * keeps `dexbot liq`, `dexbot tv`, `dexbot asset` … visually identical instead
14
+ * of each script re-implementing the same three things.
15
+ *
16
+ * Browser-safe: no Node imports. The stderr access is guarded through
17
+ * modules/env.ts, so the module can be imported from browser-reachable code
18
+ * without touching `process`.
19
+ */
20
+ import { hasProcess } from './env.js';
21
+ import { CLI_COLORS, colorize } from './cli_colors.js';
22
+ /** Erase the current terminal line (progress updates overwrite in place). */
23
+ const CLEAR_LINE = '\r\x1b[2K';
24
+ /** Console tags for the read-only analysis commands. */
25
+ export const CLI_TAGS = {
26
+ assets: '[Assets]',
27
+ liquidity: '[Liquidity]',
28
+ tradingView: '[TradingView]',
29
+ dynamicWeight: '[DynamicWeight]',
30
+ pnl: '[PnL]',
31
+ orders: '[Order]',
32
+ volatility: '[Volatility]',
33
+ regime: '[Regime]',
34
+ regimeWindows: '[RegimeWindows]',
35
+ kalman: '[Kalman]',
36
+ derivatives: '[Derivatives]',
37
+ };
38
+ /** Width of the report section headers (`── Title ──…`). */
39
+ const SECTION_WIDTH = 70;
40
+ /** stderr when it is an interactive terminal, otherwise null (no-op logging). */
41
+ function progressStream() {
42
+ if (!hasProcess())
43
+ return null;
44
+ const stream = globalThis.process?.stderr;
45
+ return stream && stream.isTTY ? stream : null;
46
+ }
47
+ /**
48
+ * Write (or overwrite) a transient `[Tag] message` progress line.
49
+ * Silenced when `enabled` is false, when stderr is not a TTY, or in a browser.
50
+ */
51
+ export function progressLine(tag, enabled, message) {
52
+ if (!enabled)
53
+ return;
54
+ const stream = progressStream();
55
+ if (!stream)
56
+ return;
57
+ stream.write(`${CLEAR_LINE}${tag} ${message}`);
58
+ }
59
+ /** Erase the transient progress line before the report is printed. */
60
+ export function clearProgressLine(enabled = true) {
61
+ if (!enabled)
62
+ return;
63
+ const stream = progressStream();
64
+ if (stream)
65
+ stream.write(CLEAR_LINE);
66
+ }
67
+ /**
68
+ * Bind {@link progressLine} to one tag, so a script keeps its short
69
+ * `progress(enabled, message)` call sites while the format stays centralized.
70
+ */
71
+ export function taggedProgress(tag) {
72
+ return (enabled, message) => progressLine(tag, enabled, message);
73
+ }
74
+ /**
75
+ * Trailer printed after a report is written, e.g.
76
+ * `[Assets] ✓ Report saved. Open report: (file:///…/bts-distribution.html)`.
77
+ * The caller supplies the file URL (analysis/chart_utils.toFileUrl); `kind`
78
+ * overrides the lowercased label in the "Open …" half (`'PnL report'` →
79
+ * `'report'`).
80
+ */
81
+ export function savedLine(tag, label, fileUrl, kind) {
82
+ return `\n${tag} ✓ ${label} saved. Open ${kind ?? label.toLowerCase()}: (${fileUrl})`;
83
+ }
84
+ /** Persistent `[Tag] message` line, e.g. `[Assets] Loading … from chain...`. */
85
+ export function loadingLine(tag, message) {
86
+ return `${tag} ${message}`;
87
+ }
88
+ /**
89
+ * Report section header block (leading blank line included):
90
+ * `\n ── Title ─────────────────────────────…`, bold amber.
91
+ */
92
+ export function section(title, width = SECTION_WIDTH) {
93
+ const rule = '─'.repeat(Math.max(0, width - title.length));
94
+ return `\n${colorize(CLI_COLORS.bold + CLI_COLORS.yellow, ` ── ${title} ${rule}`)}`;
95
+ }
96
+ /** Warning bullets (` • text`, red), one per entry. */
97
+ export function warningLines(warnings) {
98
+ return warnings.map((text) => colorize(CLI_COLORS.sell, ` • ${text}`));
99
+ }
100
+ /**
101
+ * A section header plus its warning bullets, or '' when there is nothing to
102
+ * report. Every report command prints warnings the same way through this.
103
+ */
104
+ export function warningsBlock(warnings, width = SECTION_WIDTH) {
105
+ if (warnings.length === 0)
106
+ return '';
107
+ return [section('Warnings', width), ...warningLines(warnings)].join('\n');
108
+ }
109
+ /** Muted trailing summary line, printed just above the saved-file link. */
110
+ export function summaryLine(text) {
111
+ return colorize(CLI_COLORS.gray, ` ${text}`);
112
+ }
113
+ //# sourceMappingURL=cli_progress.js.map
@@ -353,9 +353,12 @@ let TIMING = {
353
353
  // SPREAD_STALE_GEOMETRY_ESCALATE_MS: escalated window used when the
354
354
  // correction reports the geometry bind 'last-fill-blocked' — every
355
355
  // tightening slot on the corrected side sits at/through the last fill, i.e.
356
- // the sell window itself is behind the last sale (boundary/crawl lag). No
357
- // amount of waiting fixes that; a re-center does. Waiting the structural
358
- // 30 minutes just leaves the side unquoted.
356
+ // the window itself is behind the last fill (boundary/crawl lag). No
357
+ // amount of waiting fixes that; a re-center does, because it re-derives the
358
+ // center AROUND that same pivot. Waiting the structural 30 minutes just
359
+ // leaves the side unquoted. Capped at ONE re-center per pivot value
360
+ // (`_lastGeometryResyncPivotKey`): the pivot does not move with the grid, so
361
+ // a second attempt re-derives the identical veto.
359
362
  SPREAD_STALE_GEOMETRY_ESCALATE_MS: 10 * 60 * 1000, // 10 minutes
360
363
  // SPREAD_CORRECTION_MAX_ATTEMPTS: bounded attempts for one spread-correction
361
364
  // cycle (initial broadcast + fresh-master re-plan retries). Kept next to the
@@ -185,6 +185,14 @@ declare class DEXBot implements BotLike {
185
185
  _lastHeldChainOrderSignatureSince: number;
186
186
  _lastHeldChainOrderWarnAt: number;
187
187
  _lastSpreadStaleResyncAt: number;
188
+ /**
189
+ * Fill pivot (`price|type`) the geometry-bind escalation already re-centered
190
+ * for. A re-center cannot move the pivot, so the same fill is never
191
+ * re-centered twice — churn guard, cleared when the spread heals.
192
+ */
193
+ _lastGeometryResyncPivotKey: string;
194
+ /** Pivot key the "re-center cannot clear this" warning was already logged for. */
195
+ _geometryResyncWarnedPivotKey: string;
188
196
  _marketAdapterWatchdogInFlight: boolean;
189
197
  _outOfSpreadSince: number;
190
198
  _outOfSpreadStaleWarned: boolean;
@@ -213,6 +213,14 @@ class DEXBot {
213
213
  _lastHeldChainOrderSignatureSince;
214
214
  _lastHeldChainOrderWarnAt;
215
215
  _lastSpreadStaleResyncAt;
216
+ /**
217
+ * Fill pivot (`price|type`) the geometry-bind escalation already re-centered
218
+ * for. A re-center cannot move the pivot, so the same fill is never
219
+ * re-centered twice — churn guard, cleared when the spread heals.
220
+ */
221
+ _lastGeometryResyncPivotKey;
222
+ /** Pivot key the "re-center cannot clear this" warning was already logged for. */
223
+ _geometryResyncWarnedPivotKey;
216
224
  _marketAdapterWatchdogInFlight;
217
225
  _outOfSpreadSince;
218
226
  _outOfSpreadStaleWarned;
@@ -278,6 +286,8 @@ class DEXBot {
278
286
  // the first maintenance tick. Values mirror the lazy fallbacks in
279
287
  // trackOutOfSpreadStaleness.
280
288
  this._lastSpreadStaleResyncAt = 0;
289
+ this._lastGeometryResyncPivotKey = '';
290
+ this._geometryResyncWarnedPivotKey = '';
281
291
  this._outOfSpreadSince = 0;
282
292
  this._outOfSpreadStaleWarned = false;
283
293
  this._outOfSpreadTransientCount = 0;
@@ -403,6 +403,42 @@ declare function resolveRefillBoundaryHold(workingBoundary: unknown, committedBo
403
403
  effectiveBoundary: unknown;
404
404
  heldRefillSlotIds: string[];
405
405
  };
406
+ /**
407
+ * Derive the boundary the actual rails imply.
408
+ *
409
+ * `boundary` is a claim about where the BUY rail ends and the gap band begins;
410
+ * live orders are the fact. A fill-driven plan built at a re-anchored boundary
411
+ * places COUNTER orders above the committed boundary (SELL fill at slot s =>
412
+ * counter BUY at s - gapSlots). If the refill hold then keeps the old boundary,
413
+ * those counters sit inside the implied band; the next plan sees the old
414
+ * geometry and places a SELL on top of them, collapsing the spread (live
415
+ * incident: a sweep's counters at 1329.7-1345.7 were reclassified as in-band by
416
+ * a hold to 133, then sells were rotated to 1345.728664 — the exact price of
417
+ * the buy that had just filled).
418
+ *
419
+ * Rails are clamped by construction:
420
+ *
421
+ * maxBuyIdx <= boundary <= minSellIdx - gapSlots - 1
422
+ *
423
+ * Counter orders therefore win over empty refill holes: a held boundary may
424
+ * never strand a placed counter. When the plan did not place an order on the
425
+ * promoted rail (the normal refill-hold case) `maxBuyIdx` stays at/below the
426
+ * committed boundary and the hold is preserved unchanged.
427
+ *
428
+ * @param manager - OrderManager (master grid rails)
429
+ * @param opContexts - Kept op contexts of the batch (post guard/final gate)
430
+ * @param desiredBoundary - Plan boundary (falls back to the committed one)
431
+ * @param gapSlots - Gap band width
432
+ * @returns Boundary implied by the rails, or null when no rail geometry is
433
+ * usable / the rails already cross (caller keeps the current value).
434
+ */
435
+ export declare function deriveRailBoundary(manager: OrderManagerLike, opContexts: Iterable<unknown> | null | undefined, desiredBoundary: unknown, gapSlots: unknown): {
436
+ boundary: number | null;
437
+ maxBuyIdx: number | null;
438
+ minSellIdx: number | null;
439
+ clamped: boolean;
440
+ reason?: string;
441
+ };
406
442
  /**
407
443
  * Track consecutive boundary-hold batches on the manager (ops visibility).
408
444
  *
@@ -454,6 +490,28 @@ declare function resolveOnGridPivot(manager: OrderManagerLike, rawPrice: unknown
454
490
  idx: number | null;
455
491
  nearestDrift: number | null;
456
492
  };
493
+ /**
494
+ * Warn (once per batch) when a generic CREATE is emitted on the ADVERSE side of
495
+ * the crossing floor — the guard the spread-correction planner applies through
496
+ * `doesNotCrossMarket`.
497
+ *
498
+ * Non-blocking by design (see the call site): a crossing limit order executes at
499
+ * the BEST available price, so the risk is taker fees and unintended immediate
500
+ * execution, not a worse price. Blocking here would re-open the counter-order
501
+ * deadlock — after a gap the counter lands on the better side by construction,
502
+ * and a gapped market can put the planned level on the other side of the floor,
503
+ * where waiting for the market to return is worse than taking it.
504
+ *
505
+ * The floor is a pure read of already-cached evidence (a fresh live market read
506
+ * wins over the fill reference by recency), so this costs no chain call.
507
+ *
508
+ * @param {Object} bot
509
+ * @param {unknown} price - Emitted CREATE price
510
+ * @param {unknown} type - ORDER_TYPES.BUY/SELL
511
+ * @param {unknown} slotId - Slot the CREATE targets (log context)
512
+ * @returns {boolean} True when a warning was emitted (caller stops re-checking this batch)
513
+ */
514
+ declare function warnCrossingCreate(bot: BotLike, price: unknown, type: unknown, slotId: unknown): boolean;
457
515
  /**
458
516
  * Final pre-broadcast pivot gate: re-check BUILT ops against a re-refreshed
459
517
  * pivot RIGHT BEFORE broadcast.
@@ -538,8 +596,11 @@ declare function processBatchResults(bot: BotLike, result: JsonObj, opContexts:
538
596
  executed: boolean;
539
597
  hadRotation: boolean;
540
598
  updateOperationCount: number;
599
+ executedActionCount: number;
600
+ createOperationCount: number;
601
+ rotationOperationCount: number;
541
602
  }>;
542
- export { isSpreadCorrectionBypassAllowed, isLastFillGuardBlocked, resolveOnGridPivot, checkGridPriceInvariant, recordRestampBuyAboveAnchor, collectGapBandPlacementShadowSlots, deriveRotationPrice, refreshLastFillPivotFromQueue, runFinalPivotGate, buildOutsideInPairGroupsForOrders, buildOutsideInPairGroupsForCreateEntries, markMissingCreateResultsAsStructuralBlocker, formatUnmatchedChainOrderForLog, recordPendingBroadcast, clearPendingBroadcasts, popPushedWorkingGrid, findChainOrderForSlot, reconcileAfterUncertainBroadcast, executeWithRetryOnUncertain, executeChunkedWithRetryOnUncertain, formatPartialBroadcastSummary, buildActionsFromPlan, buildCowResultFromPlan, applyRotationTransitionsToWorkingGrid, updateOrdersOnChainBatchCOW, processBatchResults, adoptPlacedBatchFromChain, resolveRefillBoundaryHold, toRefillSlotIdSet, trackBoundaryHold };
603
+ export { isSpreadCorrectionBypassAllowed, isLastFillGuardBlocked, resolveOnGridPivot, warnCrossingCreate, checkGridPriceInvariant, recordRestampBuyAboveAnchor, collectGapBandPlacementShadowSlots, deriveRotationPrice, refreshLastFillPivotFromQueue, runFinalPivotGate, buildOutsideInPairGroupsForOrders, buildOutsideInPairGroupsForCreateEntries, markMissingCreateResultsAsStructuralBlocker, formatUnmatchedChainOrderForLog, recordPendingBroadcast, clearPendingBroadcasts, popPushedWorkingGrid, findChainOrderForSlot, reconcileAfterUncertainBroadcast, executeWithRetryOnUncertain, executeChunkedWithRetryOnUncertain, formatPartialBroadcastSummary, buildActionsFromPlan, buildCowResultFromPlan, applyRotationTransitionsToWorkingGrid, updateOrdersOnChainBatchCOW, processBatchResults, adoptPlacedBatchFromChain, resolveRefillBoundaryHold, toRefillSlotIdSet, trackBoundaryHold };
543
604
  export { restoreDiscardedCreates };
544
605
  declare const _default: {
545
606
  buildOutsideInPairGroupsForOrders: typeof buildOutsideInPairGroupsForOrders;