dexbot 1.6.12 → 1.6.13

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 (170) hide show
  1. package/CHANGELOG.md +33 -1
  2. package/analysis/README.md +9 -11
  3. package/analysis/ama_fitting/README.md +5 -3
  4. package/claw/README.md +1 -0
  5. package/claw/docs/AI_BOT_LIBRARY_API.md +2 -0
  6. package/claw/modules/claw_bridge.ts +0 -3
  7. package/claw/modules/claw_skill_md.ts +1 -0
  8. package/claw/package.json +3 -3
  9. package/claw/runtimes/openclaw-plugin/openclaw.plugin.json +1 -1
  10. package/claw/runtimes/openclaw-plugin/package.json +1 -1
  11. package/claw/tsconfig.json +2 -2
  12. package/dist/analysis/ama_fitting/analyze_lambda_vs_slow.js +1 -14
  13. package/dist/analysis/ama_fitting/fetch_lp_candles.js +51 -41
  14. package/dist/analysis/ama_fitting/generate_unified_comparison_chart.d.ts +1 -24
  15. package/dist/analysis/ama_fitting/generate_unified_comparison_chart.js +36 -18
  16. package/dist/analysis/ama_fitting/optimizer_high_resolution.js +18 -66
  17. package/dist/analysis/analyze_args.d.ts +12 -0
  18. package/dist/analysis/analyze_args.js +20 -0
  19. package/dist/analysis/bot_fitting/backtest_ama_sweep.d.ts +1 -16
  20. package/dist/analysis/bot_fitting/backtest_ama_sweep.js +20 -101
  21. package/dist/analysis/bot_fitting/backtest_bot_fitting.js +26 -92
  22. package/dist/analysis/bot_fitting/backtest_lookback_drawdown.js +19 -34
  23. package/dist/analysis/bot_fitting/shared_utils.d.ts +71 -3
  24. package/dist/analysis/bot_fitting/shared_utils.js +124 -8
  25. package/dist/analysis/chart_ui.d.ts +30 -1
  26. package/dist/analysis/chart_ui.js +37 -1
  27. package/dist/analysis/fills_cache.d.ts +3 -23
  28. package/dist/analysis/fills_cache.js +3 -84
  29. package/dist/analysis/fills_source.d.ts +31 -1
  30. package/dist/analysis/fills_source.js +69 -1
  31. package/dist/analysis/grid_correction_check.d.ts +1 -23
  32. package/dist/analysis/grid_correction_check.js +15 -58
  33. package/dist/analysis/math_utils.d.ts +85 -1
  34. package/dist/analysis/math_utils.js +116 -1
  35. package/dist/analysis/price_sources.d.ts +22 -1
  36. package/dist/analysis/price_sources.js +23 -0
  37. package/dist/analysis/resolve_source.js +31 -10
  38. package/dist/analysis/trade_profitability.d.ts +6 -0
  39. package/dist/analysis/trade_profitability.js +23 -97
  40. package/dist/analysis/tradingview/analyze_tradingview.d.ts +1 -17
  41. package/dist/analysis/tradingview/analyze_tradingview.js +1 -1
  42. package/dist/analysis/tradingview/tradingview_uplot_chart_generator.js +2 -15
  43. package/dist/analysis/trend_detection/backtest_ama_slope_huber.d.ts +1 -101
  44. package/dist/analysis/trend_detection/backtest_ama_slope_huber.js +22 -80
  45. package/dist/analysis/trend_detection/dynamic_weight_chart_generator.js +11 -37
  46. package/dist/analysis/trend_detection/volatility_chart_generator.js +9 -10
  47. package/dist/analysis/worker_pool.d.ts +38 -0
  48. package/dist/analysis/worker_pool.js +67 -0
  49. package/dist/dexbot.js +67 -48
  50. package/dist/market_adapter/ama_signal_runner.js +21 -54
  51. package/dist/market_adapter/candle_utils.d.ts +7 -1
  52. package/dist/market_adapter/candle_utils.js +11 -1
  53. package/dist/market_adapter/cli_args.d.ts +22 -0
  54. package/dist/market_adapter/cli_args.js +30 -0
  55. package/dist/market_adapter/core/config_normalizers.js +11 -6
  56. package/dist/market_adapter/core/kibana_candles.d.ts +3 -1
  57. package/dist/market_adapter/core/kibana_candles.js +3 -2
  58. package/dist/market_adapter/core/market_adapter_service.d.ts +85 -85
  59. package/dist/market_adapter/core/market_adapter_service.js +93 -158
  60. package/dist/market_adapter/core/signals/hurst_analyzer.d.ts +1 -6
  61. package/dist/market_adapter/core/signals/hurst_analyzer.js +1 -1
  62. package/dist/market_adapter/core/signals/permutation_entropy_analyzer.d.ts +1 -11
  63. package/dist/market_adapter/core/signals/permutation_entropy_analyzer.js +1 -1
  64. package/dist/market_adapter/inputs/fetch_book_data.js +0 -1
  65. package/dist/market_adapter/inputs/fetch_cex_synthetic_data.js +63 -107
  66. package/dist/market_adapter/inputs/fetch_lp_data.d.ts +8 -1
  67. package/dist/market_adapter/inputs/fetch_lp_data.js +25 -7
  68. package/dist/market_adapter/inputs/kibana_feed_source.js +4 -26
  69. package/dist/market_adapter/inputs/window_cache.d.ts +4 -72
  70. package/dist/market_adapter/inputs/window_cache.js +52 -177
  71. package/dist/market_adapter/interval_utils.d.ts +11 -1
  72. package/dist/market_adapter/interval_utils.js +16 -1
  73. package/dist/market_adapter/lp_chart_runner.d.ts +3 -0
  74. package/dist/market_adapter/lp_chart_runner.js +37 -19
  75. package/dist/market_adapter/market_adapter.js +27 -72
  76. package/dist/market_adapter/utils/data_discovery.d.ts +45 -1
  77. package/dist/market_adapter/utils/data_discovery.js +220 -27
  78. package/dist/market_adapter/utils/month_shards.d.ts +84 -0
  79. package/dist/market_adapter/utils/month_shards.js +237 -0
  80. package/dist/modules/account_bots.d.ts +1 -0
  81. package/dist/modules/account_bots.js +102 -121
  82. package/dist/modules/account_orders.d.ts +13 -0
  83. package/dist/modules/account_orders.js +38 -44
  84. package/dist/modules/bitshares-native/chain_client.d.ts +1 -1
  85. package/dist/modules/bitshares-native/chain_client.js +14 -13
  86. package/dist/modules/bitshares-native/resolvers.js +22 -25
  87. package/dist/modules/bitshares-native/serial/types.js +22 -50
  88. package/dist/modules/bitshares-native/signing_client.d.ts +1 -1
  89. package/dist/modules/bot_defaults.d.ts +2 -1
  90. package/dist/modules/bot_settings.d.ts +1 -1
  91. package/dist/modules/broadcast_failure.d.ts +2 -1
  92. package/dist/modules/chain_orders.d.ts +1 -1
  93. package/dist/modules/chain_orders.js +51 -96
  94. package/dist/modules/cli_start_onboarding.d.ts +2 -1
  95. package/dist/modules/constants.d.ts +7 -1
  96. package/dist/modules/constants.js +20 -1
  97. package/dist/modules/cr_planner.d.ts +1 -1
  98. package/dist/modules/cr_planner.js +1 -5
  99. package/dist/modules/credit_pricing.d.ts +2 -1
  100. package/dist/modules/credit_pricing.js +36 -40
  101. package/dist/modules/credit_runtime.d.ts +7 -0
  102. package/dist/modules/credit_runtime.js +45 -73
  103. package/dist/modules/daemon_node_health.d.ts +4 -3
  104. package/dist/modules/dexbot_class.d.ts +28 -17
  105. package/dist/modules/dexbot_class.js +105 -58
  106. package/dist/modules/dexbot_cow_runtime.d.ts +0 -7
  107. package/dist/modules/dexbot_cow_runtime.js +54 -28
  108. package/dist/modules/dexbot_credential_client.d.ts +0 -7
  109. package/dist/modules/dexbot_credential_client.js +1 -2
  110. package/dist/modules/dexbot_fill_runtime.d.ts +1 -2
  111. package/dist/modules/dexbot_fill_runtime.js +5 -6
  112. package/dist/modules/dexbot_maintenance_runtime.d.ts +20 -3
  113. package/dist/modules/dexbot_maintenance_runtime.js +84 -69
  114. package/dist/modules/dexbot_startup_runtime.d.ts +0 -1
  115. package/dist/modules/dexbot_startup_runtime.js +13 -14
  116. package/dist/modules/general_settings.d.ts +1 -1
  117. package/dist/modules/graceful_shutdown.js +17 -11
  118. package/dist/modules/key_store.js +0 -1
  119. package/dist/modules/lazy_shim.d.ts +11 -0
  120. package/dist/modules/lazy_shim.js +16 -0
  121. package/dist/modules/node_connect_policy.d.ts +3 -2
  122. package/dist/modules/node_failure_ledger.d.ts +6 -5
  123. package/dist/modules/order/format.d.ts +12 -3
  124. package/dist/modules/order/format.js +15 -3
  125. package/dist/modules/order/genesis_policy.d.ts +3 -3
  126. package/dist/modules/order/genesis_policy.js +5 -2
  127. package/dist/modules/order/grid.d.ts +4 -2
  128. package/dist/modules/order/grid.js +91 -35
  129. package/dist/modules/order/index.d.ts +1 -0
  130. package/dist/modules/order/logger.d.ts +1 -8
  131. package/dist/modules/order/logger.js +0 -9
  132. package/dist/modules/order/manager.d.ts +9 -13
  133. package/dist/modules/order/manager.js +33 -50
  134. package/dist/modules/order/utils/order.js +39 -35
  135. package/dist/modules/order/utils/system.d.ts +9 -29
  136. package/dist/modules/order/utils/system.js +17 -2
  137. package/dist/modules/order/utils/validate.js +2 -2
  138. package/dist/modules/order/utils/withPoolRef.d.ts +2 -1
  139. package/dist/modules/paths.js +32 -34
  140. package/dist/modules/runtime_settings.d.ts +2 -4
  141. package/dist/modules/settings_merge.d.ts +2 -2
  142. package/dist/modules/socket_json_client.d.ts +2 -1
  143. package/dist/modules/types.d.ts +42 -27
  144. package/dist/modules/utils/errors.js +1 -3
  145. package/dist/modules/version_notice.d.ts +11 -10
  146. package/dist/pm2.d.ts +0 -1
  147. package/dist/pm2.js +56 -35
  148. package/dist/scripts/analyze-git.js +2 -15
  149. package/dist/scripts/chart_command.js +2 -2
  150. package/dist/scripts/check_any.d.ts +4 -0
  151. package/dist/scripts/check_any.js +53 -21
  152. package/dist/scripts/diagnose-pool-history.js +1 -6
  153. package/dist/scripts/run-tests.js +0 -1
  154. package/dist/scripts/sync-version.js +0 -10
  155. package/docs/BITSHARES_ONBOARDING.md +8 -12
  156. package/docs/COPY_ON_WRITE_MASTER_PLAN.md +1 -1
  157. package/docs/DEXBOT_COMPARISON.md +6 -6
  158. package/docs/EVOLUTION.md +9 -8
  159. package/docs/FUND_MOVEMENT_AND_ACCOUNTING.md +1 -1
  160. package/docs/README.md +1 -1
  161. package/docs/WORKFLOW.md +1 -0
  162. package/docs/architecture.md +19 -10
  163. package/market_adapter/README.md +6 -4
  164. package/package.json +6 -9
  165. package/scripts/README.md +43 -38
  166. package/tests/README.md +25 -10
  167. package/dist/scripts/diagnose-kibana-candles.d.ts +0 -3
  168. package/dist/scripts/diagnose-kibana-candles.js +0 -82
  169. package/scripts/git-viewer.sh +0 -489
  170. package/scripts/postinstall.js +0 -16
