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
@@ -0,0 +1,336 @@
1
+ #!/usr/bin/env node
2
+ 'use strict';
3
+ /**
4
+ * LIQUIDITY DEPTH CHART
5
+ *
6
+ * Blends one asset pair's live limit-order book with its constant-product AMM
7
+ * pool into a single cumulative-depth chart (PoolTool-style), rendered with the
8
+ * vendored uPlot runtime. Read-only: the tool opens an ephemeral chain
9
+ * connection and never touches a running bot's client state.
10
+ *
11
+ * Usage:
12
+ * node dist/analysis/analyze_liquidity.js --pair TOKENA/TOKENB
13
+ * node dist/analysis/analyze_liquidity.js --base TOKENA --quote TOKENB
14
+ * node dist/analysis/analyze_liquidity.js --pool 1.19.133
15
+ * node dist/analysis/analyze_liquidity.js --pool <pool-token-symbol>
16
+ * node dist/analysis/analyze_liquidity.js --pair TOKENA/TOKENB --range 0.25
17
+ * npm run analysis:liquidity -- --pair TOKENA/TOKENB --depth 200
18
+ *
19
+ * Output: analysis/charts/liquidity_<base>_<quote>.html (overridable via --chart)
20
+ */
21
+ import fs from 'node:fs';
22
+ import path from 'node:path';
23
+ import { pathToFileURL } from 'node:url';
24
+ import { PATHS } from '../modules/paths.js';
25
+ import { getErrorMessage } from '../modules/utils/errors.js';
26
+ import { formatCurrency, formatFundsValue, formatPercentLabel } from '../modules/order/format.js';
27
+ import { muteChainLogs } from '../modules/utils/chain_logs.js';
28
+ import { withReadOnlyClient } from './chain_pool.js';
29
+ import { computeBookStats, computePoolPrice, resolvePriceWindow, buildDepthSeries, DEFAULT_STEPS, } from './liquidity/liquidity_depth_model.js';
30
+ import { resolveAsset, fetchOrderBook, fetchPools, resolvePool, selectPool } from './liquidity/liquidity_chain.js';
31
+ import { poolAssetIds } from '../modules/liquidity_pool_ref.js';
32
+ import { generateLiquidityHTML } from './liquidity/liquidity_chart_generator.js';
33
+ import { writeChartFile, toFileUrl } from './chart_utils.js';
34
+ import { CLI_TAGS, savedLine } from '../modules/cli_progress.js';
35
+ const DEFAULT_DEPTH = 300;
36
+ const DEFAULT_RANGE = 0.5;
37
+ function usage() {
38
+ return [
39
+ 'Liquidity depth chart (order book + AMM pool, uPlot)',
40
+ '',
41
+ 'Usage: node dist/analysis/analyze_liquidity.js [options]',
42
+ '',
43
+ 'Options:',
44
+ ' --base <symbol|id> base asset (required unless --pair or --pool is used)',
45
+ ' --quote <symbol|id> quote asset (required unless --pair or --pool is used)',
46
+ ' --pair <base>/<quote> shorthand for --base + --quote',
47
+ ' --pool <ref> one pool: id (133 / 1.19.133) or its pool token symbol;',
48
+ ' both legs are derived from it when --base/--quote are omitted',
49
+ ` --depth <n> order-book levels per side (default ${DEFAULT_DEPTH}; get_limit_orders cap is commonly 300)`,
50
+ ` --range <f> price window half-width as a fraction (default ${DEFAULT_RANGE} => +-50%)`,
51
+ ` --steps <n> price samples across the window (default ${DEFAULT_STEPS})`,
52
+ ' --chart <path> HTML output path',
53
+ ' --json <path> optional JSON dump of the sampled depth series',
54
+ ' --quiet suppress the console summary',
55
+ ' --help show this help',
56
+ '',
57
+ 'Conventions: price is quote per base (e.g. QUOTE per BASE); depth is',
58
+ 'cumulative quote liquidity (QUOTE) at or better than that price. Pool',
59
+ 'depth is net of the AMM taker fee, so the pool bid/ask curves are',
60
+ 'separated by the fee-band spread a taker has to cross.',
61
+ ].join('\n');
62
+ }
63
+ function parsePositiveNumber(raw, flag) {
64
+ const value = Number(raw);
65
+ if (!Number.isFinite(value) || value <= 0)
66
+ throw new Error(`${flag} expects a positive number`);
67
+ return value;
68
+ }
69
+ function parseArgs(argv) {
70
+ const config = {
71
+ base: '',
72
+ quote: '',
73
+ poolId: null,
74
+ depth: DEFAULT_DEPTH,
75
+ range: DEFAULT_RANGE,
76
+ steps: DEFAULT_STEPS,
77
+ chartFile: null,
78
+ jsonFile: null,
79
+ quiet: false,
80
+ help: false,
81
+ };
82
+ const positional = [];
83
+ for (let i = 0; i < argv.length; i++) {
84
+ const arg = argv[i];
85
+ if (arg === '--help' || arg === '-h')
86
+ config.help = true;
87
+ else if (arg === '--quiet')
88
+ config.quiet = true;
89
+ else if (arg === '--base')
90
+ config.base = argv[++i];
91
+ else if (arg === '--quote')
92
+ config.quote = argv[++i];
93
+ else if (arg === '--pair') {
94
+ const [base, quote] = String(argv[++i] ?? '').split(/[/:]/);
95
+ if (!base || !quote)
96
+ throw new Error('--pair expects <base>/<quote>');
97
+ config.base = base;
98
+ config.quote = quote;
99
+ }
100
+ else if (arg === '--pool') {
101
+ // A missing value must not silently fall back to "no pool".
102
+ const ref = argv[++i];
103
+ if (!ref || ref.startsWith('--'))
104
+ throw new Error('--pool expects <133|1.19.133|POOLTOKEN>');
105
+ config.poolId = ref;
106
+ }
107
+ else if (arg === '--depth')
108
+ config.depth = Math.max(1, Math.floor(parsePositiveNumber(argv[++i], '--depth')));
109
+ else if (arg === '--range')
110
+ config.range = parsePositiveNumber(argv[++i], '--range');
111
+ else if (arg === '--steps')
112
+ config.steps = Math.max(2, Math.floor(parsePositiveNumber(argv[++i], '--steps')));
113
+ else if (arg === '--chart')
114
+ config.chartFile = argv[++i] ?? null;
115
+ else if (arg === '--json')
116
+ config.jsonFile = argv[++i] ?? null;
117
+ else if (arg.startsWith('--'))
118
+ throw new Error(`Unknown option: ${arg}`);
119
+ else
120
+ positional.push(arg);
121
+ }
122
+ if (positional.length > 0)
123
+ config.base = positional[0];
124
+ if (positional.length > 1)
125
+ config.quote = positional[1];
126
+ if (positional.length > 2)
127
+ throw new Error('Too many positional arguments (expected base quote)');
128
+ if (config.range >= 0.95)
129
+ throw new Error('--range must be below 0.95');
130
+ // `--help` alone must print the usage (not fail target validation).
131
+ if (config.help)
132
+ return config;
133
+ // A pool reference carries both legs, so `--pool` alone is a valid target —
134
+ // but half a pair next to it is ambiguous (which leg would win?).
135
+ const hasBase = Boolean(config.base);
136
+ const hasQuote = Boolean(config.quote);
137
+ if (config.poolId && hasBase !== hasQuote) {
138
+ throw new Error('Pass both --base and --quote, or neither when using --pool');
139
+ }
140
+ if (!config.poolId && (!hasBase || !hasQuote)) {
141
+ throw new Error('Both base and quote assets are required (use --pair A/B, --base + --quote, or --pool <133|1.19.133|POOLTOKEN>)');
142
+ }
143
+ return config;
144
+ }
145
+ function sanitizeFilePart(value) {
146
+ return String(value || 'asset').replace(/[^A-Za-z0-9._-]+/g, '_');
147
+ }
148
+ function defaultChartPath(base, quote) {
149
+ return path.join(PATHS.ANALYSIS.CHARTS_DIR, `liquidity_${sanitizeFilePart(base.symbol)}_${sanitizeFilePart(quote.symbol)}.html`);
150
+ }
151
+ function pickWindowCenter(pool, sides) {
152
+ const poolPrice = computePoolPrice(pool);
153
+ if (poolPrice != null)
154
+ return poolPrice;
155
+ const stats = computeBookStats(sides);
156
+ if (stats.mid != null && stats.mid > 0)
157
+ return stats.mid;
158
+ const all = [...sides.bids, ...sides.asks];
159
+ if (all.length > 0) {
160
+ const sum = all.reduce((acc, o) => acc + o.price, 0);
161
+ return sum / all.length;
162
+ }
163
+ throw new Error('No order-book levels and no pool: nothing to chart for this pair');
164
+ }
165
+ async function loadSnapshot(config) {
166
+ return withReadOnlyClient(async (client) => {
167
+ let base;
168
+ let quote;
169
+ let poolId = null;
170
+ if (config.poolId) {
171
+ // Pool id or pool token: the pool object carries both legs, so it is
172
+ // resolved first and supplies base/quote when they were omitted.
173
+ const rawPool = await resolvePool(client, config.poolId);
174
+ poolId = String(rawPool.id);
175
+ const [assetA, assetB] = poolAssetIds(rawPool);
176
+ if (!assetA || !assetB)
177
+ throw new Error(`Liquidity pool ${poolId} reports no asset pair`);
178
+ if (config.base && config.quote) {
179
+ base = await resolveAsset(client, config.base);
180
+ quote = await resolveAsset(client, config.quote);
181
+ const wanted = new Set([base.id, quote.id]);
182
+ if (base.id === quote.id || !wanted.has(assetA) || !wanted.has(assetB)) {
183
+ const [poolBase, poolQuote] = await Promise.all([
184
+ resolveAsset(client, assetA),
185
+ resolveAsset(client, assetB),
186
+ ]);
187
+ throw new Error(`Liquidity pool ${poolId} holds ${poolBase.symbol}/${poolQuote.symbol}, not ${base.symbol}/${quote.symbol}`);
188
+ }
189
+ }
190
+ else {
191
+ base = await resolveAsset(client, assetA);
192
+ quote = await resolveAsset(client, assetB);
193
+ }
194
+ }
195
+ else {
196
+ base = await resolveAsset(client, config.base);
197
+ quote = await resolveAsset(client, config.quote);
198
+ }
199
+ if (base.id === quote.id)
200
+ throw new Error('Base and quote assets must differ');
201
+ const [sides, pools] = await Promise.all([
202
+ fetchOrderBook(client, base, quote, config.depth),
203
+ fetchPools(client, base.id, quote.id),
204
+ ]);
205
+ const pool = selectPool(pools, base, quote, poolId);
206
+ if (poolId && !pool) {
207
+ throw new Error(`Pool ${poolId} was not found for ${base.symbol}/${quote.symbol}`);
208
+ }
209
+ if (sides.bids.length === 0 && sides.asks.length === 0 && !pool) {
210
+ throw new Error(`No order-book levels and no AMM pool for ${base.symbol}/${quote.symbol}`);
211
+ }
212
+ const center = pickWindowCenter(pool, sides);
213
+ const window = resolvePriceWindow(center, config.range);
214
+ return { base, quote, pool, pools, sides, center, window };
215
+ });
216
+ }
217
+ function nearestIndex(prices, target) {
218
+ let lo = 0, hi = prices.length - 1;
219
+ while (lo < hi) {
220
+ const mid = (lo + hi) >> 1;
221
+ if (prices[mid] < target)
222
+ lo = mid + 1;
223
+ else
224
+ hi = mid;
225
+ }
226
+ if (lo > 0 && Math.abs(prices[lo - 1] - target) <= Math.abs(prices[lo] - target))
227
+ return lo - 1;
228
+ return lo;
229
+ }
230
+ function printSummary(snapshot, seriesResult, chartFile, config) {
231
+ const { base, quote, pool, sides, window } = snapshot;
232
+ const stats = computeBookStats(sides);
233
+ const poolPrice = seriesResult.poolPrice;
234
+ const fmtPrice = (v) => (v == null || !Number.isFinite(v) ? '-' : formatCurrency(v));
235
+ const fmtAmount = (v) => (v == null || !Number.isFinite(v) ? '-' : formatFundsValue(v));
236
+ const priceLabel = `${quote.symbol} per ${base.symbol}`;
237
+ console.log(`[Liquidity] ${base.symbol}/${quote.symbol} (price: ${priceLabel}, depth: ${quote.symbol})`);
238
+ if (pool) {
239
+ const feeText = pool.feePercent != null ? ` fee=${formatPercentLabel(pool.feePercent)}` : '';
240
+ console.log(` pool ${pool.id ?? 'unknown'} price=${fmtPrice(poolPrice)}${feeText} reserves=${fmtAmount(pool.baseReserve)} ${base.symbol} / ${fmtAmount(pool.quoteReserve)} ${quote.symbol}`);
241
+ // Fee-adjusted edges: the pool curves stop there, so the gap between
242
+ // them is the AMM spread a taker has to cross before the curve starts.
243
+ const bidEdge = seriesResult.poolBidPrice;
244
+ const askEdge = seriesResult.poolAskPrice;
245
+ if (bidEdge != null && askEdge != null) {
246
+ const feeSpread = ((askEdge - bidEdge) / askEdge) * 100;
247
+ console.log(` pool edge bid=${fmtPrice(bidEdge)} ask=${fmtPrice(askEdge)} spread=${formatPercentLabel(feeSpread)} (fee-adjusted, net of taker fee)`);
248
+ }
249
+ }
250
+ else {
251
+ console.log(' pool none');
252
+ }
253
+ console.log(` book ${stats.bidOrders} bids / ${stats.askOrders} asks best bid=${fmtPrice(stats.bestBid)} best ask=${fmtPrice(stats.bestAsk)} mid=${fmtPrice(stats.mid)} spread=${stats.spreadPercent != null ? formatPercentLabel(stats.spreadPercent) : '-'}`);
254
+ console.log(` window ${fmtPrice(window.min)} .. ${fmtPrice(window.max)} (${seriesResult.priceCount} samples, range=${config.range})`);
255
+ // The sampled series is wider than the displayed window so the inverted
256
+ // (1/p) view can stay centered; report depth at the actual window edges.
257
+ const first = nearestIndex(seriesResult.prices, window.min);
258
+ const last = nearestIndex(seriesResult.prices, window.max);
259
+ console.log(` depth at window edges book: bids=${fmtAmount(seriesResult.bookBid[first])} / asks=${fmtAmount(seriesResult.bookAsk[last])} ${quote.symbol}`);
260
+ console.log(` pool: bids=${fmtAmount(seriesResult.poolBid[first])} / asks=${fmtAmount(seriesResult.poolAsk[last])} ${quote.symbol}`);
261
+ console.log(savedLine(CLI_TAGS.liquidity, 'Chart', toFileUrl(chartFile)));
262
+ }
263
+ async function main() {
264
+ // Drop [Transport]/[NodeManager]/[bitshares_client] connection chatter;
265
+ // real errors still go to console.error.
266
+ muteChainLogs();
267
+ let config;
268
+ try {
269
+ config = parseArgs(process.argv.slice(2));
270
+ }
271
+ catch (err) {
272
+ console.error(`[Liquidity] ${getErrorMessage(err)}`);
273
+ console.error(usage());
274
+ process.exitCode = 1;
275
+ return;
276
+ }
277
+ if (config.help) {
278
+ console.log(usage());
279
+ return;
280
+ }
281
+ try {
282
+ if (!config.quiet)
283
+ console.log('[Liquidity] Loading order book and pool from chain...');
284
+ const snapshot = await loadSnapshot(config);
285
+ const stats = computeBookStats(snapshot.sides);
286
+ // Sample beyond the displayed high-price edge so the inverted view can
287
+ // use a symmetric window around 1/p0. p0/(1-range) maps exactly to the
288
+ // reciprocal window's low-price endpoint q0*(1-range).
289
+ const sampleWindow = {
290
+ min: snapshot.window.min,
291
+ max: Math.max(snapshot.window.max, snapshot.center / (1 - config.range)),
292
+ };
293
+ const expansion = (sampleWindow.max - sampleWindow.min) / (snapshot.window.max - snapshot.window.min);
294
+ const seriesResult = buildDepthSeries({
295
+ bids: snapshot.sides.bids,
296
+ asks: snapshot.sides.asks,
297
+ pool: snapshot.pool,
298
+ window: sampleWindow,
299
+ steps: Math.max(config.steps, Math.ceil(config.steps * expansion)),
300
+ });
301
+ const html = generateLiquidityHTML({
302
+ base: snapshot.base,
303
+ quote: snapshot.quote,
304
+ pool: snapshot.pool,
305
+ book: stats,
306
+ series: seriesResult,
307
+ window: snapshot.window,
308
+ });
309
+ const chartFile = config.chartFile || defaultChartPath(snapshot.base, snapshot.quote);
310
+ writeChartFile(chartFile, html);
311
+ if (config.jsonFile) {
312
+ const dump = {
313
+ generatedAt: new Date().toISOString(),
314
+ base: snapshot.base,
315
+ quote: snapshot.quote,
316
+ pool: snapshot.pool,
317
+ book: stats,
318
+ window: snapshot.window,
319
+ series: seriesResult,
320
+ };
321
+ fs.mkdirSync(path.dirname(config.jsonFile), { recursive: true });
322
+ fs.writeFileSync(config.jsonFile, JSON.stringify(dump, null, 2), 'utf8');
323
+ }
324
+ if (!config.quiet)
325
+ printSummary(snapshot, seriesResult, chartFile, config);
326
+ }
327
+ catch (err) {
328
+ console.error(`[Liquidity] ${getErrorMessage(err)}`);
329
+ process.exitCode = 1;
330
+ }
331
+ }
332
+ const invoked = process.argv[1] && import.meta.url === pathToFileURL(process.argv[1]).href;
333
+ if (invoked)
334
+ void main();
335
+ export { parseArgs };
336
+ //# sourceMappingURL=analyze_liquidity.js.map
@@ -25,7 +25,8 @@ import { HurstAnalyzer } from './trend_detection/hurst_analyzer.js';
25
25
  import { PermutationEntropyAnalyzer } from './trend_detection/permutation_entropy_analyzer.js';
