dexbot 1.6.18 → 1.7.1

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 (146) hide show
  1. package/CHANGELOG.md +68 -0
  2. package/README.md +24 -18
  3. package/analysis/README.md +117 -5
  4. package/claw/package.json +1 -1
  5. package/claw/runtimes/openclaw-plugin/openclaw.plugin.json +1 -1
  6. package/claw/runtimes/openclaw-plugin/package.json +1 -1
  7. package/dist/analysis/account_resolver.js +5 -6
  8. package/dist/analysis/analyze_dynamic_weight.js +2 -1
  9. package/dist/analysis/analyze_kalman.js +3 -2
  10. package/dist/analysis/analyze_liquidity.d.ts +17 -0
  11. package/dist/analysis/analyze_liquidity.js +336 -0
  12. package/dist/analysis/analyze_regime.js +3 -2
  13. package/dist/analysis/analyze_regime_windows.js +3 -2
  14. package/dist/analysis/analyze_volatility.js +3 -2
  15. package/dist/analysis/bot_key_utils.d.ts +44 -1
  16. package/dist/analysis/bot_key_utils.js +76 -7
  17. package/dist/analysis/fills_cache.js +2 -1
  18. package/dist/analysis/grid_correction_check.d.ts +1 -19
  19. package/dist/analysis/grid_correction_check.js +12 -30
  20. package/dist/analysis/liquidity/liquidity_chain.d.ts +66 -0
  21. package/dist/analysis/liquidity/liquidity_chain.js +178 -0
  22. package/dist/analysis/liquidity/liquidity_chart_generator.d.ts +19 -0
  23. package/dist/analysis/liquidity/liquidity_chart_generator.js +693 -0
  24. package/dist/analysis/liquidity/liquidity_depth_model.d.ts +166 -0
  25. package/dist/analysis/liquidity/liquidity_depth_model.js +258 -0
  26. package/dist/analysis/liquidity/liquidity_view.d.ts +53 -0
  27. package/dist/analysis/liquidity/liquidity_view.js +66 -0
  28. package/dist/analysis/resolve_bot_accounts.js +7 -6
  29. package/dist/analysis/trade_profitability.js +4 -2
  30. package/dist/analysis/tradingview/analyze_tradingview.js +2 -1
  31. package/dist/credential-daemon.js +13 -2
  32. package/dist/dexbot.js +77 -172
  33. package/dist/modules/account_bots.d.ts +11 -1
  34. package/dist/modules/account_orders.d.ts +12 -0
  35. package/dist/modules/account_orders.js +30 -0
  36. package/dist/modules/asset_lookup.d.ts +25 -0
  37. package/dist/modules/asset_lookup.js +75 -0
  38. package/dist/modules/bitshares-native/transport.js +24 -6
  39. package/dist/modules/bitshares_client.d.ts +24 -6
  40. package/dist/modules/bitshares_client.js +44 -7
  41. package/dist/modules/bot_settings.d.ts +2 -0
  42. package/dist/modules/chain_scan.d.ts +64 -0
  43. package/dist/modules/chain_scan.js +80 -0
  44. package/dist/modules/cli_colors.d.ts +5 -0
  45. package/dist/modules/cli_colors.js +7 -0
  46. package/dist/modules/cli_progress.d.ts +51 -0
  47. package/dist/modules/cli_progress.js +113 -0
  48. package/dist/modules/constants.d.ts +26 -3
  49. package/dist/modules/constants.js +63 -8
  50. package/dist/modules/dexbot_class.d.ts +1 -6
  51. package/dist/modules/dexbot_class.js +14 -0
  52. package/dist/modules/dexbot_cow_runtime.d.ts +97 -7
  53. package/dist/modules/dexbot_cow_runtime.js +634 -136
  54. package/dist/modules/dexbot_fill_runtime.js +132 -23
  55. package/dist/modules/dexbot_maintenance_runtime.js +242 -74
  56. package/dist/modules/dexbot_startup_runtime.js +32 -20
  57. package/dist/modules/dexbot_state_recovery.d.ts +33 -1
  58. package/dist/modules/dexbot_state_recovery.js +167 -5
  59. package/dist/modules/launcher/runtime_entry.d.ts +21 -1
  60. package/dist/modules/launcher/runtime_entry.js +36 -1
  61. package/dist/modules/liquidity_pool_ref.d.ts +32 -0
  62. package/dist/modules/liquidity_pool_ref.js +116 -0
  63. package/dist/modules/node_connect_policy.d.ts +8 -1
  64. package/dist/modules/node_connect_policy.js +18 -2
  65. package/dist/modules/node_flap_score.d.ts +87 -0
  66. package/dist/modules/node_flap_score.js +124 -0
  67. package/dist/modules/node_health_cache.d.ts +40 -3
  68. package/dist/modules/node_health_cache.js +66 -20
  69. package/dist/modules/node_manager.d.ts +101 -19
  70. package/dist/modules/node_manager.js +255 -65
  71. package/dist/modules/order/accounting.js +56 -7
  72. package/dist/modules/order/format.d.ts +24 -10
  73. package/dist/modules/order/format.js +30 -10
  74. package/dist/modules/order/grid.js +91 -13
  75. package/dist/modules/order/grid_reconcile.d.ts +5 -1
  76. package/dist/modules/order/grid_reconcile.js +333 -189
  77. package/dist/modules/order/grid_reconcile_internal.d.ts +38 -2
  78. package/dist/modules/order/grid_reconcile_internal.js +298 -100
  79. package/dist/modules/order/index.d.ts +19 -1
  80. package/dist/modules/order/lifecycle.d.ts +353 -0
  81. package/dist/modules/order/lifecycle.js +1109 -0
  82. package/dist/modules/order/manager.d.ts +273 -5
  83. package/dist/modules/order/manager.js +654 -48
  84. package/dist/modules/order/placement_lock.d.ts +102 -0
  85. package/dist/modules/order/placement_lock.js +222 -0
  86. package/dist/modules/order/strategy.js +13 -1
  87. package/dist/modules/order/sync_engine.d.ts +33 -1
  88. package/dist/modules/order/sync_engine.js +241 -73
  89. package/dist/modules/order/utils/math.d.ts +39 -1
  90. package/dist/modules/order/utils/math.js +83 -1
  91. package/dist/modules/order/utils/order.d.ts +181 -5
  92. package/dist/modules/order/utils/order.js +455 -9
  93. package/dist/modules/order/utils/system.d.ts +81 -1
  94. package/dist/modules/order/utils/system.js +331 -44
  95. package/dist/modules/order/utils/validate.d.ts +7 -1
  96. package/dist/modules/order/utils/validate.js +80 -3
  97. package/dist/modules/outcome.d.ts +54 -0
  98. package/dist/modules/outcome.js +51 -0
  99. package/dist/modules/settings_merge.d.ts +4 -0
  100. package/dist/modules/settings_merge.js +9 -0
  101. package/dist/modules/timing_policy.d.ts +82 -0
  102. package/dist/modules/timing_policy.js +244 -0
  103. package/dist/modules/types.d.ts +137 -0
  104. package/dist/modules/utils/asset_symbols.d.ts +13 -2
  105. package/dist/modules/utils/asset_symbols.js +21 -2
  106. package/dist/scripts/analysis_runner.d.ts +10 -0
  107. package/dist/scripts/analysis_runner.js +33 -0
  108. package/dist/scripts/analyze-credit.js +54 -17
  109. package/dist/scripts/analyze-orders.d.ts +4 -2
  110. package/dist/scripts/analyze-orders.js +115 -35
  111. package/dist/scripts/asset.d.ts +26 -0
  112. package/dist/scripts/asset.js +165 -0
  113. package/dist/scripts/bts_distribution.d.ts +1 -0
  114. package/dist/scripts/bts_distribution.js +194 -142
  115. package/dist/scripts/chart_command.d.ts +1 -1
  116. package/dist/scripts/chart_command.js +60 -86
  117. package/dist/scripts/chart_targets.d.ts +18 -0
  118. package/dist/scripts/chart_targets.js +48 -0
  119. package/dist/scripts/dw.js +1 -1
  120. package/dist/scripts/liquid.d.ts +24 -0
  121. package/dist/scripts/liquid.js +134 -0
  122. package/dist/scripts/rich_list.js +12 -16
  123. package/dist/scripts/test-credit-renewal.js +12 -5
  124. package/dist/scripts/token_distribution.d.ts +2 -0
  125. package/dist/scripts/token_distribution.js +132 -108
  126. package/dist/scripts/tv.js +1 -1
  127. package/dist/scripts/verify-browser-bundle.js +18 -0
  128. package/docs/COW_INVARIANTS.md +69 -10
  129. package/docs/DEXBOT_COMPARISON.md +6 -6
  130. package/docs/EVOLUTION.md +10 -8
  131. package/docs/FUND_MOVEMENT_AND_ACCOUNTING.md +1 -1
  132. package/docs/GRID_PRICE_INVARIANT.md +5 -2
  133. package/docs/GRID_RECONCILE.md +36 -11
  134. package/docs/LOGGING.md +50 -4
  135. package/docs/ORDER_ENGINE_POST_1.0_RETROSPECTIVE.md +177 -27
  136. package/docs/README.md +23 -2
  137. package/docs/WORKFLOW.md +12 -4
  138. package/docs/architecture.md +42 -5
  139. package/docs/developer_guide.md +25 -8
  140. package/modules/README.md +8 -1
  141. package/package.json +3 -1
  142. package/scripts/README.md +39 -7
  143. package/scripts/pdev.sh +14 -1
  144. package/scripts/pmain.sh +23 -8
  145. package/scripts/ptest.sh +7 -0
  146. package/tests/README.md +30 -1
