dexbot 1.6.17 → 1.7.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (156) hide show
  1. package/CHANGELOG.md +58 -0
  2. package/README.md +24 -18
  3. package/analysis/README.md +105 -12
  4. package/analysis/ama_fitting/README.md +2 -2
  5. package/analysis/bot_fitting/README.md +3 -3
  6. package/claw/package.json +1 -1
  7. package/claw/runtimes/openclaw-plugin/openclaw.plugin.json +1 -1
  8. package/claw/runtimes/openclaw-plugin/package.json +1 -1
  9. package/dist/analysis/analyze_args.d.ts +2 -1
  10. package/dist/analysis/analyze_dynamic_weight.js +2 -1
  11. package/dist/analysis/analyze_kalman.js +3 -2
  12. package/dist/analysis/analyze_liquidity.d.ts +17 -0
  13. package/dist/analysis/analyze_liquidity.js +325 -0
  14. package/dist/analysis/analyze_regime.js +3 -2
  15. package/dist/analysis/analyze_regime_windows.js +3 -2
  16. package/dist/analysis/analyze_volatility.js +3 -2
  17. package/dist/analysis/fills_source.d.ts +1 -8
  18. package/dist/analysis/fills_source.js +1 -1
  19. package/dist/analysis/grid_correction_check.d.ts +9 -6
  20. package/dist/analysis/grid_correction_check.js +56 -64
  21. package/dist/analysis/liquidity/liquidity_chain.d.ts +66 -0
  22. package/dist/analysis/liquidity/liquidity_chain.js +178 -0
  23. package/dist/analysis/liquidity/liquidity_chart_generator.d.ts +19 -0
  24. package/dist/analysis/liquidity/liquidity_chart_generator.js +523 -0
  25. package/dist/analysis/liquidity/liquidity_depth_model.d.ts +141 -0
  26. package/dist/analysis/liquidity/liquidity_depth_model.js +230 -0
  27. package/dist/analysis/liquidity/liquidity_view.d.ts +38 -0
  28. package/dist/analysis/liquidity/liquidity_view.js +55 -0
  29. package/dist/analysis/math_utils.d.ts +1 -1
  30. package/dist/analysis/trade_profitability.d.ts +1 -1
  31. package/dist/analysis/trade_profitability.js +2 -1
  32. package/dist/analysis/tradingview/analyze_tradingview.js +2 -1
  33. package/dist/analysis/tradingview/tradingview_uplot_chart_generator.js +3 -3
  34. package/dist/analysis/trend_detection/huber_scale_variants.d.ts +4 -3
  35. package/dist/dexbot.js +74 -169
  36. package/dist/market_adapter/cli_args.d.ts +6 -1
  37. package/dist/market_adapter/cli_args.js +16 -2
  38. package/dist/market_adapter/core/kibana_candles.d.ts +5 -1
  39. package/dist/market_adapter/core/kibana_candles.js +3 -1
  40. package/dist/market_adapter/core/strategies/regime_gate.d.ts +7 -1
  41. package/dist/market_adapter/core/strategies/regime_gate.js +3 -1
  42. package/dist/market_adapter/inputs/cex_candle_parsing.d.ts +7 -2
  43. package/dist/market_adapter/inputs/cex_candle_parsing.js +3 -1
  44. package/dist/market_adapter/inputs/fetch_book_data.d.ts +7 -1
  45. package/dist/market_adapter/inputs/fetch_book_data.js +3 -1
  46. package/dist/market_adapter/inputs/fetch_cex_synthetic_data.js +2 -11
  47. package/dist/market_adapter/inputs/fetch_lp_data.d.ts +26 -1
  48. package/dist/market_adapter/inputs/fetch_lp_data.js +62 -52
  49. package/dist/market_adapter/inputs/kibana_feed_source.d.ts +14 -2
  50. package/dist/market_adapter/inputs/kibana_feed_source.js +14 -1
  51. package/dist/market_adapter/inputs/window_cache.d.ts +14 -3
  52. package/dist/market_adapter/inputs/window_cache.js +14 -1
  53. package/dist/market_adapter/lp_chart_runner.d.ts +12 -9
  54. package/dist/market_adapter/lp_chart_runner.js +3 -1
  55. package/dist/market_adapter/lp_chart_strategy_loader.d.ts +5 -1
  56. package/dist/market_adapter/lp_chart_strategy_loader.js +3 -1
  57. package/dist/market_adapter/market_adapter.d.ts +10 -2
  58. package/dist/market_adapter/market_adapter.js +10 -11
  59. package/dist/market_adapter/utils/chain.d.ts +2 -3
  60. package/dist/market_adapter/utils/file_json_cache.d.ts +5 -1
  61. package/dist/market_adapter/utils/file_json_cache.js +3 -1
  62. package/dist/market_adapter/utils/file_lock.js +1 -1
  63. package/dist/market_adapter/utils/native_history.d.ts +7 -3
  64. package/dist/market_adapter/utils/native_history.js +3 -1
  65. package/dist/market_adapter/utils/pair_orientation.d.ts +2 -2
  66. package/dist/modules/asset_lookup.d.ts +25 -0
  67. package/dist/modules/asset_lookup.js +75 -0
  68. package/dist/modules/bots_file_lock.d.ts +2 -2
  69. package/dist/modules/bots_file_lock.js +2 -2
  70. package/dist/modules/chain_scan.d.ts +64 -0
  71. package/dist/modules/chain_scan.js +80 -0
  72. package/dist/modules/cli_colors.d.ts +5 -0
  73. package/dist/modules/cli_colors.js +7 -0
  74. package/dist/modules/cli_progress.d.ts +51 -0
  75. package/dist/modules/cli_progress.js +113 -0
  76. package/dist/modules/constants.js +6 -3
  77. package/dist/modules/dexbot_class.d.ts +8 -0
  78. package/dist/modules/dexbot_class.js +10 -0
  79. package/dist/modules/dexbot_cow_runtime.d.ts +62 -1
  80. package/dist/modules/dexbot_cow_runtime.js +475 -47
  81. package/dist/modules/dexbot_credential_client.d.ts +5 -0
  82. package/dist/modules/dexbot_fill_runtime.js +20 -0
  83. package/dist/modules/dexbot_maintenance_runtime.js +71 -9
  84. package/dist/modules/dexbot_startup_runtime.js +7 -1
  85. package/dist/modules/graceful_shutdown.d.ts +2 -2
  86. package/dist/modules/graceful_shutdown.js +2 -2
  87. package/dist/modules/launcher/runtime_entry.d.ts +21 -1
  88. package/dist/modules/launcher/runtime_entry.js +36 -1
  89. package/dist/modules/launcher/runtime_mode.d.ts +4 -3
  90. package/dist/modules/liquidity_pool_ref.d.ts +32 -0
  91. package/dist/modules/liquidity_pool_ref.js +116 -0
  92. package/dist/modules/node_manager.d.ts +1 -1
  93. package/dist/modules/node_manager.js +1 -1
  94. package/dist/modules/order/accounting.js +2 -1
  95. package/dist/modules/order/export.d.ts +2 -2
  96. package/dist/modules/order/export.js +2 -2
  97. package/dist/modules/order/grid.d.ts +19 -14
  98. package/dist/modules/order/grid.js +269 -61
  99. package/dist/modules/order/grid_reconcile.js +27 -2
  100. package/dist/modules/order/grid_reconcile_internal.js +94 -15
  101. package/dist/modules/order/index.d.ts +24 -4
  102. package/dist/modules/order/manager.d.ts +12 -0
  103. package/dist/modules/order/manager.js +44 -11
  104. package/dist/modules/order/strategy.js +22 -2
  105. package/dist/modules/order/sync_engine.d.ts +32 -1
  106. package/dist/modules/order/sync_engine.js +209 -26
  107. package/dist/modules/order/utils/math.d.ts +26 -10
  108. package/dist/modules/order/utils/math.js +54 -14
  109. package/dist/modules/order/utils/order.d.ts +158 -11
  110. package/dist/modules/order/utils/order.js +434 -21
  111. package/dist/modules/order/utils/system.d.ts +136 -30
  112. package/dist/modules/order/utils/system.js +465 -63
  113. package/dist/modules/order/utils/validate.d.ts +1 -0
  114. package/dist/modules/order/utils/validate.js +37 -3
  115. package/dist/modules/storage/index.d.ts +3 -2
  116. package/dist/modules/storage/index.js +3 -2
  117. package/dist/modules/types.d.ts +14 -0
  118. package/dist/modules/utils/asset_symbols.d.ts +13 -2
  119. package/dist/modules/utils/asset_symbols.js +21 -2
  120. package/dist/scripts/analysis_runner.d.ts +10 -0
  121. package/dist/scripts/analysis_runner.js +33 -0
  122. package/dist/scripts/analyze-orders.js +2 -1
  123. package/dist/scripts/asset.d.ts +26 -0
  124. package/dist/scripts/asset.js +165 -0
  125. package/dist/scripts/bts_distribution.d.ts +1 -0
  126. package/dist/scripts/bts_distribution.js +194 -142
  127. package/dist/scripts/chart_command.d.ts +1 -1
  128. package/dist/scripts/chart_command.js +60 -86
  129. package/dist/scripts/chart_targets.d.ts +18 -0
  130. package/dist/scripts/chart_targets.js +52 -0
  131. package/dist/scripts/dw.js +1 -1
  132. package/dist/scripts/liquid.d.ts +24 -0
  133. package/dist/scripts/liquid.js +134 -0
  134. package/dist/scripts/rich_list.js +12 -16
  135. package/dist/scripts/token_distribution.d.ts +2 -0
  136. package/dist/scripts/token_distribution.js +132 -108
  137. package/dist/scripts/tv.js +1 -1
  138. package/dist/scripts/verify-browser-bundle.js +18 -0
  139. package/docs/COPY_ON_WRITE_MASTER_PLAN.md +1 -1
  140. package/docs/COW_INVARIANTS.md +21 -11
  141. package/docs/DEXBOT_COMPARISON.md +6 -6
  142. package/docs/EVOLUTION.md +10 -8
  143. package/docs/FUND_MOVEMENT_AND_ACCOUNTING.md +11 -11
  144. package/docs/GRID_PRICE_INVARIANT.md +28 -5
  145. package/docs/GRID_RECONCILE.md +25 -5
  146. package/docs/LIFECYCLE.md +11 -11
  147. package/docs/LOGGING.md +37 -2
  148. package/docs/ORDER_ENGINE_POST_1.0_RETROSPECTIVE.md +124 -36
  149. package/docs/README.md +1 -1
  150. package/docs/WORKFLOW.md +3 -1
  151. package/docs/architecture.md +115 -13
  152. package/docs/developer_guide.md +12 -0
  153. package/market_adapter/README.md +9 -4
  154. package/modules/README.md +23 -15
  155. package/package.json +6 -3
  156. package/scripts/README.md +23 -7
