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
package/dist/dexbot.js CHANGED
@@ -48,7 +48,8 @@ const __dirname = _esmDirname(__filename);
48
48
  * Trading: dexbot test <bot> | drystart <bot> | reset {all|<bot>}
49
49
  * Config: dexbot bot | key | enable {all|<bot>} | disable {all|<bot>} | default | update
50
50
  * Analysis: dexbot order [<bot>] | export <bot> | credit [<bot>] | rich <asset...>
51
- * dexbot tv <target> | dw <target> | pnl <account>
51
+ * dexbot tv <target> | dw <target> | liquid <target> | pnl <account>
52
+ * dexbot asset <bts|symbol> (shorthand: dexbot a <bts|symbol>)
52
53
  * Files: dexbot clear | clear-orders | clear-market-adapter | clear-all
53
54
  *
54
55
  * NPM SCRIPTS (alternative invocation):
@@ -120,7 +121,7 @@ async function _resolveCollateralAssetId(ref) {
120
121
  }
121
122
  const { setupGracefulShutdown, registerCleanup, unregisterCleanup } = require('./modules/graceful_shutdown');
122
123
  const { collectValidationIssues, loadSettingsFile, normalizeBotEntries, resolveRawBotEntries, saveSettingsFile, } = require('./modules/bot_settings');
123
- const { buildRuntimeScriptArgs } = require('./modules/launcher/runtime_entry');
124
+ const { buildRuntimeScriptPath, runRuntimeScript } = require('./modules/launcher/runtime_entry');
124
125
  const { parseWorkerArgs, LAUNCHER_WORKER_COMMAND } = require('./modules/launcher/launch_modes');
125
126
  const { detectRuntimeMode, runtimeControlHelp, runtimeModeLabel, checkStatusTarget, resolveStatusRoute } = require('./modules/launcher/runtime_mode');
126
127
  const { PATHS, getHomeProfilesDir, getRecalculateTriggerFile, printRelocationNotices } = require('./modules/paths');
@@ -143,8 +144,8 @@ if (typeof credentialPolicy.checkPolicyFileSecurity === 'function')
143
144
  // Primary CLI driver that manages tracked bots and helper utilities such as key/bot editors.
144
145
  const PROFILES_BOTS_FILE = PATHS.PROFILES.BOTS_JSON;
145
146
  const PROFILES_DIR = PATHS.PROFILES_DIR;
146
- const CLI_COMMANDS = ['start', 'test', 'reset', 'default', 'disable', 'enable', 'drystart', 'key', 'bot', 'pm2', 'update', 'export', 'order', 'credit', 'rich', 'tv', 'dw', 'pnl', 'git', 'clear', 'clear-orders', 'clear-market-adapter', 'clear-all', 'status', 'unlock', 'delete', 'stop', 'restart', 'reload', 'help'];
147
- const COMMAND_ALIASES = { orders: 'order', keys: 'key', bots: 'bot', stat: 'status', stats: 'status', start: 'unlock', defaults: 'default', stp: 'stop', stopall: 'stop', restartall: 'restart', reloadall: 'reload' };
147
+ const CLI_COMMANDS = ['start', 'test', 'reset', 'default', 'disable', 'enable', 'drystart', 'key', 'bot', 'pm2', 'update', 'export', 'order', 'credit', 'rich', 'tv', 'dw', 'liquid', 'pnl', 'asset', 'git', 'clear', 'clear-orders', 'clear-market-adapter', 'clear-all', 'status', 'unlock', 'delete', 'stop', 'restart', 'reload', 'help'];
148
+ const COMMAND_ALIASES = { orders: 'order', keys: 'key', bots: 'bot', stat: 'status', stats: 'status', start: 'unlock', defaults: 'default', stp: 'stop', stopall: 'stop', restartall: 'restart', reloadall: 'reload', liq: 'liquid', liqu: 'liquid', liquidity: 'liquid', a: 'asset' };
148
149
  const CLI_HELP_FLAGS = ['-h', '--help'];
149
150
  const CLI_EXAMPLES_FLAG = '--cli-examples';