@@ -0,0 +1,67 @@
1
+ 'use strict';
2
+ import { Worker } from 'node:worker_threads';
3
+ import { fileURLToPath } from 'node:url';
4
+ /**
5
+ * Run a single worker thread whose entry module is the caller itself.
6
+ *
7
+ * ESM has no `__filename`, so the worker entry is resolved from the caller's
8
+ * `import.meta.url` — the caller passes its own `import.meta.url`. The worker
9
+ * module must branch on `isMainThread` to run its handler and should let the
10
+ * thread exit naturally after `parentPort.postMessage`: an explicit
11
+ * `process.exit(0)` can race the message flush and silently drop the result
12
+ * (this was duplicated in optimizer_high_resolution and backtest_ama_sweep).
13
+ *
14
+ * Rejects on `error`, on a non-zero `exit` code, and on a clean exit that never
15
+ * posted a resolvable result (previously that case hung forever).
16
+ */
17
+ function runModuleWorker(callerModuleUrl, workerData, { onProgress, resolveOn }) {
18
+ return new Promise((resolve, reject) => {
19
+ let settled = false;
20
+ const worker = new Worker(fileURLToPath(callerModuleUrl), { workerData });
21
+ worker.on('message', (msg) => {
22
+ const outcome = resolveOn(msg);
23
+ if (outcome.done) {
24
+ settled = true;
25
+ resolve(outcome.value);
26
+ return;
27
+ }
28
+ if (onProgress)
29
+ onProgress(msg);
30
+ });
31
+ worker.on('error', (err) => {
32
+ settled = true;
33
+ reject(err);
34
+ });
35
+ worker.on('exit', (code) => {
36
+ if (settled)
37
+ return;
38
+ if (code !== 0) {
39
+ settled = true;
40
+ reject(new Error(`Worker exited with code ${code}`));
41
+ return;
42
+ }
43
+ // Defer so a final `message` already in flight is processed first;
44
+ // only a genuinely result-less clean exit rejects.
45
+ setImmediate(() => {
46
+ if (settled)
47
+ return;
48
+ settled = true;
49
+ reject(new Error('Worker exited without posting a result'));
50
+ });
51
+ });
52
+ });
53
+ }
54
+ /**
55
+ * Split `values` into at most `shardCount` contiguous, roughly equal chunks.
56
+ * Empty chunks are dropped. Single home for the copy in optimizer_high_resolution.
57
+ */
58
+ function splitIntoShards(values, shardCount) {
59
+ const out = [];
60
+ const size = Math.ceil(values.length / shardCount);
61
+ for (let i = 0; i < values.length; i += size) {
62
+ out.push(values.slice(i, i + size));
63
+ }
64
+ return out.filter((s) => s.length > 0);
65
+ }
66
+ export { runModuleWorker, splitIntoShards };
67
+ //# sourceMappingURL=worker_pool.js.map
package/dist/dexbot.js CHANGED
@@ -44,17 +44,16 @@ const __dirname = _esmDirname(__filename);
44
44
  * `dexbot help` is the single source of truth (grouped one-liners below;
45
45
  * `dexbot --cli-examples` prints curated snippets):