@@ -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)}`);
@@ -17,13 +17,6 @@ interface FillRecord {
17
17
  }
18
18
  declare function assetSymbol(id: string): string;
19
19
  declare function assetPrec(id: string): number | undefined;
20
- declare function toReal(amount: number, assetId: string): number;
21
- /**
22
- * A fill needs strictly positive, finite amounts on both legs. A zero base
23
- * amount would produce an infinite price (quoteAmount / 0) that poisons
24
- * downstream inventory lots and PnL aggregates.
25
- */
26
- declare function isValidFillAmounts(baseAmount: number, quoteAmount: number): boolean;
27
20
  /** Match a user-supplied pair leg against a chain asset id or its symbol. */
28
21
  declare function matchesAssetRef(ref: string, assetId: string): boolean;
29
22
  interface ClassifiedFill {
@@ -55,5 +48,5 @@ declare function classifyFill(f: FillRecord): ClassifiedFill | null;
55
48
  declare function resolveAssetPrecisions(fills: FillRecord[]): Promise<void>;
56
49
  /** Fetch every fill_order for an account in [gte, lte], paginated via search_after. */
57
50
  declare function fetchAllFills(config: Record<string, unknown>, accountId: string, gte: string, lte: string): Promise<FillRecord[]>;
58
- export { BTS_ID, assetSymbol, assetPrec, toReal, isValidFillAmounts, matchesAssetRef, classifyFill, resolveAssetPrecisions, fetchAllFills, FillRecord, ClassifiedFill, };
51
+ export { BTS_ID, assetSymbol, assetPrec, matchesAssetRef, classifyFill, resolveAssetPrecisions, fetchAllFills, FillRecord, };
59
52
  //# sourceMappingURL=fills_source.d.ts.map
@@ -255,5 +255,5 @@ async function fetchAllFills(config, accountId, gte, lte) {
255
255
  }
256
256
  return fills;
257
257
  }
258
- export { BTS_ID, assetSymbol, assetPrec, toReal, isValidFillAmounts, matchesAssetRef, classifyFill, resolveAssetPrecisions, fetchAllFills, };
258
+ export { BTS_ID, assetSymbol, assetPrec, matchesAssetRef, classifyFill, resolveAssetPrecisions, fetchAllFills, };
259
259
  //# sourceMappingURL=fills_source.js.map
@@ -22,22 +22,25 @@ interface Violation {
22
22
  priceDelta: number;
23
23
  priceDeltaPct: number;
24
24
  pivot: number;
25
+ /** Direction-only rule has no band; kept at 0 so the JSON/CSV shape is stable. */
25
26
  halfInc: number;
27
+ /** The pivot itself (BUY must be below / SELL above it). */
26
28
  threshold: number;
27
29
  }
28
30
  /**
29
- * LAST-FILL-GUARD helper — pivot ± halfIncrement (replaces price-tolerance).
30
- * last fill @x with increment i: BUY < x*(1 - i/2/100), SELL > x*(1 + i/2/100)
31
- * e.g. x=1000, i=0.5% => BUY < 997.5, SELL > 1002.5
32
- * Cold (pivot null or lastType null) => disabled.
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).
33
37
  * @param {number} price - Target order price
34
38
  * @param {string} type - buy/sell
35
39
  * @param {number|null} lastPrice - Most recent fill price
36
40
  * @param {string|null} lastType - Most recent fill side (buy/sell)
37
- * @param {number|any} incrementPercent - Grid increment percent (e.g. 0.5). If not finite/<=0 falls back to DEFAULT_CONFIG.
38
41
  * @returns {{blocked: boolean, pivot: number|null, halfInc: number, threshold: number|null}}
39
42
  */
40
- declare function isLastFillGuardBlocked(price: unknown, type: unknown, lastPrice: unknown, lastType: unknown, incrementPercent: unknown): {
43
+ declare function isLastFillGuardBlocked(price: unknown, type: unknown, lastPrice: unknown, lastType: unknown): {
41
44
  blocked: boolean;
42
45
  pivot: number | null;
43
46
  halfInc?: number;