150
151
  const CLI_EXAMPLES = [
@@ -159,7 +160,9 @@ const CLI_EXAMPLES = [
159
160
  { title: 'Analyze order grids', command: 'dexbot order', notes: 'Spread, increment, and funds; --export for HTML.' },
160
161
  { title: 'Show live credit positions', command: 'dexbot credit', notes: 'Summed MPA + borrowed-credit positions per bot.' },
161
162
  { title: 'Asset rich list', command: 'dexbot rich <asset> [<asset...>]', notes: 'Top holder(s) per asset from the chain asset holders API.' },
162
- { title: 'Chart a bot, pool, or pair', command: 'dexbot tv <bot|pool-id|AssetA/AssetB> --month 3', notes: 'OHLC chart; --feed charts MPA price-feed history.' },
163
+ { title: 'Chart a bot, pool, or pair', command: 'dexbot tv <bot|pool|AssetA/AssetB> --month 3', notes: 'OHLC chart; pool = id (133) or pool token (LP share asset); --feed charts MPA price-feed history.' },
164
+ { title: 'Liquidity depth chart', command: 'dexbot liquid <bot|pool|AssetA/AssetB>', notes: 'Order-book + AMM pool cumulative depth; pool = id or pool token (aliases: liq, liqu, liquidity).' },
165
+ { title: 'Asset supply distribution', command: 'dexbot a bts', notes: 'Where BTS sits (collateral, pools, locks, residual) + HTML report. A bare symbol (dexbot a <symbol>) covers an issued asset; canonical: asset.' },
163
166
  { title: 'PnL report', command: 'dexbot pnl <bot|account> --month 3 [--pair BASE/QUOTE]', notes: 'Self-contained HTML PnL report for the resolved bot or chain account.' }
164
167
  ];
165
168
  const STARTUP_COLORS = {
@@ -207,14 +210,19 @@ function printCLIUsage() {
207
210
  ['default', 'Reset generated settings to defaults.'],
208
211
  ['update', 'Update DEXBot2 and restart active bots.'],
209
212
  ]],
213
+ // Ordered by the investigation an operator actually runs: grid state and its
214
+ // data export, then market research, then accounting/chain context. Keep the
215
+ // README "Bot Management" block in the same order so the two cannot drift.
210
216
  ['Analysis', [
211
217
  ['order [<bot>]', 'Analyze persisted order grids; --export for HTML.'],
212
218
  ['export <bot>', 'Export bot trades/settings to CSV/JSON.'],
213
- ['credit [<bot>]', 'Show live MPA and borrowed-credit positions.'],
214
- ['rich <asset...>', 'Per-asset rich list / top holder; --top N, --json.'],
215
- ['tv <target>', 'OHLC chart for <bot|pool-id|AssetA/AssetB>; --month N (default 3), --feed for MPA price-feed history.'],
219
+ ['tv <target>', 'OHLC chart for <bot|pool|AssetA/AssetB> (pool = id or pool token); --month N (default 3), --feed for MPA price-feed history.'],
216
220
  ['dw <target>', 'Dynamic-weight research chart; same targets and flags as tv.'],
221
+ ['liquid <target>', 'Liquidity depth chart for <bot|pool|AssetA/AssetB> (pool = id or pool token); --range, --depth, --steps (aliases: liq, liqu, liquidity).'],
217
222
  ['pnl <account>', 'HTML PnL report for a bot or account; --month N, optional --pair BASE/QUOTE filter.'],
223
+ ['credit [<bot>]', 'Show live MPA and borrowed-credit positions.'],
224
+ ['asset <bts|symbol>', 'Supply distribution: bts = core asset, bare symbol/id = issued asset; --json, --html (shorthand: a, e.g. dexbot a bts).'],
225
+ ['rich <asset...>', 'Per-asset rich list / top holder; --top N, --json.'],
218
226
  ]],
219
227
  ['Files', [
220
228
  ['clear', 'Delete log files. Stop the runtime first.'],
@@ -265,7 +273,7 @@ if (cliArgs.some(arg => CLI_HELP_FLAGS.includes(arg))) {
265
273
  // so the script prints its usage. Only scripts with offline help handling
266
274
  // belong here — forwarding to a script without it could misinterpret the
267
275
  // flag as input (e.g. a bot-name filter triggering live work).
268
- const HELP_OWNING_COMMANDS = new Set(['credit', 'rich', 'tv', 'dw', 'pnl']);
276
+ const HELP_OWNING_COMMANDS = new Set(['credit', 'rich', 'tv', 'dw', 'liquid', 'pnl', 'asset']);
269
277
  const requestedCommand = COMMAND_ALIASES[cliArgs[0]] ?? cliArgs[0];
270
278
  if (!HELP_OWNING_COMMANDS.has(requestedCommand)) {
271
279
  printCLIUsage();
@@ -842,9 +850,38 @@ async function exportBotTrades(botName) {
842
850
  process.exit(1);
843
851
  }
844
852
  }
853
+ /**
854
+ * Script-backed commands: command name → entry-point segments under the code
855
+ * root. Every entry owns its own argument parsing and usage text (the
856
+ * HELP_OWNING_COMMANDS set forwards `--help` to it), so the CLI only spawns it
857
+ * and mirrors the exit code.
858
+ */
859
+ const SCRIPT_COMMANDS = {
860
+ order: ['scripts', 'analyze-orders'],
861
+ credit: ['scripts', 'analyze-credit'],
862
+ rich: ['scripts', 'rich_list'],
863
+ git: ['scripts', 'analyze-git'],
864
+ tv: ['scripts', 'tv'],
865
+ dw: ['scripts', 'dw'],
866
+ liquid: ['scripts', 'liquid'],
867
+ pnl: ['scripts', 'pnl'],
868
+ asset: ['scripts', 'asset'],
869
+ };
870
+ /**
871
+ * Spawn a runtime entry point with inherited stdio and exit with its status.
872
+ * `rest` defaults to the CLI arguments after the command.
873
+ *
874
+ * Returns `true` after `process.exit` so a caller whose exit is intercepted
875
+ * (tests) still stops the command instead of falling through the switch.
876
+ */
877
+ function exitWithRuntimeScript(segments, label, rest = cliArgs.slice(1)) {
878
+ const status = runRuntimeScript(buildRuntimeScriptPath(__dirname, segments), rest, { label, cwd: PATHS.PROJECT_ROOT });
879
+ process.exit(status);
880
+ return true;
881
+ }
845
882
  /**
846
883
  * Parse and execute CLI commands.
847
- * Supported commands: test, drystart, reset, default, disable, enable, key, bot, pm2, update, export, order, credit, tv, dw, clear, status, unlock, help
884
+ * Supported commands: test, drystart, reset, default, disable, enable, key, bot, pm2, update, export, order, credit, tv, dw, liquid, pnl, asset, clear, status, unlock, help
848
885
  * @returns {Promise<boolean>} True if a command was handled, false otherwise
849
886
  */
850
887
  async function handleCLICommands() {
@@ -942,32 +979,12 @@ async function handleCLICommands() {
942
979
  }
943
980
  process.exit(0);
944
981
  return true;
945
- case 'pm2': {
946
- const { spawnSync } = require('child_process');
982
+ case 'pm2':
947
983
  // Forward the remaining CLI args to pm2.js so subcommands work
948
984
  // (`dexbot pm2 stop <bot>`, `dexbot pm2 restart all`, `dexbot pm2
949
- // help`...). Previously the subcommand was silently dropped and the
950
- // full-setup path ran, so `dexbot pm2 start X` started ALL bots and
951
- // `dexbot pm2 stop X` no-oped into a full setup.
952
- // buildRuntimeScriptArgs resolves the pm2 entry point under the
953
- // dist-only runtime layout (dist/pm2.js); plain node executes
954
- // compiled entries since the tsx removal.
955
- const pm2Args = buildRuntimeScriptArgs({
956
- codeRoot: __dirname,
957
- scriptSegments: ['pm2'],
958
- scriptArgs: cliArgs.slice(1),
959
- });
960
- const result = spawnSync(Config.EXEC_PATH, pm2Args, {
961
- cwd: PATHS.PROJECT_ROOT,
962
- stdio: 'inherit',
963
- });
964
- if (result.error) {
965
- console.error(`pm2: ${result.error.message}`);
966
- process.exit(1);
967
- }
968
- process.exit(result.status ?? 0);
969
- return true;
970
- }
985
+ // help`...). A dropped subcommand used to make `dexbot pm2 start X`
986
+ // start ALL bots and `dexbot pm2 stop X` no-op into a full setup.
987
+ return exitWithRuntimeScript(['pm2'], 'pm2');
971
988
  case 'update':
972
989
  setSuppressConnectionLog(true);
973
990
  require('./scripts/update');
@@ -977,118 +994,24 @@ async function handleCLICommands() {
977
994
  await exportBotTrades(target);
978
995
  process.exit(0);
979
996
  return true;
980
- case 'order': {
981
- const { spawnSync } = require('child_process');
982
- const scriptArgs = buildRuntimeScriptArgs({
983
- codeRoot: __dirname,
984
- scriptSegments: ['scripts', 'analyze-orders'],
985
- scriptArgs: cliArgs.slice(1),
986
- });
987
- const result = spawnSync(Config.EXEC_PATH, scriptArgs, {
988
- cwd: PATHS.PROJECT_ROOT,
989
- stdio: 'inherit',
990
- });
991
- if (result.error) {
992
- console.error(`order: ${result.error.message}`);
993
- process.exit(1);
994
- }
995
- process.exit(result.status ?? 0);
996
- return true;
997
- }
998
- case 'credit': {
999
- const { spawnSync } = require('child_process');
1000
- const scriptArgs = buildRuntimeScriptArgs({
1001
- codeRoot: __dirname,
1002
- scriptSegments: ['scripts', 'analyze-credit'],
1003
- scriptArgs: cliArgs.slice(1),
1004
- });
1005
- const result = spawnSync(Config.EXEC_PATH, scriptArgs, {
1006
- cwd: PATHS.PROJECT_ROOT,
1007
- stdio: 'inherit',
1008
- });
1009
- if (result.error) {
1010
- console.error(`credit: ${result.error.message}`);
1011
- process.exit(1);
1012
- }
1013
- process.exit(result.status ?? 0);
1014
- return true;
1015
- }
1016
- case 'rich': {
1017
- const { spawnSync } = require('child_process');
1018
- const scriptArgs = buildRuntimeScriptArgs({
1019
- codeRoot: __dirname,
1020
- scriptSegments: ['scripts', 'rich_list'],
1021
- scriptArgs: cliArgs.slice(1),
1022
- });
1023
- const result = spawnSync(Config.EXEC_PATH, scriptArgs, {
1024
- cwd: PATHS.PROJECT_ROOT,
1025
- stdio: 'inherit',
1026
- });
1027
- if (result.error) {
1028
- console.error(`rich: ${result.error.message}`);
1029
- process.exit(1);
1030
- }
1031
- process.exit(result.status ?? 0);
1032
- return true;
1033
- }
1034
- case 'git': {
1035
- // Repository statistics analyzer (scripts/analyze-git.ts): parses
1036
- // git history and writes analysis/charts/repo-stats.html. Git-only;
1037
- // it requires a source checkout (.git present).
1038
- const { spawnSync } = require('child_process');
1039
- const scriptArgs = buildRuntimeScriptArgs({
1040
- codeRoot: __dirname,
1041
- scriptSegments: ['scripts', 'analyze-git'],
1042
- });
1043
- const result = spawnSync(Config.EXEC_PATH, scriptArgs, {
1044
- cwd: PATHS.PROJECT_ROOT,
1045
- stdio: 'inherit',
1046
- });
1047
- if (result.error) {
1048
- console.error(`git: ${result.error.message}`);
1049
- process.exit(1);
1050
- }
1051
- process.exit(result.status ?? 0);
1052
- return true;
1053
- }
997
+ case 'order':
998
+ case 'credit':
999
+ case 'rich':
1000
+ case 'git':
1054
1001
  case 'tv':
1055
1002
  case 'dw':
1056
- case 'pnl': {
1057
- const { spawnSync } = require('child_process');
1058
- const scriptArgs = buildRuntimeScriptArgs({
1059
- codeRoot: __dirname,
1060
- scriptSegments: ['scripts', command],
1061
- scriptArgs: cliArgs.slice(1),
1062
- });
1063
- const result = spawnSync(Config.EXEC_PATH, scriptArgs, {
1064
- cwd: PATHS.PROJECT_ROOT,
1065
- stdio: 'inherit',
1066
- });
1067
- if (result.error) {
1068
- console.error(`${command}: ${result.error.message}`);
1069
- process.exit(1);
1070
- }
1071
- process.exit(result.status ?? 0);
1072
- return true;
1073
- }
1074
- case 'unlock': {
1075
- const { spawnSync } = require('child_process');
1076
- // buildRuntimeScriptArgs resolves the unlock entry point for the
1077
- // active runtime layout: dist/unlock.js when compiled, unlock.ts
1078
- // in source layouts. A hard-coded dist path silently no-ops
1079
- // (ENOENT -> exit 0), hiding the launcher.
1080
- const unlockArgs = buildRuntimeScriptArgs({
1081
- codeRoot: __dirname,
1082
- scriptSegments: ['unlock'],
1083
- scriptArgs: cliArgs.slice(1),
1084
- });
1085
- const result = spawnSync(Config.EXEC_PATH, unlockArgs, {
1086
- cwd: PATHS.PROJECT_ROOT,
1087
- stdio: 'inherit',
1088
- });
1089
- process.exit(result.status ?? 0);
1090
- return true;
1091
- }
1003
+ case 'liquid':
1004
+ case 'pnl':
1005
+ case 'asset':
1006
+ // Registered analysis/utility entry points; each one owns its
1007
+ // argument parsing, usage text and `--help` (see
1008
+ // HELP_OWNING_COMMANDS), so the CLI only forwards argv.
1009
+ return exitWithRuntimeScript(SCRIPT_COMMANDS[command], command);
1010
+ case 'unlock':
1011
+ // Resolved through buildRuntimeScriptPath for the active runtime
1012
+ // layout (dist/unlock.js when compiled). A hard-coded dist path used
1013
+ // to no-op silently (ENOENT -> exit 0), hiding the launcher.
1014
+ return exitWithRuntimeScript(['unlock'], 'unlock');
1092
1015
  case 'clear':
1093
1016
  case 'clear-orders':
1094
1017
  case 'clear-market-adapter':
@@ -1168,7 +1091,6 @@ async function handleCLICommands() {
1168
1091
  process.exit(code);
1169
1092
  return true;
1170
1093
  };
1171
- const { spawnSync } = require('child_process');
1172
1094
  // Centralized detection (modules/launcher/runtime_mode.ts), shared
1173
1095
  // with the mode-aware help output so the two cannot disagree.
1174
1096
  const runtimeInfo = detectRuntimeMode();
@@ -1176,16 +1098,8 @@ async function handleCLICommands() {
1176
1098
  // so the report matches the help banner; otherwise a live unlock
1177
1099
  // runtime is shown by delegating to `unlock status`.
1178
1100
  if (resolveStatusRoute(runtimeInfo) === 'unlock') {
1179
- const unlockArgs = buildRuntimeScriptArgs({
1180
- codeRoot: __dirname,
1181
- scriptSegments: ['unlock'],
1182
- scriptArgs: ['status', ...(target ? [target] : [])],
1183
- });
1184
- const result = spawnSync(Config.EXEC_PATH, unlockArgs, {
1185
- cwd: PATHS.PROJECT_ROOT,
1186
- stdio: 'inherit',
1187
- });
1188
- return finish(result.status ?? 0);
1101
+ const status = runRuntimeScript(buildRuntimeScriptPath(__dirname, ['unlock']), ['status', ...(target ? [target] : [])], { label: 'unlock', cwd: PATHS.PROJECT_ROOT });
1102
+ return finish(status);
1189
1103
  }
1190
1104
  // status is whole-runtime on every surface. With no unlock bot
1191
1105
  // runtime up, validate and ignore a bot name here so the behavior
@@ -1262,20 +1176,11 @@ async function handleCLICommands() {
1262
1176
  case 'delete':
1263
1177
  case 'stop':
1264
1178
  case 'restart':
1265
- case 'reload': {
1266
- const { spawnSync } = require('child_process');
1267
- const unlockArgs = buildRuntimeScriptArgs({
1268
- codeRoot: __dirname,
1269
- scriptSegments: ['unlock'],
1270
- scriptArgs: [command, ...cliArgs.slice(1)],
1271
- });
1272
- const result = spawnSync(Config.EXEC_PATH, unlockArgs, {
1273
- cwd: PATHS.PROJECT_ROOT,
1274
- stdio: 'inherit',
1275
- });
1276
- process.exit(result.status ?? 0);
1277
- return true;
1278
- }
1179
+ case 'reload':
1180
+ // The unlock runtime owns every lifecycle verb (stop/restart/
1181
+ // reload/delete) for both modes, so the CLI forwards the verb plus
1182
+ // the remaining arguments and mirrors the exit code.
1183
+ return exitWithRuntimeScript(['unlock'], command, [command, ...cliArgs.slice(1)]);
1279
1184
  case 'help':
1280
1185
  printCLIUsage();
1281
1186
  process.exit(0);
@@ -7,10 +7,14 @@
7
7
  * register handlers instead of re-listing the same switch cases; the walker
8
8
  * owns value consumption, `--help`/`-h`, and the unknown-flag error.
9
9
  *
10
+ * Values are the next argv token, or the text after `=` in a `--flag=value`
11
+ * token. The `=` form exists because a bare value that itself starts with `--`
12
+ * is rejected as a missing value (`--out --weird` fails, `--out=--weird` works).
13
+ *
10
14
  * Deliberately free of Node globals: callers pass in their own argv and own
11
15
  * the `process.exit` policy via `onHelp`, so this module stays browser-safe.
12
16
  */
13
- export interface CliArgHandlers {
17
+ interface CliArgHandlers {
14
18
  /** Flags that take a value; receives the raw next argv token (never missing or flag-shaped). */
15
19
  value?: Record<string, (raw: string) => void>;
16
20
  /** Flags that take no value. */
@@ -19,4 +23,5 @@ export interface CliArgHandlers {
19
23
  onHelp: () => void;
20
24
  }
21
25
  export declare function walkCliArgs(args: readonly string[], handlers: CliArgHandlers): void;
26
+ export {};
22
27
  //# sourceMappingURL=cli_args.d.ts.map
@@ -1,16 +1,27 @@
1
1
  'use strict';
2
2
  export function walkCliArgs(args, handlers) {
3
3
  for (let i = 0; i < args.length; i++) {
4
- const a = args[i];
4
+ const rawArg = args[i];
5
+ // `--flag=value` keeps a value that itself starts with `--` addressable.
6
+ const eq = rawArg.startsWith('--') ? rawArg.indexOf('=') : -1;
7
+ const inlineValue = eq > 2 ? rawArg.slice(eq + 1) : undefined;
8
+ const a = eq > 2 ? rawArg.slice(0, eq) : rawArg;
5
9
  if (a === '--gridResetFactor') {
6
10
  throw new Error('--gridResetFactor is no longer supported; use --deltaPercent <percent>');
7
11
  }
8
12
  if (a === '--help' || a === '-h') {
13
+ if (inlineValue !== undefined) {
14
+ throw new Error(`Flag ${a} does not take a value`);
15
+ }
9
16
  handlers.onHelp();
10
17
  continue;
11
18
  }
12
19
  const valueHandler = handlers.value?.[a];
13
20
  if (valueHandler) {
21
+ if (inlineValue !== undefined) {
22
+ valueHandler(inlineValue);
23
+ continue;
24
+ }
14
25
  const raw = args[i + 1];
15
26
  if (raw === undefined || raw.startsWith('--')) {
16
27
  throw new Error(`Flag ${a} expects a value; got ${raw === undefined ? 'nothing' : raw}`);
@@ -21,10 +32,13 @@ export function walkCliArgs(args, handlers) {
21
32
  }
22
33
  const flagHandler = handlers.flag?.[a];
23
34
  if (flagHandler) {
35
+ if (inlineValue !== undefined) {
36
+ throw new Error(`Flag ${a} does not take a value`);
37
+ }
24
38
  flagHandler();
25
39
  continue;
26
40
  }
27
- throw new Error(`Unknown argument: ${a}`);
41
+ throw new Error(`Unknown argument: ${rawArg}`);
28
42
  }
29
43
  }
30
44
  //# sourceMappingURL=cli_args.js.map
@@ -81,5 +81,9 @@ declare function resolveRequestedFillRange(cfg: KibanaCandleConfig, nowMs?: numb
81
81
  */
82
82
  declare function fetchKibanaCandles({ opType, fieldMap, assetA, assetB, config, poolId }: KibanaCandlesParams): Promise<number[][]>;
83
83
  declare function fetchKibanaClosePrices(params: KibanaCandlesParams): Promise<number[]>;
84
- export { buildDirectionalDocumentQuery, resolveRequestedFillRange, fetchKibanaCandles, fetchKibanaClosePrices, sourceFieldsForFieldMap, hitSortKey, hitSequence };
84
+ export { buildDirectionalDocumentQuery, resolveRequestedFillRange, fetchKibanaCandles, fetchKibanaClosePrices, hitSortKey, hitSequence };
85
+ /** Internal seams exercised directly by tests. */
86
+ export declare const __test: {
87
+ sourceFieldsForFieldMap: typeof sourceFieldsForFieldMap;
88
+ };
85
89
  //# sourceMappingURL=kibana_candles.d.ts.map
@@ -418,5 +418,7 @@ async function fetchKibanaClosePrices(params) {
418
418
  const candles = await fetchKibanaCandles(params);
419
419
  return candles.map((candle) => candle[4]);
420
420
  }
421
- export { buildDirectionalDocumentQuery, resolveRequestedFillRange, fetchKibanaCandles, fetchKibanaClosePrices, sourceFieldsForFieldMap, hitSortKey, hitSequence };
421
+ export { buildDirectionalDocumentQuery, resolveRequestedFillRange, fetchKibanaCandles, fetchKibanaClosePrices, hitSortKey, hitSequence };
422
+ /** Internal seams exercised directly by tests. */
423
+ export const __test = { sourceFieldsForFieldMap };
422
424
  //# sourceMappingURL=kibana_candles.js.map
@@ -105,5 +105,11 @@ export interface RegimeMultiplierResult {
105
105
  series: number[];
106
106
  }
107
107
  declare function computeRegimeMultiplier(closes: unknown, opts?: RegimeOpts): RegimeMultiplierResult;
108
- export { computeRegimeMultiplier, _resetRegimeCache, _locateResume, _analyzerBufferSize };
108
+ export { computeRegimeMultiplier };
109
+ /** Internal seams exercised directly by tests. */
110
+ export declare const __test: {
111
+ _resetRegimeCache: typeof _resetRegimeCache;
112
+ _locateResume: typeof _locateResume;
113
+ _analyzerBufferSize: typeof _analyzerBufferSize;
114
+ };
109
115
  //# sourceMappingURL=regime_gate.d.ts.map
@@ -294,5 +294,7 @@ function computeRegimeMultiplier(closes, opts = {}) {
294
294
  series: series.map((value) => roundTo(value, 1000)),
295
295
  };
296
296
  }
297
- export { computeRegimeMultiplier, _resetRegimeCache, _locateResume, _analyzerBufferSize };
297
+ export { computeRegimeMultiplier };
298
+ /** Internal seams exercised directly by tests. */
299
+ export const __test = { _resetRegimeCache, _locateResume, _analyzerBufferSize };
298
300
  //# sourceMappingURL=regime_gate.js.map
@@ -7,7 +7,7 @@
7
7
  * a one-liner and guarantees identical handling across exchanges.
8
8
  */
9
9
  export type CandleRow = [number, number, number, number, number, number];
10
- export interface OhlcIndexes {
10
+ interface OhlcIndexes {
11
11
  minLength: number;
12
12
  ts: number;
13
13
  open: number;
@@ -21,9 +21,14 @@ export declare const OHLC_CLOSE_HIGH_LOW: OhlcIndexes;
21
21
  export declare const OHLC_GATE: OhlcIndexes;
22
22
  export declare const OHLC_KRAKEN: OhlcIndexes;
23
23
  /** Normalize a seconds- or milliseconds-epoch timestamp to milliseconds. */
24
- export declare function normalizeTimestamp(raw: unknown): number;
24
+ declare function normalizeTimestamp(raw: unknown): number;
25
25
  export declare function parseCandleRow(row: unknown, idx: OhlcIndexes): CandleRow | null;
26
26
  export declare function parseCandleRows(rows: unknown[], idx: OhlcIndexes): CandleRow[];
27
27
  /** HTX can return objects instead of arrays; map those to the shared shape. */
28
28
  export declare function parseHtxObjectRow(row: unknown): CandleRow | null;
29
+ /** Internal seams exercised directly by tests. */
30
+ export declare const __test: {
31
+ normalizeTimestamp: typeof normalizeTimestamp;
32
+ };
33
+ export {};
29
34
  //# sourceMappingURL=cex_candle_parsing.d.ts.map
@@ -9,7 +9,7 @@ export const OHLC_GATE = { minLength: 7, ts: 0, open: 5, high: 3, low: 4, close:
9
9
  // Kraken OHLC: [tsSeconds, open, high, low, close, vwap, volume, count].
10
10
  export const OHLC_KRAKEN = { minLength: 7, ts: 0, open: 1, high: 2, low: 3, close: 4, volume: 6 };
11
11
  /** Normalize a seconds- or milliseconds-epoch timestamp to milliseconds. */
12
- export function normalizeTimestamp(raw) {
12
+ function normalizeTimestamp(raw) {
13
13
  const ts = Number(raw);
14
14
  if (!Number.isFinite(ts))
15
15
  return Number.NaN;
@@ -49,4 +49,6 @@ export function parseHtxObjectRow(row) {
49
49
  return null;
50
50
  return [ts, open, high, low, close, Number.isFinite(volume) ? volume : 0];
51
51
  }
52
+ /** Internal seams exercised directly by tests. */
53
+ export const __test = { normalizeTimestamp };
52
54
  //# sourceMappingURL=cex_candle_parsing.js.map
@@ -26,5 +26,11 @@ declare function isBookChunkMatch(metaInput: unknown, requestKeyInput: unknown):
26
26
  * @returns {Promise<Array>} [[timestamp_ms, open, high, low, close, volume_A], ...]
27
27
  */
28
28
  declare function fetchMarketCandlesSequentially(assetA: AssetRef, assetB: AssetRef, opts?: BookFetchOpts): Promise<number[][]>;
29
- export { bookCacheKey, bookOutputPath, isBookChunkMatch, fetchMarketCandlesSequentially, };
29
+ export { fetchMarketCandlesSequentially };
30
+ /** Internal seams exercised directly by tests. */
31
+ export declare const __test: {
32
+ bookCacheKey: typeof bookCacheKey;
33
+ bookOutputPath: typeof bookOutputPath;
34
+ isBookChunkMatch: typeof isBookChunkMatch;
35
+ };
30
36
  //# sourceMappingURL=fetch_book_data.d.ts.map
@@ -159,5 +159,7 @@ async function fetchMarketCandlesSequentially(assetA, assetB, opts = {}) {
159
159
  });
160
160
  return flipped ? invertCandleSeries(merged, { volume: 'scale' }) : merged;
161
161
  }
162
- export { bookCacheKey, bookOutputPath, isBookChunkMatch, fetchMarketCandlesSequentially, };
162
+ export { fetchMarketCandlesSequentially };
163
+ /** Internal seams exercised directly by tests. */
164
+ export const __test = { bookCacheKey, bookOutputPath, isBookChunkMatch };
163
165
  //# sourceMappingURL=fetch_book_data.js.map
@@ -613,17 +613,8 @@ function applyBotDerivedConfig(config) {
613
613
  if (!next.quoteProvided && botContext.bot.assetB) {
614
614
  next.quote = normalizeCexAssetSymbol(botContext.bot.assetB);
615
615
  }
616
- const baseCfg = MARKET_ADAPTER_DEFAULTS || {
617
- amaSlope: {
618
- lookbackBars: MARKET_ADAPTER.DYNAMIC_WEIGHT_AMA_LOOKBACK_BARS,
619
- },
620
- };
621
- const botCfg = typeof resolveBotCfg === 'function'
622
- ? resolveBotCfg(botContext.bot, baseCfg)
623
- : baseCfg;
624
- const botAma = typeof resolveAmaForBot === 'function'
625
- ? resolveAmaForBot(botContext.bot, null, botCfg)
626
- : null;
616
+ const botCfg = resolveBotCfg(botContext.bot, MARKET_ADAPTER_DEFAULTS);
617
+ const botAma = resolveAmaForBot(botContext.bot, null, botCfg);
627
618
  return { config: next, botContext, botCfg, botAma };
628
619
  }
629
620
  function printHelp() {
@@ -33,6 +33,23 @@ interface BotConfig {
33
33
  assetB?: string;
34
34
  [key: string]: unknown;
35
35
  }
36
+ declare function parseArgs(): {
37
+ poolId: null;
38
+ botName: null;
39
+ precA: null;
40
+ precB: null;
41
+ config: {
42
+ intervalSeconds: number;
43
+ lookbackHours: number;
44
+ apiKey: string | null;
45
+ chunkMonths: number;
46
+ timeRange?: {
47
+ gte?: string;
48
+ lte?: string;
49
+ };
50
+ outPath?: string;
51
+ };
52
+ };
36
53
  declare function outputPath(poolId: unknown, intervalSeconds: number, assetA: AssetRef, assetB: AssetRef): string;
37
54
  declare function applyPrecisionOverrides(assetA: AssetRef, assetB: AssetRef, precA: number | null, precB: number | null): {
38
55
  assetA: AssetRef;
@@ -57,5 +74,13 @@ declare function parseBotsConfig(raw: string, sourceLabel?: string): BotConfig[]
57
74
  * Pick a bot: by name if given, otherwise first active bot with startPrice: "pool".
58
75
  */
59
76
  declare function selectBot(bots: BotConfig[], botName: string | null | undefined): BotConfig;
60
- export { applyPrecisionOverrides, parseBotsConfig, selectBot, fetchCandlesSequentially, outputPath, loadCachedFetchContext };
77
+ export { fetchCandlesSequentially, outputPath };
78
+ /** Internal seams exercised directly by tests. */
79
+ export declare const __test: {
80
+ applyPrecisionOverrides: typeof applyPrecisionOverrides;
81
+ parseBotsConfig: typeof parseBotsConfig;
82
+ selectBot: typeof selectBot;
83
+ loadCachedFetchContext: typeof loadCachedFetchContext;
84
+ parseArgs: typeof parseArgs;
85
+ };
61
86
  //# sourceMappingURL=fetch_lp_data.d.ts.map