dexbot 1.6.15 → 1.6.16

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 (102) hide show
  1. package/CHANGELOG.md +26 -0
  2. package/README.md +4 -4
  3. package/claw/docs/DEXBOT2_TUNING_CHEAT_SHEET.md +3 -2
  4. package/claw/modules/chain_queries.ts +3 -3
  5. package/claw/package.json +1 -1
  6. package/claw/runtimes/openclaw-plugin/openclaw.plugin.json +1 -1
  7. package/claw/runtimes/openclaw-plugin/package.json +1 -1
  8. package/dist/analysis/ama_fitting/fetch_lp_candles.js +8 -1
  9. package/dist/analysis/ama_fitting/optimizer_high_resolution.d.ts +50 -1
  10. package/dist/analysis/ama_fitting/optimizer_high_resolution.js +33 -7
  11. package/dist/analysis/bot_fitting/backtest_bot_fitting.d.ts +8 -6
  12. package/dist/analysis/bot_fitting/backtest_bot_fitting.js +8 -10
  13. package/dist/analysis/bot_key_utils.js +9 -7
  14. package/dist/analysis/chart_utils.d.ts +9 -2
  15. package/dist/analysis/chart_utils.js +51 -1
  16. package/dist/analysis/tradingview/tradingview_uplot_chart_generator.d.ts +2 -1
  17. package/dist/analysis/tradingview/tradingview_uplot_chart_generator.js +19 -5
  18. package/dist/analysis/trend_detection/dynamic_weight_chart_generator.js +21 -2
  19. package/dist/analysis/trend_detection/kalman_chart_generator.js +1 -0
  20. package/dist/analysis/trend_detection/regime_chart_generator.js +1 -1
  21. package/dist/analysis/trend_detection/volatility_chart_generator.js +1 -0
  22. package/dist/dexbot.js +89 -138
  23. package/dist/market_adapter/inputs/fetch_book_data.js +36 -12
  24. package/dist/market_adapter/inputs/fetch_lp_data.d.ts +6 -0
  25. package/dist/market_adapter/inputs/fetch_lp_data.js +65 -19
  26. package/dist/market_adapter/inputs/kibana_feed_source.js +45 -12
  27. package/dist/market_adapter/inputs/window_cache.d.ts +14 -1
  28. package/dist/market_adapter/inputs/window_cache.js +53 -17
  29. package/dist/market_adapter/lp_chart_core.js +1 -0
  30. package/dist/market_adapter/utils/chain.js +4 -3
  31. package/dist/market_adapter/utils/pair_orientation.d.ts +60 -0
  32. package/dist/market_adapter/utils/pair_orientation.js +142 -0
  33. package/dist/modules/account_bots.d.ts +37 -3
  34. package/dist/modules/account_bots.js +77 -37
  35. package/dist/modules/account_orders.d.ts +4 -1
  36. package/dist/modules/account_orders.js +4 -1
  37. package/dist/modules/bitshares-native/resolvers.js +3 -3
  38. package/dist/modules/bitshares_client.d.ts +12 -10
  39. package/dist/modules/bitshares_client.js +12 -10
  40. package/dist/modules/bot_settings.js +3 -3
  41. package/dist/modules/chain_keys.d.ts +5 -1
  42. package/dist/modules/chain_keys.js +5 -1
  43. package/dist/modules/chain_orders.d.ts +6 -2
  44. package/dist/modules/chain_orders.js +6 -2
  45. package/dist/modules/constants.d.ts +5 -0
  46. package/dist/modules/constants.js +7 -1
  47. package/dist/modules/dexbot_class.d.ts +3 -1
  48. package/dist/modules/dexbot_class.js +3 -1
  49. package/dist/modules/graceful_shutdown.d.ts +6 -2
  50. package/dist/modules/graceful_shutdown.js +6 -2
  51. package/dist/modules/launcher/bot_supervisor.js +4 -0
  52. package/dist/modules/launcher/launch_modes.js +6 -3
  53. package/dist/modules/launcher/monolithic_runtime.d.ts +39 -1
  54. package/dist/modules/launcher/monolithic_runtime.js +60 -1
  55. package/dist/modules/launcher/runtime_mode.d.ts +79 -0
  56. package/dist/modules/launcher/runtime_mode.js +223 -0
  57. package/dist/modules/market_adapter_whitelist.d.ts +8 -0
  58. package/dist/modules/market_adapter_whitelist.js +8 -0
  59. package/dist/modules/order/accounting.d.ts +15 -1
  60. package/dist/modules/order/accounting.js +15 -1
  61. package/dist/modules/order/async_lock.d.ts +9 -3
  62. package/dist/modules/order/async_lock.js +9 -3
  63. package/dist/modules/order/export.d.ts +0 -5
  64. package/dist/modules/order/export.js +0 -5
  65. package/dist/modules/order/format.d.ts +6 -4
  66. package/dist/modules/order/format.js +6 -4
  67. package/dist/modules/order/grid.d.ts +29 -18
  68. package/dist/modules/order/grid.js +29 -18
  69. package/dist/modules/order/index.d.ts +1 -1
  70. package/dist/modules/order/index.js +1 -1
  71. package/dist/modules/order/logger_state.d.ts +1 -1
  72. package/dist/modules/order/logger_state.js +1 -1
  73. package/dist/modules/order/sync_engine.d.ts +26 -11
  74. package/dist/modules/order/sync_engine.js +26 -11
  75. package/dist/modules/order/utils/math.d.ts +59 -21
  76. package/dist/modules/order/utils/math.js +59 -21
  77. package/dist/modules/order/utils/order.d.ts +64 -20
  78. package/dist/modules/order/utils/order.js +64 -20
  79. package/dist/modules/order/utils/system.d.ts +41 -11
  80. package/dist/modules/order/utils/system.js +41 -11
  81. package/dist/modules/order/utils/validate.d.ts +5 -2
  82. package/dist/modules/order/utils/validate.js +5 -2
  83. package/dist/modules/utils/asset_symbols.d.ts +5 -5
  84. package/dist/modules/utils/asset_symbols.js +5 -5
  85. package/dist/modules/utils/errors.d.ts +2 -1
  86. package/dist/modules/utils/errors.js +2 -1
  87. package/dist/scripts/rich_list.d.ts +32 -0
  88. package/dist/scripts/rich_list.js +16 -8
  89. package/dist/unlock.js +49 -18
  90. package/docs/BITSHARES_ONBOARDING.md +7 -0
  91. package/docs/COW_INVARIANTS.md +1 -1
  92. package/docs/DEXBOT_COMPARISON.md +5 -5
  93. package/docs/EVOLUTION.md +8 -7
  94. package/docs/FUND_MOVEMENT_AND_ACCOUNTING.md +3 -3
  95. package/docs/GRID_RECALCULATION.md +18 -6
  96. package/docs/LIFECYCLE.md +8 -8
  97. package/docs/ORDER_ENGINE_POST_1.0_RETROSPECTIVE.md +4 -4
  98. package/docs/README.md +1 -1
  99. package/docs/WORKFLOW.md +5 -5
  100. package/market_adapter/README.md +10 -3
  101. package/package.json +3 -1
  102. package/tests/README.md +29 -0
