dexbot 1.6.18 → 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 (89) hide show
  1. package/CHANGELOG.md +26 -0
  2. package/README.md +24 -18
  3. package/analysis/README.md +95 -3
  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/analyze_dynamic_weight.js +2 -1
  8. package/dist/analysis/analyze_kalman.js +3 -2
  9. package/dist/analysis/analyze_liquidity.d.ts +17 -0
  10. package/dist/analysis/analyze_liquidity.js +325 -0
  11. package/dist/analysis/analyze_regime.js +3 -2
  12. package/dist/analysis/analyze_regime_windows.js +3 -2
  13. package/dist/analysis/analyze_volatility.js +3 -2
  14. package/dist/analysis/liquidity/liquidity_chain.d.ts +66 -0
  15. package/dist/analysis/liquidity/liquidity_chain.js +178 -0
  16. package/dist/analysis/liquidity/liquidity_chart_generator.d.ts +19 -0
  17. package/dist/analysis/liquidity/liquidity_chart_generator.js +523 -0
  18. package/dist/analysis/liquidity/liquidity_depth_model.d.ts +141 -0
  19. package/dist/analysis/liquidity/liquidity_depth_model.js +230 -0
  20. package/dist/analysis/liquidity/liquidity_view.d.ts +38 -0
  21. package/dist/analysis/liquidity/liquidity_view.js +55 -0
  22. package/dist/analysis/trade_profitability.js +2 -1
  23. package/dist/analysis/tradingview/analyze_tradingview.js +2 -1
  24. package/dist/dexbot.js +74 -169
  25. package/dist/modules/asset_lookup.d.ts +25 -0
  26. package/dist/modules/asset_lookup.js +75 -0
  27. package/dist/modules/chain_scan.d.ts +64 -0
  28. package/dist/modules/chain_scan.js +80 -0
  29. package/dist/modules/cli_colors.d.ts +5 -0
  30. package/dist/modules/cli_colors.js +7 -0
  31. package/dist/modules/cli_progress.d.ts +51 -0
  32. package/dist/modules/cli_progress.js +113 -0
  33. package/dist/modules/dexbot_cow_runtime.js +14 -4
  34. package/dist/modules/dexbot_fill_runtime.js +20 -0
  35. package/dist/modules/dexbot_maintenance_runtime.js +16 -1
  36. package/dist/modules/launcher/runtime_entry.d.ts +21 -1
  37. package/dist/modules/launcher/runtime_entry.js +36 -1
  38. package/dist/modules/liquidity_pool_ref.d.ts +32 -0
  39. package/dist/modules/liquidity_pool_ref.js +116 -0
  40. package/dist/modules/order/grid.js +9 -2
  41. package/dist/modules/order/grid_reconcile.js +22 -1
  42. package/dist/modules/order/grid_reconcile_internal.js +92 -14
  43. package/dist/modules/order/index.d.ts +15 -1
  44. package/dist/modules/order/manager.d.ts +2 -0
  45. package/dist/modules/order/manager.js +3 -0
  46. package/dist/modules/order/sync_engine.d.ts +20 -0
  47. package/dist/modules/order/sync_engine.js +101 -33
  48. package/dist/modules/order/utils/math.d.ts +18 -1
  49. package/dist/modules/order/utils/math.js +30 -1
  50. package/dist/modules/order/utils/order.d.ts +107 -1
  51. package/dist/modules/order/utils/order.js +298 -1
  52. package/dist/modules/order/utils/system.d.ts +63 -1
  53. package/dist/modules/order/utils/system.js +247 -36
  54. package/dist/modules/order/utils/validate.js +33 -2
  55. package/dist/modules/types.d.ts +5 -0
  56. package/dist/modules/utils/asset_symbols.d.ts +13 -2
  57. package/dist/modules/utils/asset_symbols.js +21 -2
  58. package/dist/scripts/analysis_runner.d.ts +10 -0
  59. package/dist/scripts/analysis_runner.js +33 -0
  60. package/dist/scripts/analyze-orders.js +2 -1
  61. package/dist/scripts/asset.d.ts +26 -0
  62. package/dist/scripts/asset.js +165 -0
  63. package/dist/scripts/bts_distribution.d.ts +1 -0
  64. package/dist/scripts/bts_distribution.js +194 -142
  65. package/dist/scripts/chart_command.d.ts +1 -1
  66. package/dist/scripts/chart_command.js +60 -86
  67. package/dist/scripts/chart_targets.d.ts +18 -0
  68. package/dist/scripts/chart_targets.js +52 -0
  69. package/dist/scripts/dw.js +1 -1
  70. package/dist/scripts/liquid.d.ts +24 -0
  71. package/dist/scripts/liquid.js +134 -0
  72. package/dist/scripts/rich_list.js +12 -16
  73. package/dist/scripts/token_distribution.d.ts +2 -0
  74. package/dist/scripts/token_distribution.js +132 -108
  75. package/dist/scripts/tv.js +1 -1
  76. package/dist/scripts/verify-browser-bundle.js +18 -0
  77. package/docs/COW_INVARIANTS.md +2 -2
  78. package/docs/DEXBOT_COMPARISON.md +6 -6
  79. package/docs/EVOLUTION.md +9 -8
  80. package/docs/FUND_MOVEMENT_AND_ACCOUNTING.md +1 -1
  81. package/docs/GRID_PRICE_INVARIANT.md +4 -1
  82. package/docs/GRID_RECONCILE.md +20 -0
  83. package/docs/LOGGING.md +25 -3
  84. package/docs/ORDER_ENGINE_POST_1.0_RETROSPECTIVE.md +2 -1
  85. package/docs/README.md +1 -1
  86. package/docs/WORKFLOW.md +3 -1
  87. package/modules/README.md +5 -1
  88. package/package.json +3 -1
  89. package/scripts/README.md +23 -7