46
46
  *
47
- * Runtime: dexbot start [bot] | stop | reload | restart | delete | status
48
- * dexbot pm2 [stop|delete|restart|reload|claw-only|update|help]
47
+ * Runtime: dexbot start [bot] | stop | reload | restart | delete | status | pm2
49
48
  * Trading: dexbot test <bot> | drystart <bot> | reset {all|<bot>}
50
49
  * Config: dexbot bot | key | enable {all|<bot>} | disable {all|<bot>} | default | update
51
- * Analysis: dexbot order [<bot>] [--export] | export <bot> | credit [<bot>]
52
- * dexbot tv <target> | dw <target>
50
+ * Analysis: dexbot order [<bot>] | export <bot> | credit [<bot>]
51
+ * dexbot tv <target> | dw <target> | pnl <account>
53
52
  * Files: dexbot clear | clear-orders | clear-market-adapter | clear-all
54
53
  *
55
54
  * NPM SCRIPTS (alternative invocation):
56
- * npm run pm2:start - Start bots (requires ecosystem.config.cjs pre-generated)
57
- * npm run pm2:stop - Stop all PM2 bots
55
+ * npm run pm2:start - Unlock + start bots via PM2 (alias of pm2:unlock)
56
+ * npm run pm2:stop - Stop all dexbot PM2 processes via the launcher
58
57
  * npm run pm2:unlock - Run dist/pm2.js (authenticate + generate config + start all)
59
58
  * npm run pm2:claw-only - Run dist/pm2.js claw-only
60
59
  *
@@ -143,28 +142,23 @@ if (typeof credentialPolicy.checkPolicyFileSecurity === 'function')
143
142
  // Primary CLI driver that manages tracked bots and helper utilities such as key/bot editors.
144
143
  const PROFILES_BOTS_FILE = PATHS.PROFILES.BOTS_JSON;