@@ -3,8 +3,9 @@
3
3
  *
4
4
  * BitShares stores asset symbols canonically UPPERCASE, so the assetA and
5
5
  * assetB symbols of a bot pair are always UPPERCASE on chain.
6
- * `lookup_asset_symbols` is case-sensitive: a lowercase symbol resolves to
7
- * null (not an error), so a lowercase input silently drops the asset. Casing
6
+ * The chain's asset lookups (`get_assets` / `lookup_asset_symbols`) are
7
+ * case-sensitive: a lowercase symbol resolves to null (not an error), so a
8
+ * lowercase input silently drops the asset. Casing
8
9
  * also leaks into everything built from a resolved symbol: the `symbol` field
9
10
  * we attach to assets, chart titles, cache-file names, Kibana query terms, and
10
11
  * strict in-process comparisons such as `assetA === 'CORE'`. That is a
@@ -35,6 +36,16 @@ export declare function normalizeAssetSymbol(value: unknown): string;
35
36
  * mixed "id or symbol" reference (credit runtime, credential policy, pools).
36
37
  */
37
38
  export declare function normalizeAssetRef(value: unknown): string;
39
+ /**
40
+ * Both spellings of a human-typed asset reference: the reference as typed
41
+ * (trimmed) and its canonical UPPERCASE form. Resolvers query the canonical form
42
+ * first and retry the as-typed spelling only when that misses (see
43
+ * modules/asset_lookup.ts), because `get_assets` is case-sensitive and a node
44
+ * may still hold a non-canonical symbol. Object ids collapse to one entry.
45
+ *
46
+ * @returns [] for empty input, otherwise 1-2 distinct spellings.
47
+ */
48
+ export declare function assetSymbolCandidates(value: unknown): string[];
38
49
  /** Case- and whitespace-insensitive asset-symbol equality. */