26
26
  import { generateRegimeHTML } from './trend_detection/regime_chart_generator.js';
27
27
  import { calculateAMA } from '../market_adapter/core/strategies/ama.js';
28
- import { writeChartFile } from './chart_utils.js';
28
+ import { writeChartFile, toFileUrl } from './chart_utils.js';
29
+ import { CLI_TAGS, savedLine } from '../modules/cli_progress.js';
29
30
  import { getCandleClose } from './math_utils.js';
30
31
  import { resolveSource, listAvailableBots } from './resolve_source.js';
31
32
  import { baseAnalysisConfig, consumeCommonAnalysisArg } from './analyze_args.js';
@@ -120,7 +121,7 @@ async function main() {
120
121
  }, 'Regime Analysis \u2014 Hurst \u00b7 Permutation Entropy');
121
122
  writeChartFile(config.chartFile, html);
122
123
  if (!config.quiet)
123
- console.log(`[Regime] \u2713 Chart saved to ${config.chartFile}`);
124
+ console.log(savedLine(CLI_TAGS.regime, 'Chart', toFileUrl(config.chartFile)));
124
125
  }
125
126
  catch (err) {
126
127
  console.error(`[Regime] Error: ${getErrorMessage(err)}`);
@@ -22,7 +22,8 @@ import { HurstAnalyzer, classifyHurst } from './trend_detection/hurst_analyzer.j
22
22
  import { PermutationEntropyAnalyzer } from './trend_detection/permutation_entropy_analyzer.js';
23
23
  import { MARKET_ADAPTER } from '../modules/constants.js';
24
24
  import { PATHS } from '../modules/paths.js';
25
- import { writeChartFile } from './chart_utils.js';
25
+ import { writeChartFile, toFileUrl } from './chart_utils.js';
26
+ import { CLI_TAGS, savedLine } from '../modules/cli_progress.js';
26
27
  import { getCandleClose } from './math_utils.js';
27
28
  import { roundTo } from '../modules/order/utils/math.js';
28
29
  import { resolveSource, listAvailableBots } from './resolve_source.js';
@@ -402,7 +403,7 @@ async function main() {
402
403
  const html = generateHeatmapHTML(results, HURST_WINDOWS, PE_WINDOWS);
403
404
  writeChartFile(config.chartFile, html);
404
405
  if (!config.quiet)
405
- console.log(`[RegimeWindows] ✓ Chart saved to ${config.chartFile}`);
406
+ console.log(savedLine(CLI_TAGS.regimeWindows, 'Chart', toFileUrl(config.chartFile)));
406
407
  }
407
408
  catch (err) {
408
409
  console.error(`[RegimeWindows] Error: ${getErrorMessage(err)}`);
@@ -29,7 +29,8 @@ import { generateHTML } from './trend_detection/volatility_chart_generator.js';
29
29
  import { MARKET_ADAPTER } from '../modules/constants.js';
30
30
  import { PATHS } from '../modules/paths.js';
31
31
  import { getCandleClose } from './math_utils.js';
32
- import { writeChartFile } from './chart_utils.js';
32
+ import { writeChartFile, toFileUrl } from './chart_utils.js';
33
+ import { CLI_TAGS, savedLine } from '../modules/cli_progress.js';
33
34
  import { resolveSource, listAvailableBots } from './resolve_source.js';
34
35
  import { baseAnalysisConfig, consumeCommonAnalysisArg } from './analyze_args.js';
35
36
  const DEFAULT_ATR_PERIOD = MARKET_ADAPTER.DYNAMIC_WEIGHT_ATR_PERIOD_DEFAULT;
@@ -144,7 +145,7 @@ async function main() {
144
145
  }, 'ATR Volatility Research');
145
146
  writeChartFile(config.chartFile, html);
146
147
  if (!config.quiet)
147
- console.log(`[Volatility] ✓ Chart saved to ${config.chartFile}`);
148
+ console.log(savedLine(CLI_TAGS.volatility, 'Chart', toFileUrl(config.chartFile)));
148
149
  }