145
144
  const PROFILES_DIR = PATHS.PROFILES_DIR;
146
- const CLI_COMMANDS = ['start', 'test', 'reset', 'default', 'disable', 'enable', 'drystart', 'key', 'bot', 'pm2', 'update', 'export', 'order', 'credit', 'tv', 'dw', 'pnl', 'clear', 'clear-orders', 'clear-market-adapter', 'clear-all', 'status', 'unlock', 'delete', 'stop', 'restart', 'reload', 'help'];
145
+ const CLI_COMMANDS = ['start', 'test', 'reset', 'default', 'disable', 'enable', 'drystart', 'key', 'bot', 'pm2', 'update', 'export', 'order', 'credit', 'tv', 'dw', 'pnl', 'git', 'clear', 'clear-orders', 'clear-market-adapter', 'clear-all', 'status', 'unlock', 'delete', 'stop', 'restart', 'reload', 'help'];
147
146
  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' };
148
147
  const CLI_HELP_FLAGS = ['-h', '--help'];
149
148
  const CLI_EXAMPLES_FLAG = '--cli-examples';
150
149
  const CLI_EXAMPLES = [
151
- { title: 'Run a bot from the tracked config', command: 'dexbot test <bot>', notes: 'Runs live; targets the named entry in profiles/bots.json.' },
152
- { title: 'Dry-run a bot without broadcasting', command: 'dexbot drystart <bot>', notes: 'Forces the run into dry-run mode even if the stored config was live.' },
153
- { title: 'Disable a bot in config', command: 'dexbot disable <bot>', notes: 'Marks the bot inactive in config.' },
154
- { title: 'Enable a bot in config', command: 'dexbot enable <bot>', notes: 'Marks the bot active in config.' },
155
- { title: 'Reset all active bot grids', command: 'dexbot reset all', notes: 'Triggers full grid regeneration for every active bot.' },
156
- { title: 'Reset a bot grid', command: 'dexbot reset <bot>', notes: 'Triggers a full grid regeneration for the named bot.' },
157
- { title: 'Manage keys', command: 'dexbot key', notes: 'Runs modules/chain_keys.ts to add or update master passwords.' },
158
- { title: 'Edit bot definitions', command: 'dexbot bot', notes: 'Launches the interactive modules/account_bots.ts helper for the JSON config.' },
159
- { title: 'Start bots with PM2', command: 'dexbot pm2', notes: 'Generates ecosystem config, authenticates, and starts PM2.' },
160
- { title: 'Update DEXBot2', command: 'dexbot update', notes: 'Fetches latest code, updates dependencies, and restarts PM2.' },
161
- { title: 'Export bot trades for local analysis', command: 'dexbot export <bot>', notes: 'Exports trading history and settings to CSV/JSON (see analysis/).' },
162
- { title: 'Analyze persisted order grids', command: 'dexbot order', notes: 'Runs the order analyzer across the orders directory (<profiles>/orders) and prints spread/increment/funds/distribution metrics. Add a bot key to render only that bot, and --export for an HTML report.' },
163
- { title: 'Show live credit/MPA positions', command: 'dexbot credit', notes: 'Queries get_margin_positions + get_credit_deals_by_borrower per preferredAccount and prints debt/collateral sums plus one Curr. CR line per whitelisted pair (active CR, else borrow-now CR vs funds avail. on the offer) and one Avar. CR line per bot. CR covers only pairs whitelisted in bots.json and listed on the current credit offer. Add a bot key to render only that bot.' },
164
- { title: 'TradingView chart for a bot, pool, or pair', command: 'dexbot tv <bot|pool-id|AssetA/AssetB> --month 3', notes: 'Fetches 1h candles for N months (default 3, pool-first with orderbook fallback; --feed charts MPA price-feed history) and writes an auto-named HTML chart.' },
165
- { title: 'PnL report for a bot or blockchain account', command: 'dexbot pnl <bot|account|1.2.x> --month 3 [--pair BASE/QUOTE]', notes: 'Resolves a local bot profile first, then the chain account, analyzes its fills for the requested window and writes a self-contained HTML PnL report.' },
166
- { title: 'Clear all bot log files', command: 'dexbot clear', notes: 'Runs scripts/clear-logs.sh to remove *.log, rotated *.log.N and *.jsonl* from the logs directory (<profiles>/logs), including the credential audit trail daemon-audit.jsonl and its rotated siblings (named in the preview). Offline only: the scripts warn when a live runtime is detected, but a running bot keeps writing to unlinked files and the space is not freed until it restarts; dexbot clear-orders / clear-market-adapter / clear-all are undone within seconds (grid state is re-persisted, the adapter rewrites its state file and lock). Stop first with dexbot stop / dexbot pm2 stop all.' },
167
- { title: 'Reset settings to defaults', command: 'dexbot default', notes: 'Runs scripts/reset-settings.sh to delete general.settings.json, market_profiles.json, and market_adapter_settings.json.' }
150
+ { title: 'Run a bot live', command: 'dexbot test <bot>', notes: 'Runs the named entry in profiles/bots.json once.' },
151
+ { title: 'Dry-run a bot', command: 'dexbot drystart <bot>', notes: 'Same as test, but never broadcasts.' },
152
+ { title: 'Reset every grid', command: 'dexbot reset all', notes: 'Pass a bot name to reset just one.' },
153
+ { title: 'Manage keys', command: 'dexbot key', notes: 'Set up the master password and keyring.' },
154
+ { title: 'Edit bot config', command: 'dexbot bot', notes: 'Interactive bots.json editor.' },
155
+ { title: 'Start bots with PM2', command: 'dexbot pm2', notes: 'Generate the ecosystem config and start PM2.' },
156
+ { title: 'Update DEXBot2', command: 'dexbot update', notes: 'Pull, install, and restart active bots.' },
157
+ { title: 'Export bot trades', command: 'dexbot export <bot>', notes: 'Write trades and settings to CSV/JSON.' },
158
+ { title: 'Analyze order grids', command: 'dexbot order', notes: 'Spread, increment, and funds; --export for HTML.' },
159
+ { title: 'Show live credit positions', command: 'dexbot credit', notes: 'Summed MPA + borrowed-credit positions per bot.' },
160
+ { 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.' },
161
+ { 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.' }
168
162
  ];
169
163
  const STARTUP_COLORS = {
170
164
  reset: CLI_COLORS.reset,
@@ -194,40 +188,40 @@ function printCLIUsage() {
194
188
  // and the description column is derived, so alignment never drifts.
195
189
  const groups = [
196
190
  ['Runtime', [
197
- ['start [bot]', 'Start the monolithic runtime (--foreground, --isolated, --dryrun, --headless, claw-only, credit).'],
198
- ['stop', 'Stop the monolithic runtime.'],
199
- ['reload', 'Reload the monolithic runtime (leaves credential daemon untouched).'],
200
- ['restart', 'Restart the monolithic runtime (re-unlocks credential daemon).'],
201
- ['delete', 'Stop/delete all runtime processes.'],
202
- ['status', 'Show bot runtime status (unlock monolithic/isolated or PM2).'],
203
- ['pm2 [<sub>]', 'Start all active bots via PM2; also stop/restart/reload/delete (dexbot pm2 help).'],
191
+ ['start [bot]', 'Start the bot runtime (flags below).'],
192
+ ['stop', 'Stop the runtime.'],
193
+ ['reload', 'Reload the runtime without re-unlocking keys.'],
194
+ ['restart', 'Restart the runtime and re-unlock keys.'],
195
+ ['delete', 'Stop and delete all runtime processes.'],
196
+ ['status', 'Show runtime status.'],
197
+ ['pm2 [<sub>]', 'Manage PM2 bots (see: dexbot pm2 help).'],
204
198
  ]],
205
199
  ['Trading', [
206
- ['test <bot>', 'Run the named bot live once (not a dry run).'],
207
- ['drystart <bot>', 'Same as test but forced dry-run.'],
208
- ['reset {all|<bot>}', 'Trigger grid reset(s); auto-reloads if running, else applies on next start.'],
200
+ ['test <bot>', 'Run a bot live once.'],
201
+ ['drystart <bot>', 'Run a bot without broadcasting.'],
202
+ ['reset {all|<bot>}', 'Reset grid state (applies now or on next start).'],
209
203
  ]],
210
204
  ['Config', [
211
- ['bot', 'Interactive bot configurator (bots.json).'],
212
- ['key', 'Set up master password and keyring.'],
205
+ ['bot', 'Interactive bots.json configurator.'],
206
+ ['key', 'Set up the master password and keyring.'],
213
207
  ['enable {all|<bot>}', 'Mark bot(s) active in config.'],
214
208
  ['disable {all|<bot>}', 'Mark bot(s) inactive in config.'],
215
- ['default', 'Reset settings to defaults (deletes generated settings files).'],
216
- ['update', 'Update DEXBot2 from the repository and restart active bots.'],
209
+ ['default', 'Reset generated settings to defaults.'],
210
+ ['update', 'Update DEXBot2 and restart active bots.'],
217
211
  ]],
218
212
  ['Analysis', [
219
- ['order [<bot>]', 'Analyze order grids (spread, increment, funds); --export for HTML.'],
220
- ['export <bot>', 'Export bot trades/settings to CSV/JSON for local analysis.'],
221
- ['credit [<bot>]', 'Live summed MPA + borrowed-credit positions per asset per bot.'],
222
- ['tv <target>', 'TradingView chart: 1h candles for <bot|pool-id|AssetA/AssetB> over --month N (default 3).'],
223
- ['dw <target>', 'Dynamic-weight research chart: same targets/flags as tv (see analysis/).'],
224
- ['pnl <account>', 'PnL HTML report for a bot/account over --month N, optional --pair BASE/QUOTE filter.'],
213
+ ['order [<bot>]', 'Analyze persisted order grids; --export for HTML.'],
214
+ ['export <bot>', 'Export bot trades/settings to CSV/JSON.'],
215
+ ['credit [<bot>]', 'Show live MPA and borrowed-credit positions.'],
216
+ ['tv <target>', 'OHLC chart for <bot|pool-id|AssetA/AssetB>; --month N (default 3), --feed for MPA price-feed history.'],
217
+ ['dw <target>', 'Dynamic-weight research chart; same targets and flags as tv.'],
218
+ ['pnl <account>', 'HTML PnL report for a bot or account; --month N, optional --pair BASE/QUOTE filter.'],
225
219
  ]],
226
220
  ['Files', [
227
- ['clear', 'Delete <profiles>/logs/*.log, *.log.N and *.jsonl* (audit trail included). Stop the runtime first.'],
228
- ['clear-orders', 'Delete persisted grid state in <profiles>/orders (regenerated on next start).'],
229
- ['clear-market-adapter', 'Delete market adapter data, state, lock, and adapter logs.'],
230
- ['clear-all', 'All of the above, plus claw data. Stop the runtime first.'],
221
+ ['clear', 'Delete log files. Stop the runtime first.'],
222
+ ['clear-orders', 'Delete persisted grid state (regenerated on start).'],
223
+ ['clear-market-adapter', 'Delete market adapter data and state.'],
224
+ ['clear-all', 'Delete orders, logs, adapter, and claw data.'],
231
225
  ]],
232
226
  ];
233
227
  const width = Math.max(...groups.flatMap(([, entries]) => entries.map(([cmd]) => cmd.length))) + 2;
@@ -238,6 +232,11 @@ function printCLIUsage() {
238
232
  console.log(` ${cmd.padEnd(width)}${desc}`);
239
233
  }
240
234
  }
235
+ console.log('Runtime flags (dexbot start):');
236
+ console.log(` ${'--foreground'.padEnd(width)}Watch in the terminal (no auto-restart).`);
237
+ console.log(` ${'--isolated'.padEnd(width)}One process per bot.`);
238
+ console.log(` ${'--dryrun'.padEnd(width)}Run without broadcasting.`);
239
+ console.log(` ${'--headless'.padEnd(width)}Non-interactive unlock (--password-file <path> or DEXBOT_MASTER_PASSWORD).`);
241
240
  console.log('Help & options:');
242
241
  console.log(` ${'help, -h, --help'.padEnd(width)}Show this help.`);
243
242
  console.log(` ${'--cli-examples'.padEnd(width)}Print curated CLI snippets.`);
@@ -1009,6 +1008,26 @@ async function handleCLICommands() {
1009
1008
  process.exit(result.status ?? 0);
1010
1009
  return true;
1011
1010
  }
1011
+ case 'git': {
1012
+ // Repository statistics analyzer (scripts/analyze-git.ts): parses
1013
+ // git history and writes analysis/charts/repo-stats.html. Git-only;
1014
+ // it requires a source checkout (.git present).
1015
+ const { spawnSync } = require('child_process');
1016
+ const scriptArgs = buildRuntimeScriptArgs({
1017
+ codeRoot: __dirname,
1018
+ scriptSegments: ['scripts', 'analyze-git'],
1019
+ });
1020
+ const result = spawnSync(Config.EXEC_PATH, scriptArgs, {
1021
+ cwd: PATHS.PROJECT_ROOT,
1022
+ stdio: 'inherit',
1023
+ });
1024
+ if (result.error) {
1025
+ console.error(`git: ${result.error.message}`);
1026
+ process.exit(1);
1027
+ }
1028
+ process.exit(result.status ?? 0);
1029
+ return true;
1030
+ }
1012
1031
  case 'tv':
1013
1032
  case 'dw':
1014
1033
  case 'pnl': {
@@ -15,6 +15,7 @@ import { Config } from '../modules/config.js';
15
15
  * node dist/market_adapter/ama_signal_runner.js --bot <bot> --compact
16
16
  */
17
17
  import { runOnceForAma } from './market_adapter.js';
18
+ import { walkCliArgs } from './cli_args.js';
18
19
  function printHelp() {
19
20
  console.log('AMA signal runner (one cycle): updates candles and returns latest AMA values.');
20
21
  console.log('');
@@ -41,60 +42,26 @@ function parseArgs() {
41
42
  compact: false,
42
43
  overrides: {},
43
44
  };
44
- for (let i = 0; i < args.length; i++) {
45
- const a = args[i];
46
- const v = args[i + 1];
47
- switch (a) {
48
- case '--bot':
49
- out.bot = v;
50
- i++;
51
- break;
52
- case '--deltaPercent':
53
- out.overrides.deltaThresholdPercent = Number(v);
54
- i++;
55
- break;
56
- case '--gridResetFactor':
57
- throw new Error('--gridResetFactor is no longer supported; use --deltaPercent <percent>');
58
- case '--bootstrapHours':
59
- out.overrides.bootstrapLookbackHours = Number(v);
60
- i++;
61
- break;
62
- case '--nativeBackfillHours':
63
- out.overrides.nativeBackfillHours = Number(v);
64
- i++;
65
- break;
66
- case '--maxStaleHours':
67
- out.overrides.maxStaleHours = Number(v);
68
- i++;
69
- break;
70
- case '--sourceRetries':
71
- out.overrides.sourceRetries = Number(v);
72
- i++;
73
- break;
74
- case '--retryDelayMs':
75
- out.overrides.retryDelayMs = Number(v);
76
- i++;
77
- break;
78
- case '--maxPages':
79
- out.overrides.maxPages = Number(v);
80
- i++;
81
- break;
82
- case '--pageLimit':
83
- out.overrides.pageLimit = Number(v);
84
- i++;
85
- break;
86
- case '--compact':
87
- out.compact = true;
88
- break;
89
- case '--help':
90
- case '-h':
91
- printHelp();
92
- process.exit(0);
93
- break;
94
- default:
95
- throw new Error(`Unknown argument: ${a}`);
96
- }
97
- }
45
+ walkCliArgs(args, {
46
+ onHelp: () => {
47
+ printHelp();
48
+ process.exit(0);
49
+ },
50
+ flag: {
51
+ '--compact': () => { out.compact = true; },
52
+ },
53
+ value: {
54
+ '--bot': (v) => { out.bot = v ?? null; },
55
+ '--deltaPercent': (v) => { out.overrides.deltaThresholdPercent = Number(v); },
56
+ '--bootstrapHours': (v) => { out.overrides.bootstrapLookbackHours = Number(v); },
57
+ '--nativeBackfillHours': (v) => { out.overrides.nativeBackfillHours = Number(v); },
58
+ '--maxStaleHours': (v) => { out.overrides.maxStaleHours = Number(v); },
59
+ '--sourceRetries': (v) => { out.overrides.sourceRetries = Number(v); },
60
+ '--retryDelayMs': (v) => { out.overrides.retryDelayMs = Number(v); },
61
+ '--maxPages': (v) => { out.overrides.maxPages = Number(v); },
62
+ '--pageLimit': (v) => { out.overrides.pageLimit = Number(v); },
63
+ },
64
+ });
98
65
  return out;
99
66
  }
100
67
  function isFiniteOrNull(v) {
@@ -67,8 +67,14 @@ declare function detectStaleTail(candles: unknown, threshold: number): {
67
67
  * @returns {Array} candles with stale tail removed
68
68
  */
69
69
  declare function pruneStaleTail(candles: unknown, threshold: number): unknown;
70
+ /**
71
+ * Collision resolver for `mergeCandles`: on a duplicate timestamp keep the
72
+ * candle with the higher volume (index 5). Shared by the window cache and
73
+ * the data-discovery loader so both pick the same winner.
74
+ */
75
+ declare function higherVolumeWins(existing: unknown, incoming: unknown): unknown;
70
76
  declare function mergeCandles(a: unknown, b: unknown, { onCollision }?: {
71
77
  onCollision?: (existing: unknown, incoming: unknown) => unknown;
72
78
  }): number[][];
73
- export { getCandleClose, getCandleTimestamp, normalizeCandle, tradesToCandles, detectMissingCandleTimestamps, fillCandleGaps, detectStaleTail, pruneStaleTail, mergeCandles };
79
+ export { getCandleClose, getCandleTimestamp, normalizeCandle, tradesToCandles, detectMissingCandleTimestamps, fillCandleGaps, detectStaleTail, pruneStaleTail, mergeCandles, higherVolumeWins };
74
80
  //# sourceMappingURL=candle_utils.d.ts.map
@@ -272,6 +272,16 @@ function pruneStaleTail(candles, threshold) {
272
272
  const keepCount = sorted.length - runLength;
273
273
  return keepCount > 0 ? sorted.slice(0, keepCount) : [];
274
274
  }
275
+ /**
276
+ * Collision resolver for `mergeCandles`: on a duplicate timestamp keep the
277
+ * candle with the higher volume (index 5). Shared by the window cache and
278
+ * the data-discovery loader so both pick the same winner.
279
+ */
280
+ function higherVolumeWins(existing, incoming) {
281
+ const a = existing;
282
+ const b = incoming;
283
+ return Number(b?.[5] || 0) > Number(a?.[5] || 0) ? incoming : existing;
284
+ }
275
285
  function mergeCandles(a, b, { onCollision } = {}) {
276
286
  const map = new Map();
277
287
  for (const c of [...(a || []), ...(b || [])]) {
@@ -290,5 +300,5 @@ function mergeCandles(a, b, { onCollision } = {}) {
290
300
  }
291
301
  return [...map.values()].sort((x, y) => x[0] - y[0]);
292
302
  }
293
- export { getCandleClose, getCandleTimestamp, normalizeCandle, tradesToCandles, detectMissingCandleTimestamps, fillCandleGaps, detectStaleTail, pruneStaleTail, mergeCandles };
303
+ export { getCandleClose, getCandleTimestamp, normalizeCandle, tradesToCandles, detectMissingCandleTimestamps, fillCandleGaps, detectStaleTail, pruneStaleTail, mergeCandles, higherVolumeWins };
294
304
  //# sourceMappingURL=candle_utils.js.map
@@ -0,0 +1,22 @@
1
+ /**
2
+ * Shared argument walker for the market_adapter CLI entry points.
3
+ *
4
+ * The runners expose an overlapping set of source/window tuning flags that
5
+ * must behave identically everywhere (`--bootstrapHours`, `--sourceRetries`,
6
+ * `--maxPages`, the unsupported `--gridResetFactor` guard, ...). Callers
7
+ * register handlers instead of re-listing the same switch cases; the walker
8
+ * owns value consumption, `--help`/`-h`, and the unknown-flag error.
9
+ *
10
+ * Deliberately free of Node globals: callers pass in their own argv and own
11
+ * the `process.exit` policy via `onHelp`, so this module stays browser-safe.
12
+ */
13
+ export interface CliArgHandlers {
14
+ /** Flags that take a value; receives the raw next argv token (never missing or flag-shaped). */
15
+ value?: Record<string, (raw: string) => void>;
16
+ /** Flags that take no value. */
17
+ flag?: Record<string, () => void>;
18
+ /** Invoked for `--help` / `-h`; the caller decides whether to exit. */
19
+ onHelp: () => void;
20
+ }
21
+ export declare function walkCliArgs(args: readonly string[], handlers: CliArgHandlers): void;
22
+ //# sourceMappingURL=cli_args.d.ts.map
@@ -0,0 +1,30 @@
1
+ 'use strict';
2
+ export function walkCliArgs(args, handlers) {
3
+ for (let i = 0; i < args.length; i++) {
4
+ const a = args[i];
5
+ if (a === '--gridResetFactor') {
6
+ throw new Error('--gridResetFactor is no longer supported; use --deltaPercent <percent>');
7
+ }
8
+ if (a === '--help' || a === '-h') {
9
+ handlers.onHelp();
10
+ continue;
11
+ }
12
+ const valueHandler = handlers.value?.[a];
13
+ if (valueHandler) {
14
+ const raw = args[i + 1];
15
+ if (raw === undefined || raw.startsWith('--')) {
16
+ throw new Error(`Flag ${a} expects a value; got ${raw === undefined ? 'nothing' : raw}`);
17
+ }
18
+ valueHandler(raw);
19
+ i++;
20
+ continue;
21
+ }
22
+ const flagHandler = handlers.flag?.[a];
23
+ if (flagHandler) {
24
+ flagHandler();
25
+ continue;
26
+ }
27
+ throw new Error(`Unknown argument: ${a}`);
28
+ }
29
+ }
30
+ //# sourceMappingURL=cli_args.js.map
@@ -12,18 +12,23 @@ function normalizeAtrPeriod(period, defaultValue = MARKET_ADAPTER.DYNAMIC_WEIGHT
12
12
  const rounded = Math.round(value);
13
13
  return Math.max(MARKET_ADAPTER.DYNAMIC_WEIGHT_ATR_PERIOD_MIN, Math.min(MARKET_ADAPTER.DYNAMIC_WEIGHT_ATR_PERIOD_MAX, rounded));
14
14
  }
15
- function normalizeMaxVolatilityOffset(value, defaultValue = MARKET_ADAPTER.DYNAMIC_WEIGHT_SYMMETRIC_SHIFT_CLAMP) {
15
+ /**
16
+ * Coerce to a finite, non-negative number, else `defaultValue`. `null`,
17
+ * `undefined` and `''` are treated as "not provided" before `Number()`
18
+ * coercion so explicit JSON null does not become 0. Zero is allowed (it
19
+ * explicitly disables the volatility shift).
20
+ */
21
+ function normalizeNonNegative(value, defaultValue) {
16
22
  if (value == null || value === '')
17
23
  return defaultValue;
18
24
  const numeric = Number(value);
19
- // Allow 0 to explicitly disable volatility shift
20
25
  return Number.isFinite(numeric) && numeric >= 0 ? numeric : defaultValue;
21
26
  }
27
+ function normalizeMaxVolatilityOffset(value, defaultValue = MARKET_ADAPTER.DYNAMIC_WEIGHT_SYMMETRIC_SHIFT_CLAMP) {
28
+ return normalizeNonNegative(value, defaultValue);
29
+ }
22
30
  function normalizeVolatilityThreshold(value, defaultValue = MARKET_ADAPTER.DYNAMIC_WEIGHT_SYMMETRIC_SHIFT_THRESHOLD) {
23
- if (value == null || value === '')
24
- return defaultValue;
25
- const numeric = Number(value);
26
- return Number.isFinite(numeric) && numeric >= 0 ? numeric : defaultValue;
31
+ return normalizeNonNegative(value, defaultValue);
27
32
  }
28
33
  export { normalizeAtrPeriod, normalizeMaxVolatilityOffset, normalizeVolatilityThreshold };
29
34
  //# sourceMappingURL=config_normalizers.js.map
@@ -59,6 +59,8 @@ interface KibanaCandlesParams {
59
59
  */
60
60
  declare function sourceFieldsForFieldMap(fieldMap: FieldMap | null | undefined): string[];
61
61
  declare function buildDirectionalDocumentQuery({ opType, soldAssetField, receivedAssetField, poolField, soldAssetId, receivedAssetId, lookbackHours, poolId, timeRange, size, searchAfter, sourceFields }: DirectionalQueryParams): Record<string, unknown>;
62
+ declare function hitSortKey(hit: unknown): string;
63
+ declare function hitSequence(source: unknown, operationIdField: unknown): number;
62
64
  declare function resolveRequestedFillRange(cfg: KibanaCandleConfig, nowMs?: number): {
63
65
  startTs: number | null;
64
66
  endTs: number | null;
@@ -79,5 +81,5 @@ declare function resolveRequestedFillRange(cfg: KibanaCandleConfig, nowMs?: numb
79
81
  */
80
82
  declare function fetchKibanaCandles({ opType, fieldMap, assetA, assetB, config, poolId }: KibanaCandlesParams): Promise<number[][]>;
81
83
  declare function fetchKibanaClosePrices(params: KibanaCandlesParams): Promise<number[]>;
82
- export { buildDirectionalDocumentQuery, resolveRequestedFillRange, fetchKibanaCandles, fetchKibanaClosePrices, sourceFieldsForFieldMap };
84
+ export { buildDirectionalDocumentQuery, resolveRequestedFillRange, fetchKibanaCandles, fetchKibanaClosePrices, sourceFieldsForFieldMap, hitSortKey, hitSequence };
83
85
  //# sourceMappingURL=kibana_candles.d.ts.map
@@ -1,5 +1,6 @@
1
1
  'use strict';
2
2
  import { fillCandleGaps, tradesToCandles } from '../candle_utils.js';
3
+ import { parseChainTimeToMs } from '../interval_utils.js';
3
4
  import { kibanaSearch, DEFAULT_CONFIG as BASE_CONFIG } from './kibana_client.js';
4
5
  import { isTransientNetworkError, sleepMs, getErrorMessage } from '../../modules/utils/errors.js';
5
6
  const DEFAULT_CONFIG = {
@@ -163,7 +164,7 @@ function hitSequence(source, operationIdField) {
163
164
  function hitToTrade(hit, { soldAsset, receivedAsset, soldAmountField, receivedAmountField, operationIdField = 'account_history.operation_id' }) {
164
165
  const source = hit?._source || {};
165
166
  const rawTime = String(getByPath(source, 'block_data.block_time') || '');
166
- const tsMs = Date.parse(rawTime.endsWith('Z') ? rawTime : `${rawTime}Z`);
167
+ const tsMs = parseChainTimeToMs(rawTime);
167
168
  if (!Number.isFinite(tsMs))
168
169
  return null;
169
170
  const soldAmount = amountForAsset(source, soldAmountField, soldAsset.id);
@@ -417,5 +418,5 @@ async function fetchKibanaClosePrices(params) {
417
418
  const candles = await fetchKibanaCandles(params);
418
419
  return candles.map((candle) => candle[4]);
419
420
  }
420
- export { buildDirectionalDocumentQuery, resolveRequestedFillRange, fetchKibanaCandles, fetchKibanaClosePrices, sourceFieldsForFieldMap };
421
+ export { buildDirectionalDocumentQuery, resolveRequestedFillRange, fetchKibanaCandles, fetchKibanaClosePrices, sourceFieldsForFieldMap, hitSortKey, hitSequence };
421
422
  //# sourceMappingURL=kibana_candles.js.map