39
50
  export declare function isSameAssetSymbol(a: unknown, b: unknown): boolean;
40
51
  /**
@@ -3,8 +3,9 @@
3
3
  *
4
4
  * BitShares stores asset symbols canonically UPPERCASE, so the assetA and
5
5
  * assetB symbols of a bot pair are always UPPERCASE on chain.
6
- * `lookup_asset_symbols` is case-sensitive: a lowercase symbol resolves to
7
- * null (not an error), so a lowercase input silently drops the asset. Casing
6
+ * The chain's asset lookups (`get_assets` / `lookup_asset_symbols`) are
7
+ * case-sensitive: a lowercase symbol resolves to null (not an error), so a
8
+ * lowercase input silently drops the asset. Casing
8
9
  * also leaks into everything built from a resolved symbol: the `symbol` field
9
10
  * we attach to assets, chart titles, cache-file names, Kibana query terms, and
10
11
  * strict in-process comparisons such as `assetA === 'CORE'`. That is a
@@ -50,6 +51,24 @@ export function normalizeAssetSymbol(value) {
50
51
  export function normalizeAssetRef(value) {
51
52
  return normalizeAssetSymbol(value);
52
53
  }
54
+ /**
55
+ * Both spellings of a human-typed asset reference: the reference as typed
56
+ * (trimmed) and its canonical UPPERCASE form. Resolvers query the canonical form
57
+ * first and retry the as-typed spelling only when that misses (see
58
+ * modules/asset_lookup.ts), because `get_assets` is case-sensitive and a node
59
+ * may still hold a non-canonical symbol. Object ids collapse to one entry.
60
+ *
61
+ * @returns [] for empty input, otherwise 1-2 distinct spellings.
62
+ */
63
+ export function assetSymbolCandidates(value) {
64
+ if (value === null || value === undefined)
65
+ return [];
66
+ const typed = String(value).trim();
67
+ if (!typed)
68
+ return [];
69
+ const canonical = normalizeAssetSymbol(typed);
70
+ return typed === canonical ? [canonical] : [typed, canonical];
71
+ }
53
72
  /** Case- and whitespace-insensitive asset-symbol equality. */