@@ -4,7 +4,7 @@ import { getAmaWarmupBars } from '../../market_adapter/core/strategies/ama.js';
4
4
  import { bilinearInterpolate } from '../../market_adapter/core/strategies/regime_interp.js';
5
5
  import { computeDynamicWeightSeries, computeHuberWindowSlopePct, computeAmaSlopeClipThreshold, echoLatchSeries, roundToN } from '../../market_adapter/core/strategies/dynamic_weight_series.js';
6
6
  import { buildKalmanVelocitySeries, computeAbsolutePercentileThreshold, resolveKalmanVelocitySmoothingConfig, smoothKalmanVelocityPoint, } from '../../market_adapter/core/signals/kalman_velocity_smoothing.js';
7
- import { embedFunctionSources, escapeHtml, serializeJsonForScript, toEpochSeconds, UPLOT_SHARED_SCRIPT, uplotInlineTags } from '../chart_utils.js';
7
+ import { embedFunctionSources, escapeHtml, serializeJsonForScript, toEpochSeconds, UPLOT_SHARED_SCRIPT, VIEWPORT_CLIP_SCRIPT, uplotInlineTags } from '../chart_utils.js';
8
8
  import { sharedChartCSS } from '../chart_css.js';
9
9
  import { Y_AXIS_SIZE, makeCursorConfig, bindHoverStateFn, wireChartEvents, zoomResetScript, sizeChartsFn, formatTimeLabelFn, refreshChartsPreservingZoomFn } from '../chart_ui.js';
10
10
  // Browser-embedded shared functions — the interactive chart runs the exact same