@@ -0,0 +1,325 @@
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 } 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.',
59
+ ].join('\n');
60
+ }
61
+ function parsePositiveNumber(raw, flag) {
62
+ const value = Number(raw);
63
+ if (!Number.isFinite(value) || value <= 0)
64
+ throw new Error(`${flag} expects a positive number`);
65
+ return value;
66
+ }
67
+ function parseArgs(argv) {
68
+ const config = {
69
+ base: '',
70
+ quote: '',
71
+ poolId: null,
72
+ depth: DEFAULT_DEPTH,
73
+ range: DEFAULT_RANGE,
74
+ steps: DEFAULT_STEPS,
75
+ chartFile: null,
76
+ jsonFile: null,
77
+ quiet: false,
78
+ help: false,
79
+ };
80
+ const positional = [];
81
+ for (let i = 0; i < argv.length; i++) {
82
+ const arg = argv[i];
83
+ if (arg === '--help' || arg === '-h')
84
+ config.help = true;
85
+ else if (arg === '--quiet')
86
+ config.quiet = true;
87
+ else if (arg === '--base')
88
+ config.base = argv[++i];
89
+ else if (arg === '--quote')
90
+ config.quote = argv[++i];
91
+ else if (arg === '--pair') {
92
+ const [base, quote] = String(argv[++i] ?? '').split(/[/:]/);
93
+ if (!base || !quote)
94
+ throw new Error('--pair expects <base>/<quote>');
95
+ config.base = base;
96
+ config.quote = quote;
97
+ }
98
+ else if (arg === '--pool') {
99
+ // A missing value must not silently fall back to "no pool".
100
+ const ref = argv[++i];
101
+ if (!ref || ref.startsWith('--'))
102
+ throw new Error('--pool expects <133|1.19.133|POOLTOKEN>');
103
+ config.poolId = ref;
104
+ }
105
+ else if (arg === '--depth')
106
+ config.depth = Math.max(1, Math.floor(parsePositiveNumber(argv[++i], '--depth')));
107
+ else if (arg === '--range')
108
+ config.range = parsePositiveNumber(argv[++i], '--range');
109
+ else if (arg === '--steps')
110
+ config.steps = Math.max(2, Math.floor(parsePositiveNumber(argv[++i], '--steps')));
111
+ else if (arg === '--chart')
112
+ config.chartFile = argv[++i] ?? null;
113
+ else if (arg === '--json')
114
+ config.jsonFile = argv[++i] ?? null;
115
+ else if (arg.startsWith('--'))
116
+ throw new Error(`Unknown option: ${arg}`);
117
+ else
118
+ positional.push(arg);
119
+ }
120
+ if (positional.length > 0)
121
+ config.base = positional[0];
122
+ if (positional.length > 1)
123
+ config.quote = positional[1];
124
+ if (positional.length > 2)
125
+ throw new Error('Too many positional arguments (expected base quote)');
126
+ if (config.range >= 0.95)
127
+ throw new Error('--range must be below 0.95');
128
+ // `--help` alone must print the usage (not fail target validation).
129
+ if (config.help)
130
+ return config;
131
+ // A pool reference carries both legs, so `--pool` alone is a valid target —
132
+ // but half a pair next to it is ambiguous (which leg would win?).
133
+ const hasBase = Boolean(config.base);
134
+ const hasQuote = Boolean(config.quote);
135
+ if (config.poolId && hasBase !== hasQuote) {
136
+ throw new Error('Pass both --base and --quote, or neither when using --pool');
137
+ }
138
+ if (!config.poolId && (!hasBase || !hasQuote)) {
139
+ throw new Error('Both base and quote assets are required (use --pair A/B, --base + --quote, or --pool <133|1.19.133|POOLTOKEN>)');
140
+ }
141
+ return config;
142
+ }
143
+ function sanitizeFilePart(value) {
144
+ return String(value || 'asset').replace(/[^A-Za-z0-9._-]+/g, '_');
145
+ }
146
+ function defaultChartPath(base, quote) {
147
+ return path.join(PATHS.ANALYSIS.CHARTS_DIR, `liquidity_${sanitizeFilePart(base.symbol)}_${sanitizeFilePart(quote.symbol)}.html`);
148
+ }
149
+ function pickWindowCenter(pool, sides) {
150
+ const poolPrice = computePoolPrice(pool);
151
+ if (poolPrice != null)
152
+ return poolPrice;
153
+ const stats = computeBookStats(sides);
154
+ if (stats.mid != null && stats.mid > 0)
155
+ return stats.mid;
156
+ const all = [...sides.bids, ...sides.asks];
157
+ if (all.length > 0) {
158
+ const sum = all.reduce((acc, o) => acc + o.price, 0);
159
+ return sum / all.length;
160
+ }
161
+ throw new Error('No order-book levels and no pool: nothing to chart for this pair');
162
+ }
163
+ async function loadSnapshot(config) {
164
+ return withReadOnlyClient(async (client) => {
165
+ let base;
166
+ let quote;
167
+ let poolId = null;
168
+ if (config.poolId) {
169
+ // Pool id or pool token: the pool object carries both legs, so it is
170
+ // resolved first and supplies base/quote when they were omitted.
171
+ const rawPool = await resolvePool(client, config.poolId);
172
+ poolId = String(rawPool.id);
173
+ const [assetA, assetB] = poolAssetIds(rawPool);
174
+ if (!assetA || !assetB)
175
+ throw new Error(`Liquidity pool ${poolId} reports no asset pair`);
176
+ if (config.base && config.quote) {
177
+ base = await resolveAsset(client, config.base);
178
+ quote = await resolveAsset(client, config.quote);
179
+ const wanted = new Set([base.id, quote.id]);
180
+ if (base.id === quote.id || !wanted.has(assetA) || !wanted.has(assetB)) {
181
+ const [poolBase, poolQuote] = await Promise.all([
182
+ resolveAsset(client, assetA),
183
+ resolveAsset(client, assetB),
184
+ ]);
185
+ throw new Error(`Liquidity pool ${poolId} holds ${poolBase.symbol}/${poolQuote.symbol}, not ${base.symbol}/${quote.symbol}`);
186
+ }
187
+ }
188
+ else {
189
+ base = await resolveAsset(client, assetA);
190
+ quote = await resolveAsset(client, assetB);
191
+ }
192
+ }
193
+ else {
194
+ base = await resolveAsset(client, config.base);
195
+ quote = await resolveAsset(client, config.quote);
196
+ }
197
+ if (base.id === quote.id)
198
+ throw new Error('Base and quote assets must differ');
199
+ const [sides, pools] = await Promise.all([
200
+ fetchOrderBook(client, base, quote, config.depth),
201
+ fetchPools(client, base.id, quote.id),
202
+ ]);
203
+ const pool = selectPool(pools, base, quote, poolId);
204
+ if (poolId && !pool) {
205
+ throw new Error(`Pool ${poolId} was not found for ${base.symbol}/${quote.symbol}`);
206
+ }
207
+ if (sides.bids.length === 0 && sides.asks.length === 0 && !pool) {
208
+ throw new Error(`No order-book levels and no AMM pool for ${base.symbol}/${quote.symbol}`);
209
+ }
210
+ const center = pickWindowCenter(pool, sides);
211
+ const window = resolvePriceWindow(center, config.range);
212
+ return { base, quote, pool, pools, sides, center, window };
213
+ });
214
+ }
215
+ function nearestIndex(prices, target) {
216
+ let lo = 0, hi = prices.length - 1;
217
+ while (lo < hi) {
218
+ const mid = (lo + hi) >> 1;
219
+ if (prices[mid] < target)
220
+ lo = mid + 1;
221
+ else
222
+ hi = mid;
223
+ }
224
+ if (lo > 0 && Math.abs(prices[lo - 1] - target) <= Math.abs(prices[lo] - target))
225
+ return lo - 1;
226
+ return lo;
227
+ }
228
+ function printSummary(snapshot, seriesResult, chartFile, config) {
229
+ const { base, quote, pool, sides, window } = snapshot;
230
+ const stats = computeBookStats(sides);
231
+ const poolPrice = seriesResult.poolPrice;
232
+ const fmtPrice = (v) => (v == null || !Number.isFinite(v) ? '-' : formatCurrency(v));
233
+ const fmtAmount = (v) => (v == null || !Number.isFinite(v) ? '-' : formatFundsValue(v));
234
+ const priceLabel = `${quote.symbol} per ${base.symbol}`;
235
+ console.log(`[Liquidity] ${base.symbol}/${quote.symbol} (price: ${priceLabel}, depth: ${quote.symbol})`);
236
+ if (pool) {
237
+ console.log(` pool ${pool.id ?? 'unknown'} price=${fmtPrice(poolPrice)} reserves=${fmtAmount(pool.baseReserve)} ${base.symbol} / ${fmtAmount(pool.quoteReserve)} ${quote.symbol}${pool.feePercent != null ? ` fee=${fmtPrice(pool.feePercent)}%` : ''}`);
238
+ }
239
+ else {
240
+ console.log(' pool none');
241
+ }
242
+ console.log(` book ${stats.bidOrders} bids / ${stats.askOrders} asks best bid=${fmtPrice(stats.bestBid)} best ask=${fmtPrice(stats.bestAsk)} mid=${fmtPrice(stats.mid)} spread=${fmtPrice(stats.spreadPercent)}%`);
243
+ console.log(` window ${fmtPrice(window.min)} .. ${fmtPrice(window.max)} (${seriesResult.priceCount} samples, range=${config.range})`);
244
+ // The sampled series is wider than the displayed window so the inverted
245
+ // (1/p) view can stay centered; report depth at the actual window edges.
246
+ const first = nearestIndex(seriesResult.prices, window.min);
247
+ const last = nearestIndex(seriesResult.prices, window.max);
248
+ console.log(` depth at window edges book: bids=${fmtAmount(seriesResult.bookBid[first])} / asks=${fmtAmount(seriesResult.bookAsk[last])} ${quote.symbol}`);
249
+ console.log(` pool: bids=${fmtAmount(seriesResult.poolBid[first])} / asks=${fmtAmount(seriesResult.poolAsk[last])} ${quote.symbol}`);
250
+ console.log(savedLine(CLI_TAGS.liquidity, 'Chart', toFileUrl(chartFile)));
251
+ }
252
+ async function main() {
253
+ // Drop [Transport]/[NodeManager]/[bitshares_client] connection chatter;
254
+ // real errors still go to console.error.
255
+ muteChainLogs();
256
+ let config;
257
+ try {
258
+ config = parseArgs(process.argv.slice(2));
259
+ }
260
+ catch (err) {
261
+ console.error(`[Liquidity] ${getErrorMessage(err)}`);
262
+ console.error(usage());
263
+ process.exitCode = 1;
264
+ return;
265
+ }
266
+ if (config.help) {
267
+ console.log(usage());
268
+ return;
269
+ }
270
+ try {
271
+ if (!config.quiet)
272
+ console.log('[Liquidity] Loading order book and pool from chain...');
273
+ const snapshot = await loadSnapshot(config);
274
+ const stats = computeBookStats(snapshot.sides);
275
+ // Sample beyond the displayed high-price edge so the inverted view can
276
+ // use a symmetric window around 1/p0. p0/(1-range) maps exactly to the
277
+ // reciprocal window's low-price endpoint q0*(1-range).
278
+ const sampleWindow = {
279
+ min: snapshot.window.min,
280
+ max: Math.max(snapshot.window.max, snapshot.center / (1 - config.range)),
281
+ };
282
+ const expansion = (sampleWindow.max - sampleWindow.min) / (snapshot.window.max - snapshot.window.min);
283
+ const seriesResult = buildDepthSeries({
284
+ bids: snapshot.sides.bids,
285
+ asks: snapshot.sides.asks,
286
+ pool: snapshot.pool,
287
+ window: sampleWindow,
288
+ steps: Math.max(config.steps, Math.ceil(config.steps * expansion)),
289
+ });
290
+ const html = generateLiquidityHTML({
291
+ base: snapshot.base,
292
+ quote: snapshot.quote,
293
+ pool: snapshot.pool,
294
+ book: stats,
295
+ series: seriesResult,
296
+ window: snapshot.window,
297
+ });
298
+ const chartFile = config.chartFile || defaultChartPath(snapshot.base, snapshot.quote);
299
+ writeChartFile(chartFile, html);
300
+ if (config.jsonFile) {
301
+ const dump = {
302
+ generatedAt: new Date().toISOString(),
303
+ base: snapshot.base,
304
+ quote: snapshot.quote,
305
+ pool: snapshot.pool,
306
+ book: stats,
307
+ window: snapshot.window,
308
+ series: seriesResult,
309
+ };
310
+ fs.mkdirSync(path.dirname(config.jsonFile), { recursive: true });
311
+ fs.writeFileSync(config.jsonFile, JSON.stringify(dump, null, 2), 'utf8');
312
+ }
313
+ if (!config.quiet)
314
+ printSummary(snapshot, seriesResult, chartFile, config);
315
+ }
316
+ catch (err) {
317
+ console.error(`[Liquidity] ${getErrorMessage(err)}`);
318
+ process.exitCode = 1;
319
+ }
320
+ }
321
+ const invoked = process.argv[1] && import.meta.url === pathToFileURL(process.argv[1]).href;
322
+ if (invoked)
323
+ void main();
324
+ export { parseArgs };
325
+ //# 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)}`);
@@ -0,0 +1,66 @@
1
+ import type { BookSides, PoolState } from './liquidity_depth_model.js';
2
+ interface ChainDbClient {
3
+ db(method: string, args?: unknown[]): Promise<unknown>;
4
+ }
5
+ interface ChainAsset {
6
+ id: string;
7
+ symbol: string;
8
+ precision: number;
9
+ }
10
+ interface RawLimitOrder {
11
+ id?: string;
12
+ for_sale?: string | number;
13
+ sell_price?: {
14
+ base?: {
15
+ amount?: string | number;
16
+ asset_id?: string;
17
+ };
18
+ quote?: {
19
+ amount?: string | number;
20
+ asset_id?: string;
21
+ };
22
+ };
23
+ }
24
+ interface RawPool {
25
+ id?: string;
26
+ asset_a?: string;
27
+ asset_b?: string;
28
+ asset_ids?: string[];
29
+ balance_a?: string | number;
30
+ balance_b?: string | number;
31
+ share_asset?: string;
32
+ taker_fee_percent?: number;
33
+ }
34
+ declare function resolveAsset(client: ChainDbClient, ref: string): Promise<ChainAsset>;
35
+ /**
36
+ * Decode raw limit orders into real bid/ask sides with display prices
37
+ * (quote per base) and quote/base amounts.
38
+ *
39
+ * `get_order_book` and `get_limit_orders` share the same side convention: an
40
+ * order whose `sell_price.base` is the requested base SELLS the base (real
41
+ * ask); the other side sells the quote (real bid).
42
+ */
43
+ declare function normalizeLimitOrders(orders: unknown, base: ChainAsset, quote: ChainAsset): BookSides;
44
+ /**
45
+ * Fetch the order book, preferring `get_limit_orders` because nodes usually
46
+ * cap `get_order_book` at 50 levels while `get_limit_orders` allows up to
47
+ * ~300 per side. Falls back to `get_order_book` when the wider API is not
48
+ * available. `depth` is per side.
49
+ */
50
+ declare function fetchOrderBook(client: ChainDbClient, base: ChainAsset, quote: ChainAsset, depth: number): Promise<BookSides>;
51
+ declare function fetchPools(client: ChainDbClient, baseId: string, quoteId: string): Promise<RawPool[]>;
52
+ /**
53
+ * Resolve a pool by id (`133` / `1.19.133`) or by its pool token (LP share-asset
54
+ * symbol). Shared with `dexbot tv`/`dw` and the liquidity analyzer's `--pool`.
55
+ */
56
+ declare function resolvePool(client: ChainDbClient, ref: string): Promise<RawPool>;
57
+ /** Decode one raw pool into display reserves (base = asset A, quote = asset B). */
58
+ declare function decodePool(pool: RawPool | null | undefined, base: ChainAsset, quote: ChainAsset): PoolState | null;
59
+ /**
60
+ * Decode and select a pool. With `poolId`, only that pool is considered;
61
+ * otherwise the deepest pool (largest quote reserve) wins.
62
+ */
63
+ declare function selectPool(pools: RawPool[], base: ChainAsset, quote: ChainAsset, poolId?: string | null): PoolState | null;
64
+ export { resolveAsset, fetchOrderBook, normalizeLimitOrders, fetchPools, resolvePool, decodePool, selectPool };
65
+ export type { ChainDbClient, ChainAsset, RawLimitOrder, RawPool };
66
+ //# sourceMappingURL=liquidity_chain.d.ts.map
@@ -0,0 +1,178 @@
1
+ 'use strict';
2
+ /**
3
+ * CHAIN READ HELPERS for the liquidity depth chart.
4
+ *
5
+ * Thin, dependency-injected wrappers over the read-only chain client so the
6
+ * order-book/pool decoding can be unit-tested with a stub `db()` function.
7
+ * Analysis connections never use the production singleton client (see
8
+ * analysis/chain_pool.ts).
9
+ *
10
+ * Pool references (id or pool token) are resolved by the shared helper in
11
+ * modules/liquidity_pool_ref.ts, so `dexbot liq`, `dexbot tv`/`dw` and this
12
+ * analyzer accept the same spellings.
13
+ */
14
+ import { blockchainToFloat } from '../../modules/order/utils/math.js';
15
+ import { poolAssetIds, resolvePoolRef } from '../../modules/liquidity_pool_ref.js';
16
+ import { resolveAssetRef } from '../../modules/asset_lookup.js';
17
+ import { normalizeOrderBook } from './liquidity_depth_model.js';
18
+ async function resolveAsset(client, ref) {
19
+ const probe = String(ref || '').trim();
20
+ if (!probe)
21
+ throw new Error('Asset reference is empty');
22
+ // Shared case-insensitive lookup (modules/asset_lookup.ts): "token.sym",
23
+ // "TOKEN.SYM" and "1.3.x" all reach the same asset object.
24
+ const asset = await resolveAssetRef((method, args) => client.db(method, args), probe);
25
+ if (!asset?.id || !asset.symbol || typeof asset.precision !== 'number') {
26
+ throw new Error(`Cannot resolve asset '${probe}' on chain`);
27
+ }
28
+ return { id: asset.id, symbol: asset.symbol, precision: asset.precision };
29
+ }
30
+ /**
31
+ * Decode raw limit orders into real bid/ask sides with display prices
32
+ * (quote per base) and quote/base amounts.
33
+ *
34
+ * `get_order_book` and `get_limit_orders` share the same side convention: an
35
+ * order whose `sell_price.base` is the requested base SELLS the base (real
36
+ * ask); the other side sells the quote (real bid).
37
+ */
38
+ function normalizeLimitOrders(orders, base, quote) {
39
+ const bids = [];
40
+ const asks = [];
41
+ if (!Array.isArray(orders))
42
+ return { bids, asks };
43
+ for (const entry of orders) {
44
+ const sellAsset = entry?.sell_price?.base?.asset_id;
45
+ const baseRaw = Number(entry?.sell_price?.base?.amount);
46
+ const quoteRaw = Number(entry?.sell_price?.quote?.amount);
47
+ const forSale = Number(entry?.for_sale ?? baseRaw);
48
+ if (!(baseRaw > 0) || !(quoteRaw > 0) || !(forSale > 0))
49
+ continue;
50
+ const sellsBase = sellAsset === base.id;
51
+ const sellsQuote = sellAsset === quote.id;
52
+ if (!sellsBase && !sellsQuote)
53
+ continue;
54
+ // `received` is the amount of the other asset the seller gets for the
55
+ // whole order; scaling by for_sale/baseRaw handles reduced fractions.
56
+ const receivedRaw = forSale * (quoteRaw / baseRaw);
57
+ if (sellsBase) {
58
+ const soldBase = blockchainToFloat(forSale, base.precision);
59
+ const receivedQuote = blockchainToFloat(receivedRaw, quote.precision);
60
+ if (soldBase > 0 && receivedQuote > 0) {
61
+ asks.push({ price: receivedQuote / soldBase, quote: receivedQuote, base: soldBase });
62
+ }
63
+ }
64
+ else {
65
+ const soldQuote = blockchainToFloat(forSale, quote.precision);
66
+ const receivedBase = blockchainToFloat(receivedRaw, base.precision);
67
+ if (soldQuote > 0 && receivedBase > 0) {
68
+ bids.push({ price: soldQuote / receivedBase, quote: soldQuote, base: receivedBase });
69
+ }
70
+ }
71
+ }
72
+ bids.sort((a, b) => b.price - a.price);
73
+ asks.sort((a, b) => a.price - b.price);
74
+ return { bids, asks };
75
+ }
76
+ /**
77
+ * Fetch the order book, preferring `get_limit_orders` because nodes usually
78
+ * cap `get_order_book` at 50 levels while `get_limit_orders` allows up to
79
+ * ~300 per side. Falls back to `get_order_book` when the wider API is not
80
+ * available. `depth` is per side.
81
+ */
82
+ async function fetchOrderBook(client, base, quote, depth) {
83
+ const requested = Math.max(1, Math.floor(depth));
84
+ const limits = [];
85
+ for (const candidate of [requested, 300, 100, 50]) {
86
+ if (candidate <= requested && !limits.includes(candidate))
87
+ limits.push(candidate);
88
+ }
89
+ for (const limit of limits) {
90
+ try {
91
+ const orders = await client.db('get_limit_orders', [base.id, quote.id, limit]);
92
+ if (Array.isArray(orders))
93
+ return normalizeLimitOrders(orders, base, quote);
94
+ }
95
+ catch (err) {
96
+ const message = String(err?.message ?? err);
97
+ if (!/limit|configured_limit|unknown|not found|method/i.test(message))
98
+ throw err;
99
+ }
100
+ }
101
+ // Conservative fallback: the classic order-book API (commonly capped at 50).
102
+ for (const limit of limits) {
103
+ if (limit > 50)
104
+ continue;
105
+ try {
106
+ const raw = await client.db('get_order_book', [base.id, quote.id, limit]);
107
+ return normalizeOrderBook(raw);
108
+ }
109
+ catch (err) {
110
+ const message = String(err?.message ?? err);
111
+ if (!/limit|configured_limit/i.test(message))
112
+ throw err;
113
+ }
114
+ }
115
+ const raw = await client.db('get_order_book', [base.id, quote.id, 50]);
116
+ return normalizeOrderBook(raw);
117
+ }
118
+ async function fetchPools(client, baseId, quoteId) {
119
+ const raw = await client.db('get_liquidity_pools_by_both_assets', [baseId, quoteId]);
120
+ return Array.isArray(raw) ? raw : [];
121
+ }
122
+ /**
123
+ * Resolve a pool by id (`133` / `1.19.133`) or by its pool token (LP share-asset
124
+ * symbol). Shared with `dexbot tv`/`dw` and the liquidity analyzer's `--pool`.
125
+ */
126
+ async function resolvePool(client, ref) {
127
+ return await resolvePoolRef((method, args) => client.db(method, args), ref);
128
+ }
129
+ /** Decode one raw pool into display reserves (base = asset A, quote = asset B). */
130
+ function decodePool(pool, base, quote) {
131
+ if (!pool)
132
+ return null;
133
+ const [assetA, assetB] = poolAssetIds(pool);
134
+ const aIsBase = assetA === base.id;
135
+ const aIsQuote = assetA === quote.id;
136
+ if (!aIsBase && !aIsQuote)
137
+ return null;
138
+ if (aIsBase && assetB !== quote.id)
139
+ return null;
140
+ if (aIsQuote && assetB !== base.id)
141
+ return null;
142
+ const baseRaw = aIsBase ? pool.balance_a : pool.balance_b;
143
+ const quoteRaw = aIsBase ? pool.balance_b : pool.balance_a;
144
+ if (baseRaw == null || quoteRaw == null)
145
+ return null;
146
+ const baseReserve = blockchainToFloat(baseRaw, base.precision);
147
+ const quoteReserve = blockchainToFloat(quoteRaw, quote.precision);
148
+ if (!(baseReserve > 0) || !(quoteReserve > 0))
149
+ return null;
150
+ // Chain stores the taker fee in 1/10000 units (50 => 0.5%).
151
+ const feePercent = typeof pool.taker_fee_percent === 'number'
152
+ ? pool.taker_fee_percent / 100
153
+ : null;
154
+ return {
155
+ id: pool.id,
156
+ shareAsset: pool.share_asset,
157
+ baseReserve,
158
+ quoteReserve,
159
+ feePercent,
160
+ };
161
+ }
162
+ /**
163
+ * Decode and select a pool. With `poolId`, only that pool is considered;
164
+ * otherwise the deepest pool (largest quote reserve) wins.
165
+ */
166
+ function selectPool(pools, base, quote, poolId) {
167
+ const wanted = poolId ? String(poolId).trim() : null;
168
+ const decoded = pools
169
+ .filter((p) => !wanted || p.id === wanted)
170
+ .map((p) => decodePool(p, base, quote))
171
+ .filter((p) => p != null);
172
+ if (decoded.length === 0)
173
+ return null;
174
+ decoded.sort((a, b) => b.quoteReserve - a.quoteReserve);
175
+ return decoded[0];
176
+ }
177
+ export { resolveAsset, fetchOrderBook, normalizeLimitOrders, fetchPools, resolvePool, decodePool, selectPool };
178
+ //# sourceMappingURL=liquidity_chain.js.map
@@ -0,0 +1,19 @@
1
+ import type { BookStats, DepthBuildResult, PoolState, PriceWindow } from './liquidity_depth_model.js';
2
+ interface ChartAsset {
3
+ symbol: string;
4
+ id?: string;
5
+ precision?: number;
6
+ }
7
+ interface LiquidityChartInput {
8
+ base: ChartAsset;
9
+ quote: ChartAsset;
10
+ pool: PoolState | null;
11
+ book: BookStats;
12
+ series: DepthBuildResult;
13
+ window: PriceWindow;
14
+ generatedAt?: string;
15
+ }
16
+ declare function generateLiquidityHTML(input: LiquidityChartInput, title?: string): string;
17
+ export { generateLiquidityHTML };
18
+ export type { LiquidityChartInput, ChartAsset };
19
+ //# sourceMappingURL=liquidity_chart_generator.d.ts.map