54
73
  export function isSameAssetSymbol(a, b) {
55
74
  const na = normalizeAssetSymbol(a);
@@ -0,0 +1,10 @@
1
+ /** Absolute path to an analysis script, e.g. ['tradingview','analyze_tradingview.js']. */
2
+ declare function analysisScriptPath(segments: string[]): string;
3
+ /**
4
+ * Resolve, run and validate an analysis script.
5
+ * Throws with a command-specific `label` when the build is missing or the
6
+ * renderer exits non-zero; child stdio is inherited.
7
+ */
8
+ declare function runAnalysisScript(segments: string[], args: string[], label: string): void;
9
+ export { analysisScriptPath, runAnalysisScript };
10
+ //# sourceMappingURL=analysis_runner.d.ts.map
@@ -0,0 +1,33 @@
1
+ 'use strict';
2
+ /**
3
+ * Spawn an analysis entry point (compiled `dist/analysis/**\/*.js`).
4
+ *
5
+ * Chart-style commands (`tv`, `dw`, `liquid`) all render through a separate
6
+ * analysis binary. This helper centralises the path resolution, existence
7
+ * check, project-root cwd, and exit-status handling so a missing build or a
8
+ * crashed renderer reports the same way everywhere.
9
+ */
10
+ import path from 'node:path';
11
+ import { fileURLToPath } from 'node:url';
12
+ const __filename = fileURLToPath(import.meta.url);
13
+ const __dirname = path.dirname(__filename);
14
+ import { PATHS } from '../modules/paths.js';
15
+ import { runRuntimeScript } from '../modules/launcher/runtime_entry.js';
16
+ /** Absolute path to an analysis script, e.g. ['tradingview','analyze_tradingview.js']. */
17
+ function analysisScriptPath(segments) {
18
+ return path.join(__dirname, '..', 'analysis', ...segments);
19
+ }
20
+ /**
21
+ * Resolve, run and validate an analysis script.
22
+ * Throws with a command-specific `label` when the build is missing or the
23
+ * renderer exits non-zero; child stdio is inherited.
24
+ */
25
+ function runAnalysisScript(segments, args, label) {
26
+ runRuntimeScript(analysisScriptPath(segments), args, {
27
+ label,
28
+ cwd: PATHS.PROJECT_ROOT,
29
+ nonZero: 'throw',
30
+ });
31
+ }
32
+ export { analysisScriptPath, runAnalysisScript };
33
+ //# sourceMappingURL=analysis_runner.js.map
@@ -28,20 +28,29 @@ const require = createRequire(import.meta.url);
28
28
  * debt_asset, debt_amount, collateral_asset, collateral_amount.
29
29
  *
30
30
  * Usage:
31
- * node dist/scripts/analyze-credit.js # credit-enabled bots only
32
- * node dist/scripts/analyze-credit.js <bot> # single bot (name or key)
31
+ * node dist/scripts/analyze-credit.js # credit-enabled bots only
32
+ * node dist/scripts/analyze-credit.js <bot> # single bot (name or key)
33
+ * node dist/scripts/analyze-credit.js <account> # every bot on that account
34
+ *
35
+ * The positional target matches a bot name/key, or the chain account the bot
36
+ * trades from (`preferredAccount` as a name or 1.2.x id, or the `accountId`
37
+ * stamped beside it by analysis/account_resolver.ts). Account matching is what
38
+ * makes `dexbot credit <account>` work on a shared account, where one account
39
+ * hosts several bot entries — the same target spelling `dexbot pnl` accepts.
33
40
  */
34
41
  const { BitShares, waitForConnected, disconnectClient, setSuppressConnectionLog } = require('../modules/bitshares_client');
35
42
  const { FEE_PARAMETERS } = require('../modules/constants');
36
43
  const { PATHS } = require('../modules/paths');
37
44
  const { getErrorMessage } = require('../modules/utils/errors');
38
- const { sanitizeKey } = require('../modules/utils/sanitize_key');
39
45
  const { normalizeAssetRef, normalizeAssetSymbol, isSameAssetSymbol } = require('../modules/utils/asset_symbols');
40
46
  const { loadSettingsFile, resolveRawBotEntries, normalizeBotEntries } = require('../modules/bot_settings');
41
47
  import { pathToFileURL } from 'node:url';
42
48
  // Terminal colors: centralized palette (modules/cli_colors.ts), shared with
43
49
  // `dexbot order` so both analyzers stay visually in lockstep.
44
50
  import { CLI_COLORS as colors } from '../modules/cli_colors.js';
51
+ // `<bot|account>` target matching lives in analysis/bot_key_utils so `credit`,
52
+ // `order`, `pnl` and the chart commands share one rule set.
53
+ import { matchBotTargetIn } from '../analysis/bot_key_utils.js';
45
54
  import { muteChainLogs } from '../modules/utils/chain_logs.js';
46
55
  import { setGlobalConsoleLevel } from '../modules/order/logger.js';
47
56
  import { deriveLiquidityPoolTokenValue } from '../modules/order/utils/system.js';
@@ -186,29 +195,57 @@ function mpaCollateralRaw(order) {
186
195
  async function main() {
187
196
  const rawArgs = process.argv.slice(2);
188
197
  if (rawArgs.includes('-h') || rawArgs.includes('--help')) {
189
- console.log('Usage: dexbot credit [<bot>]');
198
+ console.log('Usage: dexbot credit [<bot|account>]');
190
199
  console.log(' No args Summed MPA + borrowed-credit positions for credit-enabled bots.');
191
- console.log(' <bot> Only the named bot (matches name or sanitized key).');
200
+ console.log(' <bot> Only the named bot (matches name or bot key).');
201
+ console.log(' <account> Only the bots trading that account (preferredAccount name or 1.2.x id);');
202
+ console.log(' a shared account lists every bot entry that uses it.');
192
203
  console.log('Live chain data via get_margin_positions + get_credit_deals_by_borrower per preferredAccount.');
193
204
  process.exit(0);
194
205
  }
195
206
  const botFilter = rawArgs.find((a) => !a.startsWith('-'))?.trim().toLowerCase() || null;
196
207
  const { config } = loadSettingsFile(BOTS_FILE);
197
- let bots = normalizeBotEntries(resolveRawBotEntries(config))
198
- .filter((b) => b && b.active !== false && hasLending(b));
199
- if (botFilter) {
200
- const sanitized = sanitizeKey(botFilter);
201
- const matched = bots.filter((b) => String(b.name || '').toLowerCase() === botFilter ||
202
- sanitizeKey(String(b.name || '')) === sanitized ||
203
- String(b.botKey || '').toLowerCase() === botFilter);
204
- if (matched.length === 0) {
205
- console.log(`${colors.sell}No credit bot found for '${botFilter}'.${colors.reset}`);
208
+ // Keep every entry (with its file-order index, which unnamed bots' keys are
209
+ // derived from) so target matching cannot drift from what the runtime writes.
210
+ const allBots = normalizeBotEntries(resolveRawBotEntries(config)).filter((b) => Boolean(b));
211
+ const activeBots = allBots.filter((b) => b.active !== false);
212
+ // One account can back several bot entries, so a matched account selects all
213
+ // of them — the account-level view `dexbot credit <account>` promises.
214
+ const targets = botFilter ? matchBotTargetIn(allBots, botFilter) : [];
215
+ const targeted = botFilter ? new Set(targets.map((m) => m.meta)) : null;
216
+ let bots = activeBots.filter((b) => hasLending(b) && (!targeted || targeted.has(b)));
217
+ if (botFilter && bots.length === 0) {
218
+ const matchedEntries = targets.map((m) => m.meta);
219
+ const describe = (b) => ` - ${b.name || b.botKey || 'unnamed'}${b.preferredAccount ? ` (account: ${b.preferredAccount})` : ''}${hasLending(b) ? '' : ' (no debtPolicy)'}${b.active === false ? ' (inactive)' : ''}`;
220
+ // The `Available bots` hint keeps listing inactive entries so a disabled
221
+ // bot's name and account stay discoverable.
222
+ if (matchedEntries.length === 0) {
223
+ console.log(`${colors.sell}No credit bot or account found for '${botFilter}'.${colors.reset}`);
206
224
  console.log('Available bots:');
207
- const all = normalizeBotEntries(resolveRawBotEntries(config));
208
- all.forEach((b) => console.log(` - ${b.name}${hasLending(b) ? '' : ' (no debtPolicy)'}`));
225
+ allBots.forEach((b) => console.log(describe(b)));
226
+ process.exit(0);
227
+ }
228
+ const enabledMatches = matchedEntries.filter((b) => b.active !== false);
229
+ if (enabledMatches.length === 0) {
230
+ // Disabled bots are never reported, whatever their policy.
231
+ console.log(`${colors.yellow}Matched '${botFilter}' only on inactive entries:${colors.reset}`);
232
+ matchedEntries.forEach((b) => console.log(describe(b)));
233
+ console.log('Enable it with `dexbot enable <bot>`, or drop the filter to sum the active credit bots.');
209
234
  process.exit(0);
210
235
  }
211
- bots = matched;
236
+ // Enabled match(es) without a debtPolicy: that policy also supplies the
237
+ // per-bot asset filter, so without it a shared account's positions cannot
238
+ // be attributed. List every match — an inactive entry may still carry the
239
+ // policy and only need enabling.
240
+ console.log(`${colors.yellow}Matched '${botFilter}' but no enabled entry has debtPolicy.lending:${colors.reset}`);
241
+ matchedEntries.forEach((b) => console.log(describe(b)));
242
+ // Every enabled match lacks the policy here (a credit-enabled one would have
243
+ // been reported), so both remedies are always offered.
244
+ console.log('Add a debtPolicy via `dexbot bot` to include it in `dexbot credit`.');
245
+ if (matchedEntries.some((b) => b.active === false)) {
246
+ console.log('Disabled entries also need `dexbot enable <bot>` first.');
247
+ }
248
+ process.exit(0);
212
249
  }
213
250
  if (bots.length === 0) {
214
251
  console.log(`No credit-enabled bots found in ${BOTS_FILE} (debtPolicy.lending is empty everywhere).`);
@@ -10,13 +10,15 @@
10
10
  * - Grid slot distribution (% near center) vs grid composition
11
11
  *
12
12
  * Usage:
13
- * node dist/scripts/analyze-orders.js # terminal output
14
- * node dist/scripts/analyze-orders.js --export # standalone HTML report
13
+ * node dist/scripts/analyze-orders.js # terminal output
14
+ * node dist/scripts/analyze-orders.js <bot|account> # one bot, or every bot on an account
15
+ * node dist/scripts/analyze-orders.js --export # standalone HTML report
15
16
  */
16
17
  import { CLI_COLORS as colors } from '../modules/cli_colors.js';
17
18
  /** Loose JSON-object view used across the analyzer. */
18
19
  type JsonObj = Record<string, unknown>;
19
20
  interface GridSlot {
21
+ id?: string;
20
22
  type?: string;
21
23
  state?: string;
22
24
  price: number;
@@ -10,13 +10,16 @@
10
10
  * - Grid slot distribution (% near center) vs grid composition
11
11
  *
12
12
  * Usage:
13
- * node dist/scripts/analyze-orders.js # terminal output
14
- * node dist/scripts/analyze-orders.js --export # standalone HTML report
13
+ * node dist/scripts/analyze-orders.js # terminal output
14
+ * node dist/scripts/analyze-orders.js <bot|account> # one bot, or every bot on an account
15
+ * node dist/scripts/analyze-orders.js --export # standalone HTML report
15
16
  */
16
17
  import fs from 'node:fs';
17
18
  import path from 'node:path';
18
19
  import { formatCurrency, formatFundsValue } from '../modules/order/format.js';
19
20
  import { resolveConfiguredPriceBound } from '../modules/order/utils/order.js';
21
+ import { calculateGapSlots } from '../modules/order/utils/math.js';
22
+ import { parseSlotIndex } from '../modules/order/utils/slot.js';
20
23
  import { ORDER_TYPES, ORDER_STATES, MARKET_ADAPTER } from '../modules/constants.js';
21
24
  import { applyAsymmetricBounds } from '../market_adapter/core/asymmetric_bounds.js';
22
25
  import { PATHS } from '../modules/paths.js';
@@ -25,7 +28,11 @@ import { getStorage } from '../modules/storage/index.js';
25
28
  const { readJSON } = getStorage();
26
29
  import { getErrorMessage } from '../modules/utils/errors.js';
27
30
  import { toFileUrl } from '../analysis/chart_utils.js';
28
- import { isSameBotName, sanitizeKey } from '../modules/utils/sanitize_key.js';
31
+ import { CLI_TAGS, savedLine } from '../modules/cli_progress.js';
32
+ import { isSameBotName } from '../modules/utils/sanitize_key.js';
33
+ // Bot keys and `<bot|account>` target matching are shared with the other
34
+ // analysis tools (analysis/bot_key_utils) so the commands cannot drift.
35
+ import { computeBotKey, matchBotAccountTarget, matchBotEntryTarget } from '../analysis/bot_key_utils.js';
29
36
  import { CLI_COLORS as colors } from '../modules/cli_colors.js';
30
37
  import { pathToFileURL } from 'node:url';
31
38
  const ORDERS_DIR = PATHS.ORDERS_DIR;
@@ -52,17 +59,6 @@ const HEADER_WIDTH = 11 + BAR_WIDTH;
52
59
  * Utility Functions
53
60
  * Helper functions for file I/O, formatting, and data retrieval
54
61
  */
55
- function createBotKey(bot, index) {
56
- if (bot && bot.name) {
57
- return sanitizeKey(String(bot.name));
58
- }
59
- const identifier = bot && bot.assetA && bot.assetB
60
- ? `${bot.assetA}/${bot.assetB}`
61
- : bot && bot.assetAId && bot.assetBId
62
- ? `${bot.assetAId}/${bot.assetBId}`
63
- : `bot-${index}`;
64
- return `${sanitizeKey(identifier)}-${index}`;
65
- }
66
62
  function hasOrderGrid(data) {
67
63
  if (!data || typeof data !== 'object' || Array.isArray(data))
68
64
  return false;
@@ -298,7 +294,9 @@ function getConfiguredBotConfig(botKey, botData) {
298
294
  return botsConfig.find((bot, index) => {
299
295
  if (!bot)
300
296
  return false;
301
- return createBotKey(bot, index) === botKey || (meta.name && isSameBotName(bot.name, meta.name));
297
+ // Same key generator the runtime writes with (analysis/bot_key_utils →
298
+ // modules/account_orders), so a renamed pair can never drift.
299
+ return computeBotKey(bot, index) === botKey || (meta.name && isSameBotName(bot.name, meta.name));
302
300
  }) || null;
303
301
  }
304
302
  function getOrderFileCandidate(fileName) {
@@ -394,12 +392,23 @@ function analyzeOrder(botData, config, botKey) {
394
392
  const hasBoundary = typeof botData.boundaryIdx === 'number' && Number.isFinite(botData.boundaryIdx);
395
393
  const boundaryIdx = hasBoundary ? botData.boundaryIdx : 0;
396
394
  const boundaryLess = !hasBoundary;
397
- const buySlots = boundaryLess
398
- ? grid.filter((s) => s.type === ORDER_TYPES.BUY)
399
- : grid.filter((s, i) => i <= boundaryIdx && s.type === ORDER_TYPES.BUY);
400
- const sellSlots = boundaryLess
401
- ? grid.filter((s) => s.type === ORDER_TYPES.SELL)
402
- : grid.filter((s, i) => i > boundaryIdx && s.type === ORDER_TYPES.SELL);
395
+ /** Slot identity: the parsed `slot-N` id wins over the array position (a re-sort invalidates position). */
396
+ const slotIndex = (s, i) => {
397
+ const parsed = parseSlotIndex(s?.id);
398
+ return parsed === null ? i : parsed;
399
+ };
400
+ // CLASSIFY BY SLOT TYPE, NOT BY ARRAY SLICE.
401
+ // The persisted boundary says where the rails SHOULD be; a live order can be
402
+ // stranded inside the spread band (a boundary commit moved away from it and
403
+ // GAP-EVAC has not evacuated it yet) and it keeps its rail type. Slicing by
404
+ // index (`i <= boundaryIdx`) dropped exactly those orders from every bucket:
405
+ // the report then summed to fewer slots than the grid holds AND measured the
406
+ // "real" spread from the geometry edge instead of the actual top of book
407
+ // (observed live: 2.02% reported vs 1.21% on chain, with two live buys hidden
408
+ // inside the band). Type buckets keep every order visible; the geometry
409
+ // disagreement is reported explicitly via `gapBand.inBandPlaced`.
410
+ const buySlots = grid.filter((s) => s.type === ORDER_TYPES.BUY);
411
+ const sellSlots = grid.filter((s) => s.type === ORDER_TYPES.SELL);
403
412
  const spreadSlots = grid.filter((s) => s.type === ORDER_TYPES.SPREAD);
404
413
  const activeBuySlots = buySlots.filter((s) => s.state === ORDER_STATES.ACTIVE || s.state === ORDER_STATES.PARTIAL);
405
414
  const virtualBuySlots = buySlots.filter((s) => s.state === ORDER_STATES.VIRTUAL);
@@ -424,8 +433,11 @@ function analyzeOrder(botData, config, botKey) {
424
433
  // design (a partially-placed grid IS partially masked); it is not a bug, but
425
434
  // the output should be read with that caveat in mind.
426
435
  const hasOrderId = (s) => !!(s && s.orderId);
427
- const railBuys = boundaryLess ? grid.filter((s) => s.type === ORDER_TYPES.BUY) : grid.slice(0, boundaryIdx + 1);
428
- const railSells = boundaryLess ? grid.filter((s) => s.type === ORDER_TYPES.SELL) : grid.slice(boundaryIdx + 1);
436
+ // Rail lists are type-based for the same reason as the buckets above: a
437
+ // stranded live order is still a live order on its side, and excluding it
438
+ // fabricates a tighter (geometry-edge) spread.
439
+ const railBuys = buySlots;
440
+ const railSells = sellSlots;
429
441
  const placedBuys = railBuys.filter((s) => s.type === ORDER_TYPES.BUY && hasOrderId(s));
430
442
  const placedSells = railSells.filter((s) => s.type === ORDER_TYPES.SELL && hasOrderId(s));
431
443
  const geoBuy = railBuys.filter((s) => s.type === ORDER_TYPES.BUY);
@@ -445,6 +457,45 @@ function analyzeOrder(botData, config, botKey) {
445
457
  const realSpread = bestBuySlot && bestSellSlot
446
458
  ? ((bestSellSlot.price - bestBuySlot.price) / bestBuySlot.price)
447
459
  : 0;
460
+ /**
461
+ * Gap-band occupancy: live rail orders resting strictly inside the band.
462
+ * These are the spread-collapse signature — they hold band slots that should
463
+ * be empty, so the top-of-book spread is narrower than the configured gap.
464
+ * Detection is geometry-only (slot index vs boundary/gap), matching the
465
+ * runtime's `detectGapEvacuationCandidates`. The band width comes from the
466
+ * snapshot's frozen genesis (the geometry the slots were built with), then
467
+ * the live config, then the count of SPREAD-typed slots.
468
+ */
469
+ const snapshotGapSlots = Number(botData.genesis?.gapSlots);
470
+ // Unknown geometry stays unknown: without a frozen genesis gap or a live
471
+ // config there is no band to judge, and guessing one (e.g. from the
472
+ // SPREAD-typed slot count, which includes empty rail holes) would fabricate
473
+ // an "occupied band" warning. Same absent-aware rule as the runtime.
474
+ const gapSlots = Number.isFinite(snapshotGapSlots) && snapshotGapSlots >= 0
475
+ ? Math.floor(snapshotGapSlots)
476
+ : (config
477
+ ? calculateGapSlots(config.incrementPercent, config.targetSpreadPercent, config.gridLimits)
478
+ : null);
479
+ const sellStartIdx = hasBoundary && gapSlots !== null ? boundaryIdx + 1 + gapSlots : null;
480
+ const inBandPlaced = [];
481
+ if (hasBoundary && gapSlots !== null && sellStartIdx !== null) {
482
+ grid.forEach((s, i) => {
483
+ if (!hasOrderId(s))
484
+ return;
485
+ const idx = slotIndex(s, i);
486
+ if (idx > boundaryIdx && idx < sellStartIdx) {
487
+ inBandPlaced.push({
488
+ // Real snapshots always carry a slot id; fall back to the chain order
489
+ // id (then the array position) so the report always names something
490
+ // an operator can act on.
491
+ id: String(s.id ?? s.orderId ?? `#${i}`),
492
+ type: String(s.type ?? '?'),
493
+ price: Number(s.price),
494
+ idx,
495
+ });
496
+ }
497
+ });
498
+ }
448
499
  let spreadDiff, targetSpread, incrementCheck;
449
500
  /**
450
501
  * Config-based Comparisons
@@ -526,6 +577,7 @@ function analyzeOrder(botData, config, botKey) {
526
577
  buy: buySlots.length,
527
578
  sell: sellSlots.length,
528
579
  spread: spreadSlots.length,
580
+ stranded: inBandPlaced.length,
529
581
  activeBuy: activeBuySlots.length,
530
582
  virtualBuy: virtualBuySlots.length,
531
583
  activeSell: activeSellSlots.length,
@@ -533,6 +585,11 @@ function analyzeOrder(botData, config, botKey) {
533
585
  partialBuy: buySlots.filter((s) => s.state === ORDER_STATES.PARTIAL).length,
534
586
  partialSell: sellSlots.filter((s) => s.state === ORDER_STATES.PARTIAL).length
535
587
  },
588
+ gapBand: {
589
+ gapSlots,
590
+ sellStartIdx,
591
+ inBandPlaced
592
+ },
536
593
  // Slot data for weight visualization
537
594
  slotData: {
538
595
  buy: buySlots,
@@ -1136,6 +1193,19 @@ function formatAnalysis(analysisInput) {
1136
1193
  else {
1137
1194
  lines.push(` Spread:${formatPercent(analysis.spread.real).padStart(6)} | Incr.:${formatPercent(analysis.increment.avg).padStart(6)}`);
1138
1195
  }
1196
+ // Spread-collapse warning: live rail orders sitting inside the gap band eat
1197
+ // the spread slots, so the reported spread is the REAL top-of-book gap (which
1198
+ // is narrower than the configured one). Naming the slots is what makes the
1199
+ // state actionable — they need a GAP-EVAC evacuation, not a config change.
1200
+ const inBandPlaced = analysis.gapBand?.inBandPlaced ?? [];
1201
+ if (inBandPlaced.length > 0) {
1202
+ const names = inBandPlaced
1203
+ .map((o) => `${o.id} ${o.type} @${formatCurrency(o.price)}`)
1204
+ .join(', ');
1205
+ lines.push(` ${colors.sell}⚠️ Spread band occupied:${colors.reset} ` +
1206
+ `${inBandPlaced.length} live order(s) inside the ${analysis.gapBand?.gapSlots ?? '?'}-slot band ` +
1207
+ `(${names}) — real spread is narrower than target; GAP-EVAC must evacuate them`);
1208
+ }
1139
1209
  // Active orders comparison
1140
1210
  if (analysis.hasConfig && analysis.coreOrdersTarget) {
1141
1211
  const buyTarget = analysis.coreOrdersTarget.buy;
@@ -1420,14 +1490,15 @@ function generateHtmlReport(analyses) {
1420
1490
  const outPath = path.join(PATHS.ANALYSIS.CHARTS_DIR, 'order-analysis.html');
1421
1491
  fs.mkdirSync(PATHS.ANALYSIS.CHARTS_DIR, { recursive: true });
1422
1492
  fs.writeFileSync(outPath, html, 'utf-8');
1423
- console.log(`\n📄 Order Analysis saved. Open report: (${toFileUrl(outPath)})`);
1493
+ console.log(savedLine(CLI_TAGS.orders, 'Order Analysis', toFileUrl(outPath), 'report'));
1424
1494
  }
1425
1495
  function main() {
1426
1496
  const rawArgs = process.argv.slice(2);
1427
1497
  const exportHtml = rawArgs.includes('--export');
1428
- // Positional (non-flag) args are treated as bot key filters. Example:
1429
- // node dist/scripts/analyze-orders.js <bot>
1430
- // node dist/scripts/analyze-orders.js <bot> --export
1498
+ // Positional (non-flag) args select the analysed grids: a bot name/key, or a
1499
+ // chain account (every bot trading it). Examples:
1500
+ // node dist/scripts/analyze-orders.js <bot|account>
1501
+ // node dist/scripts/analyze-orders.js <bot|account> --export
1431
1502
  const botKeyFilter = rawArgs.find((arg) => !arg.startsWith('-'))?.trim().toLowerCase() || null;
1432
1503
  if (!exportHtml) {
1433
1504
  const targetNote = botKeyFilter ? ` (filter: ${botKeyFilter})` : '';
@@ -1436,21 +1507,30 @@ function main() {
1436
1507
  }
1437
1508
  // Get all order files sorted by modification time (newest first)
1438
1509
  let { files, skippedCandidates } = getOrderFiles();
1439
- // Filter to a single bot when a bot key was requested. Also match the
1440
- // sanitized form of a bot name (e.g. "AAA-BBB" -> "aaa-bbb").
1510
+ // Filter to the requested bot or account. Target matching is the shared
1511
+ // `<bot|account>` rule set (analysis/bot_key_utils): bot key, bot name, or the
1512
+ // chain account the bot trades from (`preferredAccount` name / 1.2.x id).
1513
+ // The file's own key still matches when a snapshot has no bots.json entry.
1441
1514
  if (botKeyFilter) {
1442
- const sanitizedFilter = sanitizeKey(botKeyFilter);
1443
- const matched = files.filter((file) => String(file.botKey).toLowerCase() === botKeyFilter
1444
- || String(file.botKey).toLowerCase() === sanitizedFilter
1445
- || (file.config?.name && sanitizeKey(file.config.name) === sanitizedFilter));
1515
+ const matched = files.filter((file) => {
1516
+ const config = file.config ?? null;
1517
+ return matchBotEntryTarget(config, botKeyFilter, file.botKey) !== null
1518
+ || matchBotAccountTarget(config, botKeyFilter);
1519
+ });
1446
1520
  if (matched.length === 0) {
1447
1521
  if (exportHtml) {
1448
1522
  generateHtmlReport([]);
1449
1523
  }
1450
1524
  else {
1451
- console.log(`${colors.sell}No order grid found for bot key '${botKeyFilter}'.${colors.reset}`);
1525
+ console.log(`${colors.sell}No order grid found for '${botKeyFilter}'.${colors.reset}`);
1452
1526
  console.log('Available bots:');
1453
- files.forEach((file) => console.log(` - ${file.botKey}`));
1527
+ files.forEach((file) => {
1528
+ const config = file.config ?? null;
1529
+ const name = config?.name ? String(config.name) : '';
1530
+ const nameSuffix = name && name.toLowerCase() !== String(file.botKey).toLowerCase() ? ` (${name})` : '';
1531
+ const account = config?.preferredAccount ? ` (account: ${String(config.preferredAccount)})` : '';
1532
+ console.log(` - ${file.botKey}${nameSuffix}${account}`);
1533
+ });
1454
1534
  }
1455
1535
  process.exit(0);
1456
1536
  }
@@ -0,0 +1,26 @@
1
+ #!/usr/bin/env node
2
+ type AssetKind = 'bts' | 'token';
3
+ interface AssetConfig {
4
+ /** Distribution analyzer to run, or null when no target was given. */
5
+ kind: AssetKind | null;
6
+ /** Token symbol or asset id (token kind only). */
7
+ asset: string | null;
8
+ /** Flags forwarded verbatim to the analyzer. */
9
+ scriptArgs: string[];
10
+ help: boolean;
11
+ }
12
+ declare const CORE_ASSET_ID = "1.3.0";
13
+ declare const ANALYZERS: Record<AssetKind, {
14
+ script: string;
15
+ label: string;
16
+ }>;
17
+ /**
18
+ * Split `<target> <flags...>` into the analyzer identity plus the untouched
19
+ * flag list. `bts` (and the core asset id) route to the core-asset analyzer;
20
+ * anything else is an issued-asset symbol/id. Flags are validated per target so
21
+ * a `bts`-only option cannot be silently accepted (and ignored) by the token
22
+ * analyzer, or vice versa.
23
+ */
24
+ declare function parseArgs(argv: string[]): AssetConfig;
25
+ export { parseArgs, ANALYZERS, CORE_ASSET_ID };
26
+ //# sourceMappingURL=asset.d.ts.map