@@ -692,6 +692,8 @@ function generateHTML(data, title = 'Dynamic Weight Research') {
692
692
 
693
693
  ${UPLOT_SHARED_SCRIPT}
694
694
 
695
+ ${VIEWPORT_CLIP_SCRIPT}
696
+
695
697
  ${refreshChartsPreservingZoomFn({
696
698
  anchor: 'outputChart?.scales?.x',
697
699
  reload: [
@@ -784,6 +786,11 @@ function generateHTML(data, title = 'Dynamic Weight Research') {
784
786
  ctx.save();
785
787
  ctx.beginPath(); ctx.rect(bbox.left, bbox.top, bbox.width, bbox.height); ctx.clip();
786
788
  ctx.globalCompositeOperation = 'destination-over';
789
+ // Cull segments that cannot intersect the viewport so we skip
790
+ // their (expensive, destination-over) fillRect and valToPos work.
791
+ const xScale = u.scales.x || {};
792
+ const smin = xScale.min, smax = xScale.max;
793
+ const canCull = Number.isFinite(smin) && Number.isFinite(smax);
787
794
  let i = 0;
788
795
  while (i < data.signals.length) {
789
796
  const s = currentLatchedSignals[i] || data.signals[i];
@@ -796,6 +803,16 @@ function generateHTML(data, title = 'Dynamic Weight Research') {
796
803
  if (sj !== s) break;
797
804
  j++;
798
805
  }
806
+ if (canCull) {
807
+ // A run that reaches the last real bar is drawn all the way
808
+ // to bbox.right, so it is visible for any viewport past its
809
+ // start (never cull it on the right). Only runs that end at a
810
+ // real bar can be entirely left of the viewport.
811
+ const reachesRightEdge = j >= data.realBarCount;
812
+ const segEnd = reachesRightEdge ? Infinity : data.dates[j];
813
+ if (segEnd < smin) { i = j; continue; }
814
+ if (data.dates[i] > smax) break;
815
+ }
799
816
  const x0 = u.valToPos(data.dates[i], 'x', true);
800
817
  const x1 = j < data.realBarCount ? u.valToPos(data.dates[j], 'x', true) : bbox.left + bbox.width;
801
818
  if (isBull) { ctx.fillStyle = 'rgba(46,160,67,0.06)'; ctx.fillRect(x0, bbox.top, x1 - x0, bbox.height); }
@@ -822,7 +839,8 @@ function generateHTML(data, title = 'Dynamic Weight Research') {
822
839
  const zeroY = u.valToPos(0, scaleKey, true);
823
840
  const path = new Path2D();
824
841
  let inSeg = false, lastX = 0;
825
- for (let i = 0; i < values.length; i++) {
842
+ const [lo, hi] = visibleBarRange(u, values.length);
843
+ for (let i = lo; i <= hi; i++) {
826
844
  const v = values[i];
827
845
  if (v === null) { if (inSeg) { path.lineTo(lastX, zeroY); inSeg = false; } continue; }
828
846
  const x = u.valToPos(data.dates[i], 'x', true);
@@ -954,6 +972,7 @@ function generateHTML(data, title = 'Dynamic Weight Research') {
954
972
  axes: [
955
973
  makeTimeAxis(false),
956
974
  { scale: 'y', stroke: '#ffffff', grid: { stroke: '#1c2128' }, ticks: { stroke: '#30363d', width: 1 }, size: Y_AXIS_SIZE, font: '11px Segoe UI, sans-serif',
975
+ splits: logAxisSplits,
957
976
  values: (u, v) => v.map(x => x != null ? x.toFixed(4) : ''), }
958
977
  ],
959
978
  cursor: cursorCfg,
@@ -340,6 +340,7 @@ function generateHTML(data, title = 'Kalman Trajectory Analysis') {
340
340
  ticks: { stroke: '#30363d', width: 1 },
341
341
  size: ${Y_AXIS_SIZE},
342
342
  font: '11px Segoe UI, sans-serif',
343
+ splits: logAxisSplits,
343
344
  values: (u, v) => v.map(x => x != null ? x.toFixed(4) : ''),
344
345
  }
345
346
  ],
@@ -256,7 +256,7 @@ function generateRegimeHTML(data, title = 'Regime Analysis') {
256
256
  ],
257
257
  axes: [
258
258
  X_AXIS_CFG,
259
- { ...yAxis('y'), values: (u, v) => v.map(x => x != null ? fmtPrice(x) : '') },
259
+ { ...yAxis('y'), splits: logAxisSplits, values: (u, v) => v.map(x => x != null ? fmtPrice(x) : '') },
260
260
  ],
261
261
  cursor: cursorCfg,
262
262
  hooks: { draw: [(u) => { updateLegend(u.cursor.idx); }] },
@@ -519,6 +519,7 @@ function generateHTML(data, title = 'ATR Volatility Research') {
519
519
  axes: [
520
520
  { show: false, stroke: '#ffffff', grid: { stroke: '#1c2128' }, ticks: { stroke: '#30363d', width: 1 }, size: 28, font: '11px Segoe UI, sans-serif' },
521
521
  { scale: 'y', stroke: '#ffffff', grid: { stroke: '#1c2128' }, ticks: { stroke: '#30363d', width: 1 }, size: Y_AXIS_SIZE, font: '11px Segoe UI, sans-serif',
522
+ splits: logAxisSplits,
522
523
  values: (u, v) => v.map(x => x != null ? fmtNum(x, 6) : '') },
523
524
  ],
524
525
  cursor: cursorCfg,
package/dist/dexbot.js CHANGED
@@ -122,6 +122,7 @@ const { setupGracefulShutdown, registerCleanup, unregisterCleanup } = require('.
122
122
  const { collectValidationIssues, loadSettingsFile, normalizeBotEntries, resolveRawBotEntries, saveSettingsFile, } = require('./modules/bot_settings');
123
123
  const { buildRuntimeScriptArgs } = require('./modules/launcher/runtime_entry');
124
124
  const { parseWorkerArgs, LAUNCHER_WORKER_COMMAND } = require('./modules/launcher/launch_modes');
125
+ const { detectRuntimeMode, runtimeControlHelp, runtimeModeLabel, checkStatusTarget, resolveStatusRoute } = require('./modules/launcher/runtime_mode');
125
126
  const { PATHS, getHomeProfilesDir, getRecalculateTriggerFile, printRelocationNotices } = require('./modules/paths');
126
127
  const credentialPolicy = require('./modules/credential_policy');
127
128
  const { Config } = require('./modules/config');
@@ -186,17 +187,13 @@ const cliArgs = process.argv.slice(2);
186
187
  */
187
188
  function printCLIUsage() {
188
189
  // Grouped so the full command set stays scannable; descriptions are one line each
189
- // and the description column is derived, so alignment never drifts.
190
+ // and the description column is derived, so alignment never drifts. The
191
+ // Runtime group is phrased for the runtime that is actually up — the
192
+ // detection and the mode→instructions mapping are centralized in
193
+ // modules/launcher/runtime_mode.ts so `help` and `status` agree.
194
+ const runtime = detectRuntimeMode();
190
195
  const groups = [
191
- ['Runtime', [
192
- ['start [bot]', 'Start the bot runtime (flags below).'],
193
- ['stop', 'Stop the runtime.'],
194
- ['reload', 'Reload the runtime without re-unlocking keys.'],
195
- ['restart', 'Restart the runtime and re-unlock keys.'],
196
- ['delete', 'Stop and delete all runtime processes.'],
197
- ['status', 'Show runtime status.'],
198
- ['pm2 [<sub>]', 'Manage PM2 bots (see: dexbot pm2 help).'],
199
- ]],
196
+ ['Runtime', runtimeControlHelp(runtime.mode).map((entry) => [entry.command, entry.description])],
200
197
  ['Trading', [
201
198
  ['test <bot>', 'Run a bot live once.'],
202
199
  ['drystart <bot>', 'Run a bot without broadcasting.'],
@@ -228,6 +225,12 @@ function printCLIUsage() {
228
225
  ];
229
226
  const width = Math.max(...groups.flatMap(([, entries]) => entries.map(([cmd]) => cmd.length))) + 2;
230
227
  console.log('Usage: dexbot [command] [bot]');
228
+ console.log(`Active runtime: ${runtimeModeLabel(runtime)}`);
229
+ if (runtime.mode === 'none') {
230
+ console.log(' Standard start: dexbot start (monolithic)');
231
+ console.log(' Alternatives: dexbot start --isolated | dexbot pm2');
232
+ }
233
+ console.log();
231
234
  for (const [title, entries] of groups) {
232
235
  console.log(`${title}:`);
233
236
  for (const [cmd, desc] of entries) {
@@ -1165,60 +1168,18 @@ async function handleCLICommands() {
1165
1168
  process.exit(code);
1166
1169
  return true;
1167
1170
  };
1168
- const { spawnSync, execSync } = require('child_process');
1169
- const MONOLITHIC_PID_FILE = PATHS.PROFILES.MONOLITHIC_PID;
1170
- const MONOLITHIC_CRED_PID_FILE = PATHS.PROFILES.MONOLITHIC_CRED_PID;
1171
- const SUPERVISOR_SOCK = PATHS.PROFILES.SUPERVISOR_SOCK;
1172
- let unlockRunning = false;
1173
- if (storage.exists(MONOLITHIC_PID_FILE)) {
1174
- try {
1175
- const pid = Number(storage.readFile(MONOLITHIC_PID_FILE).trim());
1176
- if (Number.isInteger(pid) && pid > 0) {
1177
- try {
1178
- process.kill(pid, 0);
1179
- unlockRunning = true;
1180
- }
1181
- catch (err) {
1182
- if (getErrorCode(err) === 'EACCES') {
1183
- console.warn('[dexbot]', `process.kill(${pid}, 0) EACCES — process exists but permission denied`);
1184
- unlockRunning = true;
1185
- }
1186
- else if (getErrorCode(err) !== 'ESRCH') {
1187
- console.warn('[dexbot]', `process.kill(${pid}, 0) unexpected error: ${getErrorMessage(err)}`);
1188
- }
1189
- }
1190
- }
1191
- }
1192
- catch (_) { }
1193
- }
1194
- if (!unlockRunning && storage.exists(SUPERVISOR_SOCK)) {
1195
- unlockRunning = true;
1196
- }
1197
- // A credential daemon can outlive a `dexbot stop` (bots + market
1198
- // adapter stop; the daemon stays up for fast re-unlock). Report it
1199
- // too, so `stat` does not show "No DEXBot2 processes running." when
1200
- // only the daemon remains.
1201
- if (!unlockRunning && storage.exists(MONOLITHIC_CRED_PID_FILE)) {
1202
- try {
1203
- const pid = Number(storage.readFile(MONOLITHIC_CRED_PID_FILE).trim());
1204
- if (Number.isInteger(pid) && pid > 0) {
1205
- try {
1206
- process.kill(pid, 0);
1207
- unlockRunning = true;
1208
- }
1209
- catch (err) {
1210
- if (getErrorCode(err) === 'EACCES')
1211
- unlockRunning = true;
1212
- }
1213
- }
1214
- }
1215
- catch (_) { }
1216
- }
1217
- if (unlockRunning) {
1171
+ const { spawnSync } = require('child_process');
1172
+ // Centralized detection (modules/launcher/runtime_mode.ts), shared
1173
+ // with the mode-aware help output so the two cannot disagree.
1174
+ const runtimeInfo = detectRuntimeMode();
1175
+ // PM2 bots win over a stray credential daemon (resolveStatusRoute)
1176
+ // so the report matches the help banner; otherwise a live unlock
1177
+ // runtime is shown by delegating to `unlock status`.
1178
+ if (resolveStatusRoute(runtimeInfo) === 'unlock') {
1218
1179
  const unlockArgs = buildRuntimeScriptArgs({
1219
1180
  codeRoot: __dirname,
1220
1181
  scriptSegments: ['unlock'],
1221
- scriptArgs: ['status'],
1182
+ scriptArgs: ['status', ...(target ? [target] : [])],
1222
1183
  });
1223
1184
  const result = spawnSync(Config.EXEC_PATH, unlockArgs, {
1224
1185
  cwd: PATHS.PROJECT_ROOT,
@@ -1226,85 +1187,75 @@ async function handleCLICommands() {
1226
1187
  });
1227
1188
  return finish(result.status ?? 0);
1228
1189
  }
1229
- try {
1230
- const output = execSync('pm2 jlist 2>/dev/null', { encoding: 'utf8', timeout: 5000 }).toString().trim();
1231
- const jsonStart = output.indexOf('[');
1232
- if (jsonStart === -1) {
1233
- console.log('No DEXBot2 processes running.');
1234
- return finish(0);
1235
- }
1236
- const allProcs = JSON.parse(output.slice(jsonStart));
1237
- if (!Array.isArray(allProcs) || allProcs.length === 0) {
1238
- console.log('No DEXBot2 processes running.');
1239
- return finish(0);
1240
- }
1241
- const serviceNames = new Set(['dexbot-cred', 'dexbot-adapter', 'dexbot-update']);
1242
- const botNames = new Set();
1243
- try {
1244
- const { config } = loadSettingsFile(PROFILES_BOTS_FILE);
1245
- const entries = resolveRawBotEntries(config);
1246
- for (const b of entries) {
1247
- if (b.name)
1248
- botNames.add(b.name);
1249
- }
1250
- }
1251
- catch (_) { }
1252
- const dexbotProcs = allProcs.filter((p) => {
1253
- const name = String(p?.name || '');
1254
- return serviceNames.has(name) || botNames.has(name);
1255
- });
1256
- if (dexbotProcs.length === 0) {
1257
- console.log('No DEXBot2 processes running.');
1258
- return finish(0);
1259
- }
1260
- console.log('='.repeat(50));
1261
- console.log('DEXBot2 PM2 Processes');
1262
- console.log('='.repeat(50));
1263
- console.log('');
1264
- const fmtUptime = (p) => {
1265
- if (!p?.pm2_env?.pm_uptime)
1266
- return '-';
1267
- const ms = Date.now() - new Date(p.pm2_env.pm_uptime).getTime();
1268
- const s = Math.floor(Math.abs(ms) / 1000);
1269
- if (s < 60)
1270
- return `${s}s`;
1271
- const m = Math.floor(s / 60);
1272
- if (m < 60)
1273
- return `${m}m ${s % 60}s`;
1274
- const h = Math.floor(m / 60);
1275
- if (h < 24)
1276
- return `${h}h ${m % 60}m`;
1277
- const d = Math.floor(h / 24);
1278
- return `${d}d ${h % 24}h`;
1279
- };
1280
- const fmtMem = (p) => {
1281
- const bytes = p?.monit?.memory;
1282
- if (!bytes || bytes <= 0)
1283
- return '-';
1284
- if (bytes < 1024)
1285
- return `${bytes}B`;
1286
- if (bytes < 1024 * 1024)
1287
- return `${(bytes / 1024).toFixed(1)}KB`;
1288
- return `${(bytes / (1024 * 1024)).toFixed(1)}MB`;
1289
- };
1290
- const rows = dexbotProcs.map((p) => ({
1291
- pid: String(p?.pid || '-'),
1292
- name: String(p?.name || '-'),
1293
- status: String(p?.pm2_env?.status || '-'),
1294
- uptime: fmtUptime(p),
1295
- mem: fmtMem(p),
1296
- }));
1297
- const nameWidth = Math.max(...rows.map(r => r.name.length), 4);
1298
- const statusWidth = Math.max(...rows.map(r => r.status.length), 6);
1299
- const header = `${'PID'.padEnd(8)} ${'NAME'.padEnd(nameWidth)} ${'STATUS'.padEnd(statusWidth)} ${'UPTIME'.padEnd(12)} ${'MEMORY'}`;
1300
- console.log(header);
1301
- console.log('-'.repeat(header.length));
1302
- for (const r of rows) {
1303
- console.log(`${r.pid.padEnd(8)} ${r.name.padEnd(nameWidth)} ${r.status.padEnd(statusWidth)} ${r.uptime.padEnd(12)} ${r.mem}`);
1304
- }
1190
+ // status is whole-runtime on every surface. With no unlock bot
1191
+ // runtime up, validate and ignore a bot name here so the behavior
1192
+ // matches the `unlock status <bot>` path.
1193
+ const statusCheck = checkStatusTarget(target);
1194
+ if (statusCheck.error) {
1195
+ console.error(startupError(statusCheck.error));
1196
+ return finish(1);
1305
1197
  }
1306
- catch {
1198
+ if (statusCheck.notice) {
1199
+ console.warn(statusCheck.notice);
1200
+ }
1201
+ // No unlock runtime: render the PM2 table for this install's own
1202
+ // processes (already filtered by the shared detector).
1203
+ const dexbotProcs = runtimeInfo.pm2Processes;
1204
+ if (dexbotProcs.length === 0) {
1307
1205
  console.log('No DEXBot2 processes running.');
1206
+ return finish(0);
1207
+ }
1208
+ console.log('='.repeat(50));
1209
+ console.log('DEXBot2 PM2 Processes');
1210
+ console.log('='.repeat(50));
1211
+ console.log('');
1212
+ const fmtUptime = (p) => {
1213
+ if (!p?.pm2_env?.pm_uptime)
1214
+ return '-';
1215
+ const ms = Date.now() - new Date(p.pm2_env.pm_uptime).getTime();
1216
+ const s = Math.floor(Math.abs(ms) / 1000);
1217
+ if (s < 60)
1218
+ return `${s}s`;
1219
+ const m = Math.floor(s / 60);
1220
+ if (m < 60)
1221
+ return `${m}m ${s % 60}s`;
1222
+ const h = Math.floor(m / 60);
1223
+ if (h < 24)
1224
+ return `${h}h ${m % 60}m`;
1225
+ const d = Math.floor(h / 24);
1226
+ return `${d}d ${h % 24}h`;
1227
+ };
1228
+ const fmtMem = (p) => {
1229
+ const bytes = p?.monit?.memory;
1230
+ if (!bytes || bytes <= 0)
1231
+ return '-';
1232
+ if (bytes < 1024)
1233
+ return `${bytes}B`;
1234
+ if (bytes < 1024 * 1024)
1235
+ return `${(bytes / 1024).toFixed(1)}KB`;
1236
+ return `${(bytes / (1024 * 1024)).toFixed(1)}MB`;
1237
+ };
1238
+ const rows = dexbotProcs.map((p) => ({
1239
+ pid: String(p?.pid || '-'),
1240
+ name: String(p?.name || '-'),
1241
+ status: String(p?.pm2_env?.status || '-'),
1242
+ uptime: fmtUptime(p),
1243
+ mem: fmtMem(p),
1244
+ }));
1245
+ const nameWidth = Math.max(...rows.map(r => r.name.length), 4);
1246
+ const statusWidth = Math.max(...rows.map(r => r.status.length), 6);
1247
+ const header = `${'PID'.padEnd(8)} ${'NAME'.padEnd(nameWidth)} ${'STATUS'.padEnd(statusWidth)} ${'UPTIME'.padEnd(12)} ${'MEMORY'}`;
1248
+ console.log(header);
1249
+ console.log('-'.repeat(header.length));
1250
+ for (const r of rows) {
1251
+ console.log(`${r.pid.padEnd(8)} ${r.name.padEnd(nameWidth)} ${r.status.padEnd(statusWidth)} ${r.uptime.padEnd(12)} ${r.mem}`);
1252
+ }
1253
+ // Mixed state: surface a stray unlock-mode credential daemon too —
1254
+ // it holds unlocked keys in memory and would otherwise be invisible
1255
+ // here because PM2 wins the status route.
1256
+ if (runtimeInfo.credentialDaemonPid > 0) {
1257
+ console.log();
1258
+ console.log(`Credential daemon also running (unlock mode), PID ${runtimeInfo.credentialDaemonPid}.`);
1308
1259
  }
1309
1260
  return finish(0);
1310
1261
  }
@@ -23,11 +23,15 @@
23
23
  import { getMarketCandles } from '../core/kibana_market_candles.js';
24
24
  import { path } from '../../modules/path_api.js';
25
25
  import { PATHS } from '../../modules/paths.js';
26
- import { toIntervalLabel, slugPart } from '../interval_utils.js';
26
+ import { toIntervalLabel } from '../interval_utils.js';
27
27
  import { buildFetchWindowsFromRange, runCachedWindows } from './window_cache.js';
28
+ import { canonicalPair, pairFolderSlug, sameAssets, swappedAssets, inverseSiblingOutPath, invertCandleSeries } from '../utils/pair_orientation.js';
28
29
  function bookCacheKey(assetA, assetB) {
29
- // Orientation matters: candles are B-per-A, so A/B and B/A are different series.
30
- return `${slugPart(assetA?.symbol || assetA?.id)}_${slugPart(assetB?.symbol || assetB?.id)}`;
30
+ // Canonical orientation: A/B and B/A share one cache family. Candles are
31
+ // B-per-A, so the stored series is always the canonical one and the
32
+ // fetcher inverts it back for an inverse request.
33
+ const pair = canonicalPair(assetA || {}, assetB || {});
34
+ return pairFolderSlug(pair.assetA, pair.assetB);
31
35
  }
32
36
  function bookOutputPath(assetA, assetB, intervalSeconds) {
33
37
  const label = toIntervalLabel(intervalSeconds);
@@ -43,11 +47,17 @@ function isBookChunkMatch(metaInput, requestKeyInput) {
43
47
  return false;
44
48
  if (meta.intervalSeconds !== requestKey.intervalSeconds)
45
49
  return false;
46
- if (meta.assetA?.id !== requestKey.assetA.id || meta.assetB?.id !== requestKey.assetB.id)
50
+ return sameAssets(meta, requestKey);
51
+ }
52
+ /** Same identity, opposite orientation (legacy pre-canonicalization shard). */
53
+ function isBookChunkMatchInverse(metaInput, requestKeyInput) {
54
+ const meta = metaInput;
55
+ const requestKey = requestKeyInput;
56
+ if (meta.source !== 'book' || requestKey.source !== 'book')
47
57
  return false;
48
- if (meta.assetA?.precision !== requestKey.assetA.precision || meta.assetB?.precision !== requestKey.assetB.precision)
58
+ if (meta.intervalSeconds !== requestKey.intervalSeconds)
49
59
  return false;
50
- return true;
60
+ return swappedAssets(meta, requestKey);
51
61
  }
52
62
  /**
53
63
  * OHLC order-book fill candles for an asset pair with chunk-level disk reuse.
@@ -64,13 +74,19 @@ async function fetchMarketCandlesSequentially(assetA, assetB, opts = {}) {
64
74
  if (!timeRange?.gte || !timeRange?.lte) {
65
75
  throw new Error('fetchMarketCandlesSequentially requires opts.timeRange { gte, lte }');
66
76
  }
67
- const pair = bookCacheKey(assetA, assetB);
68
- const outPath = opts.outPath || bookOutputPath(assetA, assetB, intervalSeconds);
77
+ // Canonical storage: fetch/query the lower-id leg as A, invert the result
78
+ // back if the caller asked for the other side. One cache family per pair.
79
+ const canon = canonicalPair(assetA, assetB);
80
+ const storeA = canon.assetA;
81
+ const storeB = canon.assetB;
82
+ const flipped = canon.flipped;
83
+ const pair = bookCacheKey(storeA, storeB);
84
+ const outPath = opts.outPath || bookOutputPath(storeA, storeB, intervalSeconds);
69
85
  const requestKey = {
70
86
  source: 'book',
71
87
  pair,
72
- assetA: { id: assetA.id, precision: assetA.precision, symbol: assetA.symbol },
73
- assetB: { id: assetB.id, precision: assetB.precision, symbol: assetB.symbol },
88
+ assetA: { id: storeA.id, precision: storeA.precision, symbol: storeA.symbol },
89
+ assetB: { id: storeB.id, precision: storeB.precision, symbol: storeB.symbol },
74
90
  intervalSeconds,
75
91
  };
76
92
  const plainWindows = buildFetchWindowsFromRange(timeRange, chunkMonths);
@@ -106,7 +122,7 @@ async function fetchMarketCandlesSequentially(assetA, assetB, opts = {}) {
106
122
  }
107
123
  catch (_) { /* progress must never fail the fetch */ }
108
124
  };
109
- const candles = await getMarketCandles(assetA, assetB, {
125
+ const candles = await getMarketCandles(storeA, storeB, {
110
126
  ...passthrough,
111
127
  ...(signal ? { signal } : {}),
112
128
  onPage,
@@ -115,11 +131,18 @@ async function fetchMarketCandlesSequentially(assetA, assetB, opts = {}) {
115
131
  });
116
132
  return sawPartial ? { candles, complete: false } : candles;
117
133
  };
118
- return runCachedWindows({
134
+ const merged = await runCachedWindows({
119
135
  windows,
120
136
  outPath,
121
137
  requestKey,
122
138
  isMatch: isBookChunkMatch,
139
+ inverse: (() => {
140
+ const invFolder = pairFolderSlug(storeB, storeA);
141
+ const legacy = inverseSiblingOutPath(outPath, storeA, storeB, `book_${invFolder}_${toIntervalLabel(intervalSeconds)}.json`);
142
+ return legacy
143
+ ? { outPath: legacy, isMatch: isBookChunkMatchInverse, toRequest: (c) => invertCandleSeries(c, { volume: 'scale' }) }
144
+ : undefined;
145
+ })(),
123
146
  metaForWindow: (window) => ({
124
147
  source: 'book',
125
148
  esSource: 'https://kibana.bitshares.dev (bitshares-*, op_type 4, fill_order)',
@@ -134,6 +157,7 @@ async function fetchMarketCandlesSequentially(assetA, assetB, opts = {}) {
134
157
  bucketMs: intervalSeconds * 1000,
135
158
  allowSubFetch: true,
136
159
  });
160
+ return flipped ? invertCandleSeries(merged, { volume: 'scale' }) : merged;
137
161
  }
138
162
  export { bookCacheKey, bookOutputPath, isBookChunkMatch, fetchMarketCandlesSequentially, };
139
163
  //# sourceMappingURL=fetch_book_data.js.map
@@ -38,6 +38,12 @@ declare function applyPrecisionOverrides(assetA: AssetRef, assetB: AssetRef, pre
38
38
  assetA: AssetRef;
39
39
  assetB: AssetRef;
40
40
  };
41
+ /**
42
+ * Locate a cached fetch context for a bot. Standard calls omit `dir` and both
43
+ * orientations are probed, so a bot whose pair is the inverse of the canonical
44
+ * folder still skips the blockchain connect. An explicit `dir` (tests, custom
45
+ * layouts) is scanned alone.
46
+ */
41
47
  declare function loadCachedFetchContext(bot: BotConfig, intervalSeconds: number, dir?: string): {
42
48
  poolId: string;
43
49
  assetA: AssetRef;