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
@@ -5,8 +5,8 @@
5
5
  * Both entries (scripts/tv.ts, scripts/dw.ts) are thin wrappers around run(cmd).
6
6
  *
7
7
  * Usage:
8
- * dexbot tv <bot|pool-id|AssetA/AssetB> [--month N] [--chart <path>] [--feed|--pool|--book]
9
- * dexbot dw <bot|pool-id|AssetA/AssetB> [--month N] [--chart <path>] [--feed|--pool|--book]
8
+ * dexbot tv <bot|pool|AssetA/AssetB> [--month N] [--chart <path>] [--feed|--pool|--book]
9
+ * dexbot dw <bot|pool|AssetA/AssetB> [--month N] [--chart <path>] [--feed|--pool|--book]
10
10
  *
11
11
  * The pipeline owns everything up to the rendered HTML:
12
12
  * 1. parse target/flags (parseArgs),
@@ -25,21 +25,19 @@
25
25
  import fs from 'node:fs';
26
26
  import os from 'node:os';
27
27
  import path from 'node:path';
28
- import { spawnSync } from 'node:child_process';
29
- import { fileURLToPath } from 'node:url';
30
- const __filename = fileURLToPath(import.meta.url);
31
- const __dirname = path.dirname(__filename);
32
- import { loadBotMeta, loadBotSettings, computeBotKey } from '../analysis/bot_key_utils.js';
33
28
  import { PATHS } from '../modules/paths.js';
34
- import { normalizePoolId, resolveAsset, findPoolByAssets } from '../market_adapter/utils/chain.js';
29
+ import { poolAssetIds, resolvePoolRef } from '../modules/liquidity_pool_ref.js';
30
+ import { resolveAsset, findPoolByAssets } from '../market_adapter/utils/chain.js';
35
31
  import { normalizeAssetSymbol, splitPairTarget } from '../modules/utils/asset_symbols.js';
36
32
  import { fetchCandlesSequentially, outputPath } from '../market_adapter/inputs/fetch_lp_data.js';
37
33
  import { fetchMarketCandlesSequentially } from '../market_adapter/inputs/fetch_book_data.js';
38
34
  import { fetchFeedCandlesSequentially } from '../market_adapter/inputs/kibana_feed_source.js';
39
35
  import { muteChainLogs } from '../modules/utils/chain_logs.js';
40
- import { isSameBotName, sanitizeKey } from '../modules/utils/sanitize_key.js';
36
+ import { sanitizeKey } from '../modules/utils/sanitize_key.js';
41
37
  import { slugPart, parseChainTimeToMs } from '../market_adapter/interval_utils.js';
42
38
  import { monthsToHours } from '../modules/utils/time_range.js';
39
+ import { findBotByTarget, isPoolIdTarget, isPoolTarget, knownTargetsHint } from './chart_targets.js';
40
+ import { runAnalysisScript } from './analysis_runner.js';
43
41
  const INTERVAL_SECONDS = 3600;
44
42
  const DEFAULT_MONTHS = 3;
45
43
  // Explicit --feed warns when the settlement feed is older than this
@@ -67,12 +65,12 @@ const RENDERERS = {
67
65
  },
68
66
  };