149
150
  catch (err) {
150
151
  console.error(`[Volatility] Error: ${getErrorMessage(err)}`);
@@ -30,6 +30,12 @@ declare function persistBotAccountId(botKey: unknown, accountId: string, filePat
30
30
  * never silently reuse a stale ID.
31
31
  */
32
32
  declare function getStoredBotAccountId(botKey: unknown, expectedRef?: string | null, filePath?: string): string | null;
33
+ /**
34
+ * Chain account id (`1.2.x`) test — the single spelling rule for account ids.
35
+ * Analysis tools used to carry a private copy of this regex (`account_resolver`,
36
+ * `trade_profitability`, `fills_cache`, `resolve_bot_accounts`).
37
+ */
38
+ declare function isAccountIdRef(ref: unknown): boolean;
33
39
  /**
34
40
  * Find the bot entry whose preferredAccount matches a raw account reference
35
41
  * (case-insensitive). Used by tools that accept a bare account name to locate
@@ -40,7 +46,44 @@ declare function findBotKeyByAccountRef(ref: unknown, filePath?: string): {
40
46
  botKey: string;
41
47
  meta: BotEntry;
42
48
  } | null;
49
+ /**
50
+ * Which spelling of a `<bot|account>` CLI target matched a bot entry.
51
+ * `name`/`key` identify one bot; `account` identifies the chain account and
52
+ * therefore every entry that trades from it.
53
+ */
54
+ type BotTargetKind = 'name' | 'key' | 'account';
55
+ interface BotTargetMatch {
56
+ botKey: string;
57
+ meta: BotEntry;
58
+ matchedBy: BotTargetKind;
59
+ }
60
+ /**
61
+ * Match one bot entry against a `<bot>` target: display name (the same
62
+ * case/space-insensitive rule `resolveBotKey` uses) or bot key. `botKey` is a
63
+ * parameter because callers that key entries by a stored file name
64
+ * (`analyze-orders` reads `profiles/orders/<botKey>.json`) know the key without
65
+ * an entry, and a key must still match when the config entry is missing.
66
+ */
67
+ declare function matchBotEntryTarget(entry: BotEntry | null | undefined, target: unknown, botKey?: unknown): BotTargetKind | null;
68
+ /**
69
+ * Does the target name the chain account behind this bot? Covers both stored
70
+ * spellings: `preferredAccount` (name or typed 1.2.x id) and the `accountId`
71
+ * `account_resolver.ts` stamps next to it. Matched case-insensitively — chain
72
+ * account names are lowercase, but operators type them any way they like.
73
+ */
74
+ declare function matchBotAccountTarget(entry: BotEntry | null | undefined, target: unknown): boolean;
75
+ /**
76
+ * Canonical `<bot|account>` target resolution: every entry matching the target
77
+ * as a bot name, a bot key, or the chain account it trades from. This is the
78
+ * one rule set behind `dexbot credit`, `dexbot order` and the chart commands —
79
+ * they previously each carried a slightly different copy (some name-only, some
80
+ * key-only, `credit` a third variant). Each caller picks the spellings it
81
+ * accepts from `matchedBy`: a chart command takes the first `name`/`key` match
82
+ * (an account is ambiguous there), while `credit` reports every match.
83
+ */
84
+ declare function matchBotTargetIn(entries: Array<BotEntry | null | undefined> | null | undefined, target: unknown): BotTargetMatch[];
43
85
  declare function resolveAmaConfig(botKey: unknown): AmaConfig;
44
86
  declare function resolveAmaKey(botKey: unknown): string;
45
- export { loadBotSettings, sanitizeKey, computeBotKey, resolveBotKey, candleFileForBot, resolveCandleFile, loadBotMeta, getStoredBotAccountId, findBotKeyByAccountRef, persistBotAccountId, resolveAmaConfig, resolveAmaKey };
87
+ export { loadBotSettings, sanitizeKey, computeBotKey, resolveBotKey, candleFileForBot, resolveCandleFile, loadBotMeta, getStoredBotAccountId, findBotKeyByAccountRef, persistBotAccountId, resolveAmaConfig, resolveAmaKey, isAccountIdRef, matchBotEntryTarget, matchBotAccountTarget, matchBotTargetIn };
88
+ export type { BotTargetKind, BotTargetMatch };
46
89
  //# sourceMappingURL=bot_key_utils.d.ts.map
@@ -7,7 +7,7 @@ const { readJSON, writeJSON } = getStorage();
7
7
  import { parseJsonWithComments } from '../modules/order/utils/system.js';
8
8
  import { MARKET_ADAPTER } from '../modules/constants.js';
9
9
  import { loadMarketProfiles } from './tradingview/tradingview_uplot_chart_generator.js';
10
- import { sanitizeKey } from '../modules/utils/sanitize_key.js';
10
+ import { isSameBotName, sanitizeKey } from '../modules/utils/sanitize_key.js';
11
11
  import { isSameAssetSymbol, canonicalizeBotAssetSymbols } from '../modules/utils/asset_symbols.js';
12
12
  // Single source of truth for bot keys (named AND unnamed bots) so analysis
13
13
  // tools resolve the same files production writes.
@@ -378,7 +378,7 @@ function patchAccountIdInRaw(filePath, entryIndex, accountId) {
378
378
  * the file was updated.
379
379
  */
380
380
  function persistBotAccountId(botKey, accountId, filePath = PATHS.PROFILES.BOTS_JSON) {
381
- if (!botKey || !/^1\.2\.\d+$/.test(String(accountId)))
381
+ if (!botKey || !isAccountIdRef(accountId))
382
382
  return false;
383
383
  let settings = null;
384
384
  try {
@@ -427,13 +427,21 @@ function getStoredBotAccountId(botKey, expectedRef, filePath = PATHS.PROFILES.BO
427
427
  if (!meta)
428
428
  return null;
429
429
  const accountIdRaw = String(meta.accountId ?? '');
430
- const stored = /^1\.2\.\d+$/.test(accountIdRaw) ? accountIdRaw : null;
430
+ const stored = isAccountIdRef(accountIdRaw) ? accountIdRaw : null;
431
431
  if (!stored)
432
432
  return null;
433
433
  if (expectedRef != null && String(meta.preferredAccount ?? '').toLowerCase() !== String(expectedRef).toLowerCase())
434
434
  return null;
435
435
  return stored;
436
436
  }
437
+ /**
438
+ * Chain account id (`1.2.x`) test — the single spelling rule for account ids.
439
+ * Analysis tools used to carry a private copy of this regex (`account_resolver`,
440
+ * `trade_profitability`, `fills_cache`, `resolve_bot_accounts`).
441
+ */
442
+ function isAccountIdRef(ref) {
443
+ return /^1\.2\.\d+$/.test(String(ref ?? '').trim());
444
+ }
437
445
  /**
438
446
  * Find the bot entry whose preferredAccount matches a raw account reference
439
447
  * (case-insensitive). Used by tools that accept a bare account name to locate
@@ -441,7 +449,7 @@ function getStoredBotAccountId(botKey, expectedRef, filePath = PATHS.PROFILES.BO
441
449
  * or when no bot claims the name.
442
450
  */
443
451
  function findBotKeyByAccountRef(ref, filePath = PATHS.PROFILES.BOTS_JSON) {
444
- if (!ref || /^1\.2\.\d+$/.test(String(ref)))
452
+ if (!ref || isAccountIdRef(ref))
445
453
  return null;
446
454
  let settings = null;
447
455
  try {
@@ -451,15 +459,76 @@ function findBotKeyByAccountRef(ref, filePath = PATHS.PROFILES.BOTS_JSON) {
451
459
  return null;
452
460
  }
453
461
  const entries = Array.isArray(settings?.bots) ? settings.bots : [];
454
- const want = String(ref).toLowerCase();
455
462
  for (let i = 0; i < entries.length; i++) {
456
463
  const entry = entries[i];
457
- if (entry && String(entry.preferredAccount ?? '').toLowerCase() === want) {
464
+ if (entry && matchBotAccountTarget(entry, ref)) {
458
465
  return { botKey: computeBotKey(entry, i), meta: entry };
459
466
  }
460
467
  }
461
468
  return null;
462
469
  }
470
+ /** Trimmed target or '' — the positional is user input, so never assume a string. */
471
+ function normalizeBotTarget(target) {
472
+ return typeof target === 'string' ? target.trim() : '';
473
+ }
474
+ /**
475
+ * Match one bot entry against a `<bot>` target: display name (the same
476
+ * case/space-insensitive rule `resolveBotKey` uses) or bot key. `botKey` is a
477
+ * parameter because callers that key entries by a stored file name
478
+ * (`analyze-orders` reads `profiles/orders/<botKey>.json`) know the key without
479
+ * an entry, and a key must still match when the config entry is missing.
480
+ */
481
+ function matchBotEntryTarget(entry, target, botKey) {
482
+ const raw = normalizeBotTarget(target);
483
+ if (!raw)
484
+ return null;
485
+ if (entry && isSameBotName(entry.name, raw))
486
+ return 'name';
487
+ const key = String(botKey ?? '').trim();
488
+ if (!key)
489
+ return null;
490
+ return key.toLowerCase() === raw.toLowerCase() || sanitizeKey(key) === sanitizeKey(raw) ? 'key' : null;
491
+ }
492
+ /**
493
+ * Does the target name the chain account behind this bot? Covers both stored
494
+ * spellings: `preferredAccount` (name or typed 1.2.x id) and the `accountId`
495
+ * `account_resolver.ts` stamps next to it. Matched case-insensitively — chain
496
+ * account names are lowercase, but operators type them any way they like.
497
+ */
498
+ function matchBotAccountTarget(entry, target) {
499
+ const raw = normalizeBotTarget(target).toLowerCase();
500
+ if (!entry || !raw)
501
+ return false;
502
+ const account = String(entry.preferredAccount ?? '').trim().toLowerCase();
503
+ if (account && account === raw)
504
+ return true;
505
+ const accountId = String(entry.accountId ?? '').trim().toLowerCase();
506
+ return Boolean(accountId) && accountId === raw;
507
+ }
508
+ /**
509
+ * Canonical `<bot|account>` target resolution: every entry matching the target
510
+ * as a bot name, a bot key, or the chain account it trades from. This is the
511
+ * one rule set behind `dexbot credit`, `dexbot order` and the chart commands —
512
+ * they previously each carried a slightly different copy (some name-only, some
513
+ * key-only, `credit` a third variant). Each caller picks the spellings it
514
+ * accepts from `matchedBy`: a chart command takes the first `name`/`key` match
515
+ * (an account is ambiguous there), while `credit` reports every match.
516
+ */
517
+ function matchBotTargetIn(entries, target) {
518
+ const out = [];
519
+ const list = Array.isArray(entries) ? entries : [];
520
+ for (let index = 0; index < list.length; index++) {
521
+ const entry = list[index];
522
+ if (!entry)
523
+ continue;
524
+ const botKey = computeBotKey(entry, index);
525
+ const matchedBy = matchBotEntryTarget(entry, target, botKey)
526
+ ?? (matchBotAccountTarget(entry, target) ? 'account' : null);
527
+ if (matchedBy)
528
+ out.push({ botKey, meta: entry, matchedBy });
529
+ }
530
+ return out;
531
+ }
463
532
  function resolveAmaConfig(botKey) {
464
533
  const botMeta = loadBotMeta(botKey);
465
534
  if (!botMeta)
@@ -539,5 +608,5 @@ function resolveAmaKey(botKey) {
539
608
  }
540
609
  return 'AMA3';
541
610
  }
542
- export { loadBotSettings, sanitizeKey, computeBotKey, resolveBotKey, candleFileForBot, resolveCandleFile, loadBotMeta, getStoredBotAccountId, findBotKeyByAccountRef, persistBotAccountId, resolveAmaConfig, resolveAmaKey };
611
+ export { loadBotSettings, sanitizeKey, computeBotKey, resolveBotKey, candleFileForBot, resolveCandleFile, loadBotMeta, getStoredBotAccountId, findBotKeyByAccountRef, persistBotAccountId, resolveAmaConfig, resolveAmaKey, isAccountIdRef, matchBotEntryTarget, matchBotAccountTarget, matchBotTargetIn };
543
612
  //# sourceMappingURL=bot_key_utils.js.map
@@ -26,6 +26,7 @@
26
26
  import path from 'node:path';
27
27
  import { getStorage } from '../modules/storage/index.js';
28
28
  import { PATHS } from '../modules/paths.js';
29
+ import { isAccountIdRef } from './bot_key_utils.js';
29
30
  import { writeJsonAtomic } from '../market_adapter/utils/atomic_write.js';
30
31
  import { shardKeyForTimestamp, shardBoundsForKey, shardKeysForRange, shardPathFor, unionQueriedRanges, compactCoverage, mergeSpans, subtractRanges, } from '../market_adapter/utils/month_shards.js';
31
32
  import { fetchAllFills } from './fills_source.js';
@@ -38,7 +39,7 @@ const MAX_COVERAGE_SPANS = 64;
38
39
  const SHARD_EXT = '.json';
39
40
  function accountFileBase(accountId) {
40
41
  const s = String(accountId ?? '').trim();
41
- if (/^1\.2\.\d+$/.test(s))
42
+ if (isAccountIdRef(s))
42
43
  return s;
43
44
  return s.replace(/[^a-zA-Z0-9._-]+/g, '-').replace(/^-+|-+$/g, '') || 'account';
44
45
  }
@@ -1,4 +1,5 @@
1
1
  #!/usr/bin/env node
2
+ import { isLastFillGuardBlocked } from '../modules/order/utils/system.js';
2
3
  import { FillRecord } from './fills_source.js';
3
4
  interface TradeFill {
4
5
  time: string;
@@ -27,25 +28,6 @@ interface Violation {
27
28
  /** The pivot itself (BUY must be below / SELL above it). */
28
29
  threshold: number;
29
30
  }
30
- /**
31
- * LAST-FILL-GUARD helper — DIRECTION ONLY relative to the last fill price.
32
- * BUY blocked if price >= pivot
33
- * SELL blocked if price <= pivot
34
- * e.g. pivot 1000 => BUY must be < 1000, SELL must be > 1000
35
- * Cold (pivot null or lastType null) => disabled. Equal price stays blocked
36
- * (a re-place at the just-filled level).
37
- * @param {number} price - Target order price
38
- * @param {string} type - buy/sell
39
- * @param {number|null} lastPrice - Most recent fill price
40
- * @param {string|null} lastType - Most recent fill side (buy/sell)
41
- * @returns {{blocked: boolean, pivot: number|null, halfInc: number, threshold: number|null}}
42
- */
43
- declare function isLastFillGuardBlocked(price: unknown, type: unknown, lastPrice: unknown, lastType: unknown): {
44
- blocked: boolean;
45
- pivot: number | null;
46
- halfInc?: number;
47
- threshold?: number | null;
48
- };
49
31
  declare function classifyFills(fills: FillRecord[]): {
50
32
  trades: TradeFill[];
51
33
  skipped: number;