69
67
  function printUsage(cmd = 'tv') {
70
- console.log(`Usage: dexbot ${cmd} <bot|pool-id|AssetA/AssetB> [--month N] [--chart <path>] [--feed|--pool|--book]`);
68
+ console.log(`Usage: dexbot ${cmd} <bot|pool|AssetA/AssetB> [--month N] [--chart <path>] [--feed|--pool|--book]`);
71
69
  for (const line of RENDERERS[cmd].usageBlurb)
72
70
  console.log(line);
73
71
  console.log('');
74
72
  console.log(' <bot> Bot name or key from profiles/bots.json');
75
- console.log(' <pool-id> Liquidity pool id, e.g. 133 or 1.19.133 (always pool candles)');
73
+ console.log(' <pool> Pool id (133 or 1.19.133) or its pool token (LP share-asset symbol); always pool candles');
76
74
  console.log(' AssetA/AssetB Pair symbols, e.g. TOKENA/TOKENB (pool-first, orderbook fallback)');
77
75
  console.log(' Case-insensitive: assetA/assetB is uppercased before it reaches the chain');
78
76
  console.log(' MPA pairs (e.g. BTS/HONEST.USD) can chart price-feed history via --feed');
@@ -230,86 +228,68 @@ function parseArgs(argv, cmd = 'tv') {
230
228
  source = picked;
231
229
  }
232
230
  else if (arg.startsWith('--')) {
233
- throw new Error(`Unknown flag "${arg}". Usage: dexbot ${cmd} <bot|pool-id|AssetA/AssetB> [--month N]`);
231
+ throw new Error(`Unknown flag "${arg}". Usage: dexbot ${cmd} <bot|pool|AssetA/AssetB> [--month N]`);
234
232
  }
235
233
  else if (!target) {
236
234
  target = arg;
237
235
  }
238
236
  else {
239
- throw new Error(`Unexpected argument "${arg}". Only one target is supported. Usage: dexbot ${cmd} <bot|pool-id|AssetA/AssetB> [--month N]`);
237
+ throw new Error(`Unexpected argument "${arg}". Only one target is supported. Usage: dexbot ${cmd} <bot|pool|AssetA/AssetB> [--month N]`);
240
238
  }
241
239
  }
242
240
  return { target, months, chart, source, help };
243
241
  }
244
- function isPoolIdTarget(target) {
245
- return /^(1\.19\.\d+|\d+)$/.test(target.trim());
246
- }
247
- function findBotByTarget(target) {
248
- const settings = loadBotSettings();
249
- const entries = Array.isArray(settings?.bots) ? settings.bots : [];
250
- for (let i = 0; i < entries.length; i++) {
251
- const entry = entries[i];
252
- if (!entry)
253
- continue;
254
- if (isSameBotName(entry.name, target))
255
- return { botKey: computeBotKey(entry, i) ?? '', meta: entry };
256
- }
257
- const meta = loadBotMeta(target);
258
- if (meta) {
259
- const idx = entries.indexOf(meta);
260
- return { botKey: computeBotKey(meta, idx >= 0 ? idx : 0) ?? '', meta };
261
- }
262
- return null;
263
- }
264
242
  function monthsLabel(months) {
265
243
  return Number.isInteger(months) ? `${months}m` : `${String(months).replace('.', 'p')}m`;
266
244
  }
267
- async function resolvePoolAssets(poolId, bitsharesClient) {
268
- const fullId = normalizePoolId(poolId);
269
- // Chain pool object via get_objects([poolId]) → asset_a / asset_b.
245
+ async function resolvePoolAssets(poolRef, bitsharesClient) {
270
246
  const db = bitsharesClient.BitShares?.db;
271
- if (db && typeof db.get_objects === 'function') {
272
- try {
273
- const objs = await db.get_objects([fullId]);
274
- const pool = (Array.isArray(objs) ? objs[0] : null);
275
- const idA = pool?.asset_a || pool?.asset_ids?.[0];
276
- const idB = pool?.asset_b || pool?.asset_ids?.[1];
277
- if (idA && idB) {
278
- const assets = typeof db.get_assets === 'function' ? await db.get_assets([String(idA), String(idB)]) : null;
279
- // Tolerate both [..] and [[..]] result shapes.
280
- const list = (Array.isArray(assets) ? assets.flat(Infinity) : []);
281
- const metaA = list.find((a) => String(a?.id) === String(idA));
282
- const metaB = list.find((a) => String(a?.id) === String(idB));
283
- if (metaA && metaB) {
284
- return {
285
- assetA: { id: String(metaA.id), precision: Number(metaA.precision), symbol: String(metaA.symbol || idA) },
286
- assetB: { id: String(metaB.id), precision: Number(metaB.precision), symbol: String(metaB.symbol || idB) },
287
- };
288
- }
289
- }
290
- }
291
- catch (_) {
292
- // Fall through to Kibana discovery below.
247
+ if (!db)
248
+ throw new Error('BitShares client has no database API');
249
+ // `poolRef` is a pool id (133 / 1.19.133) or a pool token (LP share-asset
250
+ // symbol); modules/liquidity_pool_ref owns both spellings so `tv`, `dw` and
251
+ // `liq` cannot drift on which pools they accept.
252
+ const pool = await resolvePoolRef((method, args) => {
253
+ const call = db[method];
254
+ if (typeof call !== 'function')
255
+ throw new Error(`Chain API '${method}' is not available on this node`);
256
+ return call(...(args ?? []));
257
+ }, poolRef);
258
+ const poolId = String(pool.id);
259
+ const [idA, idB] = poolAssetIds(pool);
260
+ if (idA && idB && typeof db.get_assets === 'function') {
261
+ const assets = await db.get_assets([String(idA), String(idB)]).catch(() => null);
262
+ // Tolerate both [..] and [[..]] result shapes.
263
+ const list = (Array.isArray(assets) ? assets.flat(Infinity) : []);
264
+ const metaA = list.find((a) => String(a?.id) === String(idA));
265
+ const metaB = list.find((a) => String(a?.id) === String(idB));
266
+ if (metaA && metaB) {
267
+ return {
268
+ assetA: { id: String(metaA.id), precision: Number(metaA.precision), symbol: String(metaA.symbol || idA) },
269
+ assetB: { id: String(metaB.id), precision: Number(metaB.precision), symbol: String(metaB.symbol || idB) },
270
+ poolId,
271
+ };
293
272
  }
294
273
  }
295
274
  // Fallback: Kibana discovery (what went into the pool) + chain precision lookup.
296
275
  const { discoverPoolAssets } = await import('../market_adapter/inputs/kibana_source.js');
297
- const ids = await discoverPoolAssets(fullId, {});
276
+ const ids = await discoverPoolAssets(poolId, {});
298
277
  if (!Array.isArray(ids) || ids.length !== 2) {
299
- throw new Error(`Pool ${fullId}: expected exactly 2 assets, discovered [${(ids || []).join(', ')}]. Pass AssetA/AssetB instead.`);
278
+ throw new Error(`Pool ${poolId}: expected exactly 2 assets, discovered [${(ids || []).join(', ')}]. Pass AssetA/AssetB instead.`);
300
279
  }
301
- const [idA, idB] = ids.map(String);
302
- if (!db || typeof db.get_assets !== 'function')
303
- throw new Error(`Pool ${fullId}: chain asset lookup unavailable`);
304
- const assets = await db.get_assets([idA, idB]);
305
- const metaA = (assets || []).find((a) => String(a?.id) === idA);
306
- const metaB = (assets || []).find((a) => String(a?.id) === idB);
280
+ const [fallbackA, fallbackB] = ids.map(String);
281
+ if (typeof db.get_assets !== 'function')
282
+ throw new Error(`Pool ${poolId}: chain asset lookup unavailable`);
283
+ const assets = await db.get_assets([fallbackA, fallbackB]);
284
+ const metaA = (assets || []).find((a) => String(a?.id) === fallbackA);
285
+ const metaB = (assets || []).find((a) => String(a?.id) === fallbackB);
307
286
  if (!metaA || !metaB || !Number.isFinite(Number(metaA.precision)) || !Number.isFinite(Number(metaB.precision))) {
308
- throw new Error(`Pool ${fullId}: failed to resolve asset metadata for ${idA}/${idB}`);
287
+ throw new Error(`Pool ${poolId}: failed to resolve asset metadata for ${fallbackA}/${fallbackB}`);
309
288
  }
310
289
  return {
311
- assetA: { id: idA, precision: Number(metaA.precision), symbol: String(metaA.symbol || idA) },
312
- assetB: { id: idB, precision: Number(metaB.precision), symbol: String(metaB.symbol || idB) },
290
+ assetA: { id: fallbackA, precision: Number(metaA.precision), symbol: String(metaA.symbol || fallbackA) },
291
+ assetB: { id: fallbackB, precision: Number(metaB.precision), symbol: String(metaB.symbol || fallbackB) },
292
+ poolId,
313
293
  };
314
294
  }
315
295
  async function run(cmd) {
@@ -327,20 +307,19 @@ async function run(cmd) {
327
307
  const endMs = Math.floor(Date.now() / bucketMs) * bucketMs;
328
308
  const startMs = endMs - lookbackHours * 3600 * 1000;
329
309
  const timeRange = { gte: new Date(startMs).toISOString(), lte: new Date(endMs).toISOString() };
330
- // Classify the target locally first so a typo'd bot / malformed pair
331
- // fails fast without waiting for a chain connection.
310
+ // Classify the target locally first so a malformed pair fails fast without
311
+ // waiting for a chain connection. A bot is matched by name/key, a pair by
312
+ // its `/`; everything else is a pool reference (id or pool token), which is
313
+ // resolved on chain with a clear error when it is neither.
332
314
  const botHit = findBotByTarget(target);
333
- const poolTarget = !botHit && isPoolIdTarget(target);
334
- const pairTarget = !botHit && !poolTarget && target.includes('/');
315
+ const pairTarget = !botHit && target.includes('/');
316
+ const poolTarget = !botHit && !pairTarget && isPoolTarget(target);
335
317
  // A pair target may be typed in any case ("assetb/asseta"); the legs are
336
318
  // canonicalized here so the chain call, the cache keys, the chart title and
337
319
  // the exported HTML all speak the same UPPERCASE symbols.
338
320
  const pairParts = pairTarget ? splitPairTarget(target) : [];
339
- if (!botHit && !poolTarget && !pairTarget) {
340
- const settings = loadBotSettings();
341
- const entries = Array.isArray(settings?.bots) ? settings.bots : [];
342
- const keys = entries.map((b, i) => computeBotKey(b, i)).filter(Boolean);
343
- throw new Error(`Unknown target "${target}". Use a bot name/key${keys.length ? ` (${keys.slice(0, 8).join(', ')}${keys.length > 8 ? ', …' : ''})` : ''}, a pool id (e.g. 133), or AssetA/AssetB.`);
321
+ if (!botHit && !pairTarget && !poolTarget) {
322
+ throw new Error(`Unknown target "${target}". ${knownTargetsHint(true)}`);
344
323
  }
345
324
  if (pairTarget && pairParts.length !== 2)
346
325
  throw new Error(`Invalid pair "${target}". Use AssetA/AssetB, e.g. TOKENA/TOKENB (case is normalized to uppercase)`);
@@ -384,8 +363,8 @@ async function run(cmd) {
384
363
  }
385
364
  }
386
365
  else if (poolTarget) {
387
- poolId = normalizePoolId(target.trim());
388
- const resolved = await resolvePoolAssets(poolId, bitsharesClient);
366
+ const resolved = await resolvePoolAssets(target, bitsharesClient);
367
+ poolId = resolved.poolId;
389
368
  assetA = resolved.assetA;
390
369
  assetB = resolved.assetB;
391
370
  sourceLabel = `pool ${poolId}`;
@@ -467,9 +446,6 @@ async function run(cmd) {
467
446
  // Everything above this point is identical for every command; only the
468
447
  // RENDERERS entry below differs.
469
448
  const renderer = RENDERERS[cmd];
470
- const analyzer = path.join(__dirname, '..', 'analysis', ...renderer.analyzerRel);
471
- if (!fs.existsSync(analyzer))
472
- throw new Error(`${renderer.exporterName} not found at ${analyzer} (run npm run build first)`);
473
449
  const feedSuffix = feedCtx ? '_feed' : '';
474
450
  const baseName = botKey
475
451
  ? `${cmd}_${sanitizeKey(botKey)}${feedSuffix}`
@@ -490,9 +466,7 @@ async function run(cmd) {
490
466
  // dropped on purpose: it duplicated that resolution.
491
467
  if (botKey)
492
468
  analyzerArgs.push('--bot-key', botKey);
493
- const result = spawnSync(process.execPath, [analyzer, ...analyzerArgs], { stdio: 'inherit' });
494
- if (result.status !== 0)
495
- throw new Error(`${renderer.exporterName} exited with status ${result.status}`);
469
+ runAnalysisScript(renderer.analyzerRel, analyzerArgs, renderer.exporterName);
496
470
  try {
497
471
  fs.unlinkSync(tmpFile);
498
472
  }
@@ -0,0 +1,18 @@
1
+ import type { BotEntry } from '../modules/bot_settings.js';
2
+ interface BotTarget {
3
+ botKey: string;
4
+ meta: BotEntry;
5
+ }
6
+ /** Pool id targets (`133` / `1.19.x`) — delegates to the shared pool-ref rules. */
7
+ declare function isPoolIdTarget(target: string): boolean;
8
+ /** True when a target could name a pool (numeric id or pool-token symbol). */
9
+ declare function isPoolTarget(target: string): boolean;
10
+ /** Find a bot by display name or by key (same rules as `dexbot tv`). */
11
+ declare function findBotByTarget(target: string): BotTarget | null;
12
+ /** Bot keys used in the unknown-target hint (first 8 shown by callers). */
13
+ declare function knownBotKeys(): string[];
14
+ /** Shared trailing hint for an unresolved target. */
15
+ declare function knownTargetsHint(includePool: boolean): string;
16
+ export { isPoolIdTarget, isPoolTarget, findBotByTarget, knownBotKeys, knownTargetsHint };
17
+ export type { BotTarget };
18
+ //# sourceMappingURL=chart_targets.d.ts.map
@@ -0,0 +1,52 @@
1
+ 'use strict';
2
+ /**
3
+ * Shared target resolution for chart-style CLI commands (`dexbot tv`, `dw`,
4
+ * `liquid`). Keeping bot lookup and key formatting here prevents the commands
5
+ * from drifting on which bots are recognised and how the "unknown target"
6
+ * hint is rendered.
7
+ */
8
+ import { isSameBotName } from '../modules/utils/sanitize_key.js';
9
+ import { isPoolIdRef, isPoolRefLike } from '../modules/liquidity_pool_ref.js';
10
+ import { loadBotMeta, loadBotSettings, computeBotKey } from '../analysis/bot_key_utils.js';
11
+ /** Pool id targets (`133` / `1.19.x`) — delegates to the shared pool-ref rules. */
12
+ function isPoolIdTarget(target) {
13
+ return isPoolIdRef(target);
14
+ }
15
+ /** True when a target could name a pool (numeric id or pool-token symbol). */
16
+ function isPoolTarget(target) {
17
+ return isPoolRefLike(target);
18
+ }
19
+ /** Find a bot by display name or by key (same rules as `dexbot tv`). */
20
+ function findBotByTarget(target) {
21
+ const settings = loadBotSettings();
22
+ const entries = Array.isArray(settings?.bots) ? settings.bots : [];
23
+ for (let i = 0; i < entries.length; i++) {
24
+ const entry = entries[i];
25
+ if (!entry)
26
+ continue;
27
+ if (isSameBotName(entry.name, target))
28
+ return { botKey: computeBotKey(entry, i) ?? '', meta: entry };
29
+ }
30
+ const meta = loadBotMeta(target);
31
+ if (meta) {
32
+ const idx = entries.findIndex((entry) => isSameBotName(entry.name, meta.name));
33
+ return { botKey: computeBotKey(meta, idx >= 0 ? idx : 0) ?? '', meta };
34
+ }
35
+ return null;
36
+ }
37
+ /** Bot keys used in the unknown-target hint (first 8 shown by callers). */
38
+ function knownBotKeys() {
39
+ const settings = loadBotSettings();
40
+ const entries = Array.isArray(settings?.bots) ? settings.bots : [];
41
+ return entries.map((entry, index) => computeBotKey(entry, index)).filter(Boolean);
42
+ }
43
+ /** Shared trailing hint for an unresolved target. */
44
+ function knownTargetsHint(includePool) {
45
+ const keys = knownBotKeys();
46
+ const botHint = keys.length ? ` (${keys.slice(0, 8).join(', ')}${keys.length > 8 ? ', …' : ''})` : '';
47
+ return includePool
48
+ ? `Use a bot name/key${botHint}, a pool id (133 / 1.19.133) or pool token, or AssetA/AssetB.`
49
+ : `Use a bot name/key${botHint} or AssetA/AssetB.`;
50
+ }
51
+ export { isPoolIdTarget, isPoolTarget, findBotByTarget, knownBotKeys, knownTargetsHint };
52
+ //# sourceMappingURL=chart_targets.js.map
@@ -2,7 +2,7 @@
2
2
  'use strict';
3
3
  /**
4
4
  * Usage:
5
- * dexbot dw <bot|pool-id|AssetA/AssetB> [--month N] [--chart <path>] [--feed|--pool|--book]
5
+ * dexbot dw <bot|pool|AssetA/AssetB> [--month N] [--chart <path>] [--feed|--pool|--book]
6
6
  *
7
7
  * Thin entry for the shared chart-command pipeline in scripts/chart_command.ts
8
8
  * (identical fetch/target logic as `dexbot tv`). This command renders through
@@ -0,0 +1,24 @@
1
+ #!/usr/bin/env node
2
+ interface LiquidConfig {
3
+ target: string | null;
4
+ analyzerArgs: string[];
5
+ help: boolean;
6
+ }
7
+ interface ResolvedPair {
8
+ base: string;
9
+ quote: string;
10
+ botName?: string;
11
+ botKey?: string;
12
+ }
13
+ /** Pool target: an id (`133` / `1.19.133`) or a pool token symbol. */
14
+ interface ResolvedPoolRef {
15
+ pool: string;
16
+ }
17
+ declare function printUsage(): void;
18
+ declare function parseArgs(argv: string[]): LiquidConfig;
19
+ declare function resolveTarget(target: string): ResolvedPair | ResolvedPoolRef;
20
+ /** Analyzer arguments for a resolved target (`--pair` or `--pool`). */
21
+ declare function analyzerArgsFor(target: ResolvedPair | ResolvedPoolRef, options: string[]): string[];
22
+ declare function run(): Promise<void>;
23
+ export { parseArgs, resolveTarget, analyzerArgsFor, printUsage, run };
24
+ //# sourceMappingURL=liquid.d.ts.map
@@ -0,0 +1,134 @@
1
+ #!/usr/bin/env node
2
+ 'use strict';
3
+ /**
4
+ * Usage:
5
+ * dexbot liquid <bot|pool|AssetA/AssetB> [--range F] [--depth N] [--steps N]
6
+ * [--pool <ref>] [--chart <path>] [--json <path>] [--quiet]
7
+ *
8
+ * Thin CLI wrapper behind the liquidity depth chart generator
9
+ * (analysis/analyze_liquidity.js): resolve a bot name/key, a pool (id or pool
10
+ * token) or a pair target, then render the live order-book + AMM pool chart.
11
+ *
12
+ * Supported targets:
13
+ * - bot name or key from profiles/bots.json (uses the bot's assetA/assetB)
14
+ * - pool id (133 / 1.19.133) or pool token (LP share-asset symbol)
15
+ * - AssetA/AssetB symbols (case-insensitive; normalized to UPPERCASE)
16
+ *
17
+ * The analyzer owns the chain work, depth sampling, pool resolution and HTML
18
+ * rendering; this entry only routes the target and forwards the options.
19
+ */
20
+ import { pathToFileURL } from 'node:url';
21
+ import { getErrorMessage } from '../modules/utils/errors.js';
22
+ import { splitPairTarget, normalizeAssetSymbol } from '../modules/utils/asset_symbols.js';
23
+ import { findBotByTarget, isPoolTarget, knownTargetsHint } from './chart_targets.js';
24
+ import { runAnalysisScript } from './analysis_runner.js';
25
+ const PASS_THROUGH_FLAGS = new Set(['--range', '--depth', '--steps', '--pool', '--chart', '--json']);
26
+ function printUsage() {
27
+ console.log('Usage: dexbot liquid <bot|pool|AssetA/AssetB> [options]');
28
+ console.log('Live cumulative-depth chart blending the limit-order book and the AMM pool (uPlot).');
29
+ console.log('');
30
+ console.log(' <bot> Bot name or key from profiles/bots.json');
31
+ console.log(' <pool> Pool id (133 / 1.19.133) or its pool token (LP share-asset symbol)');
32
+ console.log(' AssetA/AssetB Pair symbols, e.g. TOKENA/TOKENB (case-insensitive)');
33
+ console.log('');
34
+ console.log('Options:');
35
+ console.log(' --range <f> Price window half-width (default 0.5 => +/-50%)');
36
+ console.log(' --depth <n> Order-book levels per side (default 300; node cap commonly 300)');
37
+ console.log(' --steps <n> Price samples across the window (default 400)');
38
+ console.log(' --pool <ref> Restrict to one pool: id (133 / 1.19.133) or pool token');
39
+ console.log(' (default: deepest pool of the resolved pair)');
40
+ console.log(' --chart <path> Override the output HTML path');
41
+ console.log(' --json <path> Optional JSON dump of the sampled depth series');
42
+ console.log(' --quiet Suppress the console summary');
43
+ console.log(' --help Show this help');
44
+ console.log('');
45
+ console.log('Output: analysis/charts/liquidity_<base>_<quote>.html');
46
+ console.log('Price is quote per base; click the x-axis to invert, y-axis to switch depth asset.');
47
+ }
48
+ function parseArgs(argv) {
49
+ let target = null;
50
+ let help = false;
51
+ const analyzerArgs = [];
52
+ for (let i = 0; i < argv.length; i++) {
53
+ const arg = argv[i];
54
+ if (arg === '--help' || arg === '-h') {
55
+ help = true;
56
+ }
57
+ else if (arg === '--quiet') {
58
+ analyzerArgs.push(arg);
59
+ }
60
+ else if (PASS_THROUGH_FLAGS.has(arg)) {
61
+ const value = argv[++i];
62
+ if (value == null || value.startsWith('--')) {
63
+ throw new Error(`${arg} expects a value. Usage: dexbot liquid <bot|AssetA/AssetB> [options]`);
64
+ }
65
+ analyzerArgs.push(arg, value);
66
+ }
67
+ else if (arg.startsWith('--')) {
68
+ throw new Error(`Unknown flag "${arg}". Usage: dexbot liquid <bot|AssetA/AssetB> [options]`);
69
+ }
70
+ else if (!target) {
71
+ target = arg;
72
+ }
73
+ else {
74
+ throw new Error(`Unexpected argument "${arg}". Only one target is supported. Usage: dexbot liquid <bot|AssetA/AssetB> [options]`);
75
+ }
76
+ }
77
+ return { target, analyzerArgs, help };
78
+ }
79
+ function resolveTarget(target) {
80
+ if (target.includes('/')) {
81
+ const parts = splitPairTarget(target);
82
+ if (parts.length !== 2) {
83
+ throw new Error(`Invalid pair "${target}". Use AssetA/AssetB, e.g. TOKENA/TOKENB`);
84
+ }
85
+ return { base: parts[0], quote: parts[1] };
86
+ }
87
+ const hit = findBotByTarget(target);
88
+ if (hit) {
89
+ const base = normalizeAssetSymbol(hit.meta.assetA);
90
+ const quote = normalizeAssetSymbol(hit.meta.assetB);
91
+ if (!base || !quote)
92
+ throw new Error(`Bot '${target}' has no assetA/assetB pair in profiles/bots.json`);
93
+ return { base, quote, botName: hit.meta.name, botKey: hit.botKey };
94
+ }
95
+ // Not a bot and not a pair: a pool reference. Ids and pool tokens are both
96
+ // accepted (the analyzer resolves them on chain), so only references that
97
+ // could not name a pool at all fail locally.
98
+ if (!isPoolTarget(target)) {
99
+ throw new Error(`Unknown target "${target}". ${knownTargetsHint(true)}`);
100
+ }
101
+ return { pool: target };
102
+ }
103
+ /** Analyzer arguments for a resolved target (`--pair` or `--pool`). */
104
+ function analyzerArgsFor(target, options) {
105
+ if (!('pool' in target)) {
106
+ return ['--pair', `${target.base}/${target.quote}`, ...options];
107
+ }
108
+ // The target already names the pool; a second --pool would silently chart a
109
+ // different one (the analyzer keeps the last value), so reject it instead.
110
+ if (options.includes('--pool')) {
111
+ throw new Error('Target already names a pool; drop --pool (or use AssetA/AssetB with --pool)');
112
+ }
113
+ return ['--pool', target.pool, ...options];
114
+ }
115
+ async function run() {
116
+ const { target, analyzerArgs, help } = parseArgs(process.argv.slice(2));
117
+ if (help || !target) {
118
+ printUsage();
119
+ if (!help && !target)
120
+ process.exitCode = 1;
121
+ return;
122
+ }
123
+ const resolved = resolveTarget(target);
124
+ runAnalysisScript(['analyze_liquidity.js'], analyzerArgsFor(resolved, analyzerArgs), 'Liquidity chart generator');
125
+ }
126
+ const invoked = process.argv[1] && import.meta.url === pathToFileURL(process.argv[1]).href;
127
+ if (invoked) {
128
+ run().catch((err) => {
129
+ console.error(`[liquid] Error: ${getErrorMessage(err)}`);
130
+ process.exit(1);
131
+ });
132
+ }
133
+ export { parseArgs, resolveTarget, analyzerArgsFor, printUsage, run };
134
+ //# sourceMappingURL=liquid.js.map
@@ -15,11 +15,11 @@
15
15
  * npm run richlist -- <ASSET> --top 10
16
16
  */
17
17
  import { pathToFileURL } from 'node:url';
18
- import { normalizeAssetSymbol } from '../modules/utils/asset_symbols.js';
18
+ import { lookupAssetRefs } from '../modules/asset_lookup.js';
19
19
  const DB_API = 0; // database_api is always registered first
20
20
  const LOGIN_API = 1; // login_api (registered second)
21
21
  const FALLBACK_HOLDER_LIMIT = 100; // used when the node does not report api_limit_get_asset_holders
22
- const LOOKUP_PAGE = 100; // chunk size for lookup_asset_symbols / get_objects
22
+ const LOOKUP_PAGE = 100; // get_objects chunk size for the 2.3.x supply fetch
23
23
  /** Nodes known to expose `asset_api` to anonymous logins come first. */
24
24
  const DEFAULT_NODES = [
25
25
  'wss://dex.iobanker.com/ws',
@@ -242,20 +242,16 @@ async function readHolderLimit(client) {
242
242
  // Chain queries
243
243
  // ---------------------------------------------------------------------------
244
244
  export async function lookupSymbols(session, symbolsOrIds) {
245
- const out = [];
246
- for (let i = 0; i < symbolsOrIds.length; i += LOOKUP_PAGE) {
247
- const slice = symbolsOrIds.slice(i, i + LOOKUP_PAGE);
248
- // `lookup_asset_symbols` is case-sensitive: a lowercase symbol returns
249
- // null on-chain, so canonicalize before handing it to the node. Asset
250
- // object ids ("1.3.x") pass through untouched. `request` keeps the
251
- // caller's spelling so "asset not found" still echoes the input.
252
- const refs = slice.map((s) => normalizeAssetSymbol(s));
253
- const res = await session.client.call(session.dbApi, 'lookup_asset_symbols', [refs]);
254
- res.forEach((a, j) => out.push(a
255
- ? { request: slice[j], found: true, id: a.id, symbol: a.symbol, precision: a.precision }
256
- : { request: slice[j], found: false }));
257
- }
258
- return out;
245
+ // Shared case-insensitive lookup (modules/asset_lookup.ts): one batched
246
+ // get_assets call for the whole list, `request` keeps the caller's spelling
247
+ // so "asset not found" still echoes the input.
248
+ const looked = await lookupAssetRefs((method, args) => session.client.call(session.dbApi, method, args), symbolsOrIds);
249
+ // An object missing its symbol/precision is useless downstream, so treat it
250
+ // exactly like a miss instead of formatting amounts with `undefined`.
251
+ return looked.map(({ request, asset }) => (asset && asset.id && asset.symbol
252
+ && typeof asset.precision === 'number'
253
+ ? { request, found: true, id: asset.id, symbol: asset.symbol, precision: asset.precision }
254
+ : { request, found: false }));
259
255
  }
260
256
  /**
261
257
  * Look up symbols/ids. Legacy `bit*` MPA names were renamed on-chain without the
@@ -35,6 +35,8 @@
35
35
  * no keys, no transactions. Chain source of truth: bitshares-core 7.0.x.
36
36
  *
37
37
  * Usage:
38
+ * dexbot asset <symbol|1.3.x> [options] # CLI shortcut
39
+ * dexbot a <symbol|1.3.x> [options] # shorthand for the line above
38
40
  * node dist/scripts/token_distribution.js <symbol|1.3.x>
39
41
  * node dist/scripts/token_distribution.js <token> --json
40
42
  * node dist/scripts/token_distribution.js <asset-id> --no-html