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,166 @@
1
+ /**
2
+ * LIQUIDITY DEPTH MODEL (pure, no I/O)
3
+ *
4
+ * Blends the limit-order book with the constant-product AMM pool of one asset
5
+ * pair into a single cumulative-depth curve, in the style of PoolTool's depth
6
+ * chart.
7
+ *
8
+ * Conventions
9
+ * -----------
10
+ * - `base` = asset A (the asset whose price is quoted)
11
+ * - `quote` = asset B (the asset the depth is measured in)
12
+ * - display price = quote per base (B/A), matching DEXBot2's price orientation
13
+ * - depth = cumulative quote (B) liquidity at or better than that price:
14
+ * * bids: quote the buyer has to spend to fill every bid at price >= p
15
+ * * asks: quote the seller receives for every ask at price <= p
16
+ * Parallel base-unit (A) depth arrays are sampled for the chart's y-axis
17
+ * toggle: bids/asks accumulate order base amounts, and the pool uses the
18
+ * mirror constant-product solution (see poolBidBaseDepth/poolAskBaseDepth).
19
+ *
20
+ * The on-chain order book exposes orders as `base`/`quote` decimal strings.
21
+ * `get_order_book(A, B)` returns:
22
+ * - `bids`: orders that SELL A (real asks) — the source code puts every
23
+ * order whose `sell_price.base` is asset A into this list.
24
+ * - `asks`: orders that SELL B, i.e. buy A (real bids).
25
+ * `normalizeOrderBook` performs that side flip, so the rest of this module
26
+ * (and the chart) speaks plain real bid/ask.
27
+ *
28
+ * Pool depth is the exact constant-product solution, net of the AMM taker fee
29
+ * f (`taker_fee_percent / 100`). The fee comes off the output side and stays in
30
+ * the pool (the on-chain liquidity_pool_exchange evaluator), so a swap that
31
+ * moves the reserve price p0 -> p pays:
32
+ * - selling base into the pool (p < p0):
33
+ * gross quote out = quoteReserve * (1 - sqrt(p / p0))
34
+ * taker gets = (1 - f) * gross
35
+ * - buying base from the pool (p > p0):
36
+ * gross quote in = quoteReserve * (sqrt(p / p0) - 1)
37
+ * taker gets = (1 - f) * gross base
38
+ * The marginal price of such a trade is p * (1 - f) when selling and
39
+ * p / (1 - f) when buying, so the curve is parameterized by that EFFECTIVE
40
+ * price P instead of the reserve price. That keeps the local slope of the
41
+ * cumulative curve equal to P at every sample (the same property the fee-free
42
+ * closed forms have), and it opens a fee band between the two sides:
43
+ * bid (P < (1 - f) * p0) = (1 - f) * quoteReserve * (1 - sqrt(P / ((1 - f) * p0)))
44
+ * ask (P > p0 / (1 - f)) = quoteReserve * (sqrt(P * (1 - f) / p0) - 1)
45
+ * i.e. the AMM's own spread `[(1 - f) * p0, p0 / (1 - f)]` (~2f wide) that a
46
+ * taker has to cross. With f = 0 both sides collapse onto p0 and reduce to the
47
+ * curve PoolTool plots (`amount_y * (1 - sqrt(p_pool/p))` and
48
+ * `amount_y * (sqrt(p_pool/p) - 1)`; its price is base-per-quote, so the same
49
+ * curves appear with the reciprocal price). The closed forms preserve
50
+ * x * y = k and move the implied pool price to exactly p.
51
+ */
52
+ interface RawBookOrder {
53
+ price?: string | number;
54
+ base?: string | number;
55
+ quote?: string | number;
56
+ id?: string;
57
+ owner_name?: string;
58
+ }
59
+ interface RawOrderBook {
60
+ bids?: RawBookOrder[];
61
+ asks?: RawBookOrder[];
62
+ }
63
+ interface BookOrder {
64
+ /** Display price in quote per base. */
65
+ price: number;
66
+ /** Amount of quote asset traded by this order (the depth unit). */
67
+ quote: number;
68
+ /** Amount of base asset traded by this order. */
69
+ base: number;
70
+ }
71
+ interface BookSides {
72
+ /** Real bids (buyers of base), highest price first. */
73
+ bids: BookOrder[];
74
+ /** Real asks (sellers of base), lowest price first. */
75
+ asks: BookOrder[];
76
+ }
77
+ interface PoolState {
78
+ id?: string;
79
+ shareAsset?: string;
80
+ baseReserve: number;
81
+ quoteReserve: number;
82
+ /** AMM taker fee in percent (e.g. 0.2 = 20 bps), when known. */
83
+ feePercent?: number | null;
84
+ }
85
+ interface DepthSeries {
86
+ prices: number[];
87
+ /** Effective pool bid edge (fee-adjusted); null without a pool. */
88
+ poolBidPrice: number | null;
89
+ /** Effective pool ask edge (fee-adjusted); null without a pool. */
90
+ poolAskPrice: number | null;
91
+ /** Cumulative quote (B) depth. */
92
+ bookBid: number[];
93
+ poolBid: number[];
94
+ bookAsk: number[];
95
+ poolAsk: number[];
96
+ /** Cumulative base (A) depth, same price axis (toggled by the chart). */
97
+ bookBidBase: number[];
98
+ poolBidBase: number[];
99
+ bookAskBase: number[];
100
+ poolAskBase: number[];
101
+ }
102
+ interface PriceWindow {
103
+ min: number;
104
+ max: number;
105
+ }
106
+ interface BookStats {
107
+ bestBid: number | null;
108
+ bestAsk: number | null;
109
+ mid: number | null;
110
+ spreadPercent: number | null;
111
+ bidOrders: number;
112
+ askOrders: number;
113
+ bidQuoteTotal: number;
114
+ askQuoteTotal: number;
115
+ }
116
+ interface DepthBuildInput {
117
+ bids: BookOrder[];
118
+ asks: BookOrder[];
119
+ pool?: PoolState | null;
120
+ window: PriceWindow;
121
+ steps?: number;
122
+ }
123
+ interface DepthBuildResult extends DepthSeries {
124
+ poolPrice: number | null;
125
+ /** Union grid including exact book levels for sharp step corners. */
126
+ priceCount: number;
127
+ }
128
+ declare const DEFAULT_STEPS = 400;
129
+ /**
130
+ * Convert the raw `get_order_book` payload into real bid/ask sides and display
131
+ * prices (quote per base). Invalid orders (missing/zero amounts) are skipped.
132
+ * See the module header for why the on-chain `bids` list becomes real asks.
133
+ */
134
+ declare function normalizeOrderBook(rawBook: RawOrderBook | null | undefined): BookSides;
135
+ declare function computePoolPrice(pool: PoolState | null | undefined): number | null;
136
+ declare function computeBookStats(sides: BookSides): BookStats;
137
+ /**
138
+ * Symmetric linear window around the pool price (or the book mid when there is
139
+ * no pool), e.g. range 0.5 => [0.5 * center, 1.5 * center].
140
+ */
141
+ declare function resolvePriceWindow(center: number | null, range: number): PriceWindow;
142
+ /**
143
+ * AMM taker fee as a fraction (0.2% => 0.002). Unknown/negative fees are 0 and
144
+ * the value is capped below 1 so the effective ask edge stays finite.
145
+ */
146
+ declare function poolFeeFraction(pool: PoolState | null | undefined): number;
147
+ /** Effective pool bid edge: the highest price a pool seller can realize. */
148
+ declare function poolBidPrice(poolPrice: number, fee?: number): number;
149
+ /** Effective pool ask edge: the lowest price a pool buyer can realize. */
150
+ declare function poolAskPrice(poolPrice: number, fee?: number): number;
151
+ declare function poolBidDepth(price: number, poolPrice: number, quoteReserve: number, fee?: number): number;
152
+ declare function poolAskDepth(price: number, poolPrice: number, quoteReserve: number, fee?: number): number;
153
+ declare function poolBidBaseDepth(price: number, poolPrice: number, baseReserve: number, fee?: number): number;
154
+ declare function poolAskBaseDepth(price: number, poolPrice: number, baseReserve: number, fee?: number): number;
155
+ /**
156
+ * Sample the two liquidity sources independently over a price window. The
157
+ * returned arrays are all the same length and share the `prices` axis.
158
+ *
159
+ * Book depth and pool depth are deliberately NOT summed: an on-chain order and
160
+ * an AMM reserve are different claims on liquidity, so the chart shows them
161
+ * side by side at each price instead of collapsing them into one stacked total.
162
+ */
163
+ declare function buildDepthSeries(input: DepthBuildInput): DepthBuildResult;
164
+ export { DEFAULT_STEPS, normalizeOrderBook, computePoolPrice, computeBookStats, resolvePriceWindow, buildDepthSeries, poolFeeFraction, poolBidPrice, poolAskPrice, poolBidDepth, poolAskDepth, poolBidBaseDepth, poolAskBaseDepth, };
165
+ export type { RawBookOrder, RawOrderBook, BookOrder, BookSides, PoolState, DepthSeries, DepthBuildInput, DepthBuildResult, PriceWindow, BookStats, };
166
+ //# sourceMappingURL=liquidity_depth_model.d.ts.map
@@ -0,0 +1,258 @@
1
+ 'use strict';
2
+ const DEFAULT_STEPS = 400;
3
+ function isFinitePositive(value) {
4
+ return typeof value === 'number' && Number.isFinite(value) && value > 0;
5
+ }
6
+ function toPositiveNumber(value) {
7
+ const n = typeof value === 'number' ? value : Number(value);
8
+ return Number.isFinite(n) && n > 0 ? n : null;
9
+ }
10
+ /**
11
+ * Convert the raw `get_order_book` payload into real bid/ask sides and display
12
+ * prices (quote per base). Invalid orders (missing/zero amounts) are skipped.
13
+ * See the module header for why the on-chain `bids` list becomes real asks.
14
+ */
15
+ function normalizeOrderBook(rawBook) {
16
+ const bids = [];
17
+ const asks = [];
18
+ const collect = (list, target) => {
19
+ if (!Array.isArray(list))
20
+ return;
21
+ for (const entry of list) {
22
+ const base = toPositiveNumber(entry?.base);
23
+ const quote = toPositiveNumber(entry?.quote);
24
+ if (base == null || quote == null)
25
+ continue;
26
+ target.push({ price: quote / base, quote, base });
27
+ }
28
+ };
29
+ // On-chain `bids` sell the base asset => real asks.
30
+ collect(rawBook?.bids, asks);
31
+ // On-chain `asks` sell the quote asset => real bids.
32
+ collect(rawBook?.asks, bids);
33
+ bids.sort((a, b) => b.price - a.price);
34
+ asks.sort((a, b) => a.price - b.price);
35
+ return { bids, asks };
36
+ }
37
+ function computePoolPrice(pool) {
38
+ if (!pool)
39
+ return null;
40
+ if (!isFinitePositive(pool.baseReserve) || !isFinitePositive(pool.quoteReserve))
41
+ return null;
42
+ return pool.quoteReserve / pool.baseReserve;
43
+ }
44
+ function computeBookStats(sides) {
45
+ const bestBid = sides.bids.length ? sides.bids[0].price : null;
46
+ const bestAsk = sides.asks.length ? sides.asks[0].price : null;
47
+ const mid = bestBid != null && bestAsk != null
48
+ ? (bestBid + bestAsk) / 2
49
+ : bestBid ?? bestAsk ?? null;
50
+ const spreadPercent = bestBid != null && bestAsk != null && bestAsk > 0
51
+ ? ((bestAsk - bestBid) / bestAsk) * 100
52
+ : null;
53
+ return {
54
+ bestBid,
55
+ bestAsk,
56
+ mid,
57
+ spreadPercent,
58
+ bidOrders: sides.bids.length,
59
+ askOrders: sides.asks.length,
60
+ bidQuoteTotal: sides.bids.reduce((sum, o) => sum + o.quote, 0),
61
+ askQuoteTotal: sides.asks.reduce((sum, o) => sum + o.quote, 0),
62
+ };
63
+ }
64
+ /**
65
+ * Symmetric linear window around the pool price (or the book mid when there is
66
+ * no pool), e.g. range 0.5 => [0.5 * center, 1.5 * center].
67
+ */
68
+ function resolvePriceWindow(center, range) {
69
+ if (!isFinitePositive(center)) {
70
+ throw new Error('resolvePriceWindow: center price must be a positive finite number');
71
+ }
72
+ if (!Number.isFinite(range) || range <= 0 || range >= 0.95) {
73
+ throw new Error('resolvePriceWindow: range must be between 0 (exclusive) and 0.95 (exclusive)');
74
+ }
75
+ return { min: center * (1 - range), max: center * (1 + range) };
76
+ }
77
+ function lowerBound(values, target) {
78
+ let lo = 0, hi = values.length;
79
+ while (lo < hi) {
80
+ const mid = (lo + hi) >> 1;
81
+ if (values[mid] < target)
82
+ lo = mid + 1;
83
+ else
84
+ hi = mid;
85
+ }
86
+ return lo;
87
+ }
88
+ function upperBound(values, target) {
89
+ let lo = 0, hi = values.length;
90
+ while (lo < hi) {
91
+ const mid = (lo + hi) >> 1;
92
+ if (values[mid] <= target)
93
+ lo = mid + 1;
94
+ else
95
+ hi = mid;
96
+ }
97
+ return lo;
98
+ }
99
+ function buildPriceGrid(input, poolPrice, poolFee) {
100
+ const { window } = input;
101
+ const steps = Math.max(2, Math.floor(input.steps ?? DEFAULT_STEPS));
102
+ const span = window.max - window.min;
103
+ const eps = Math.max(span * 1e-9, Number.MIN_VALUE);
104
+ const values = [];
105
+ for (let i = 0; i < steps; i++) {
106
+ values.push(window.min + (span * i) / (steps - 1));
107
+ }
108
+ // Duplicate each book level with a tiny offset so the cumulative step is
109
+ // drawn as a near-vertical jump instead of a diagonal ramp between samples.
110
+ // Bids: depth excludes the level once price moves above it (p + eps).
111
+ // Asks: depth excludes the level once price moves below it (p - eps).
112
+ for (const order of input.bids) {
113
+ values.push(order.price, order.price + eps);
114
+ }
115
+ for (const order of input.asks) {
116
+ values.push(order.price, order.price - eps);
117
+ }
118
+ if (poolPrice != null) {
119
+ // Reserve price plus both fee-adjusted edges, so the band corners are
120
+ // sampled sharply instead of being smeared across a step interval.
121
+ values.push(poolPrice, poolBidPrice(poolPrice, poolFee), poolAskPrice(poolPrice, poolFee));
122
+ }
123
+ const inWindow = values.filter((v) => Number.isFinite(v) && v > 0 && v >= window.min && v <= window.max);
124
+ inWindow.sort((a, b) => a - b);
125
+ const deduped = [];
126
+ for (const v of inWindow) {
127
+ if (deduped.length === 0 || v !== deduped[deduped.length - 1])
128
+ deduped.push(v);
129
+ }
130
+ return deduped;
131
+ }
132
+ /**
133
+ * Build cumulative book depth lookup tables. Bids are stored ascending with a
134
+ * suffix sum (depth at p = sum of bids priced >= p); asks ascending with a
135
+ * prefix sum (depth at p = sum of asks priced <= p).
136
+ */
137
+ function buildBookLookups(sides) {
138
+ const bidAsc = [...sides.bids].sort((a, b) => a.price - b.price);
139
+ const bidPrices = bidAsc.map((o) => o.price);
140
+ const bidSuffix = new Array(bidPrices.length + 1).fill(0);
141
+ const bidSuffixBase = new Array(bidPrices.length + 1).fill(0);
142
+ for (let i = bidAsc.length - 1; i >= 0; i--) {
143
+ bidSuffix[i] = bidSuffix[i + 1] + bidAsc[i].quote;
144
+ bidSuffixBase[i] = bidSuffixBase[i + 1] + bidAsc[i].base;
145
+ }
146
+ const askAsc = [...sides.asks].sort((a, b) => a.price - b.price);
147
+ const askPrices = askAsc.map((o) => o.price);
148
+ const askPrefix = new Array(askPrices.length + 1).fill(0);
149
+ const askPrefixBase = new Array(askPrices.length + 1).fill(0);
150
+ for (let i = 0; i < askAsc.length; i++) {
151
+ askPrefix[i + 1] = askPrefix[i] + askAsc[i].quote;
152
+ askPrefixBase[i + 1] = askPrefixBase[i] + askAsc[i].base;
153
+ }
154
+ return { bidPrices, bidSuffix, bidSuffixBase, askPrices, askPrefix, askPrefixBase };
155
+ }
156
+ /**
157
+ * AMM taker fee as a fraction (0.2% => 0.002). Unknown/negative fees are 0 and
158
+ * the value is capped below 1 so the effective ask edge stays finite.
159
+ */
160
+ function poolFeeFraction(pool) {
161
+ const percent = pool?.feePercent;
162
+ if (typeof percent !== 'number' || !Number.isFinite(percent) || percent <= 0)
163
+ return 0;
164
+ return Math.min(percent, 99) / 100;
165
+ }
166
+ /** Effective pool bid edge: the highest price a pool seller can realize. */
167
+ function poolBidPrice(poolPrice, fee = 0) {
168
+ return poolPrice * (1 - fee);
169
+ }
170
+ /** Effective pool ask edge: the lowest price a pool buyer can realize. */
171
+ function poolAskPrice(poolPrice, fee = 0) {
172
+ return poolPrice / (1 - fee);
173
+ }
174
+ function poolBidDepth(price, poolPrice, quoteReserve, fee = 0) {
175
+ const edge = poolBidPrice(poolPrice, fee);
176
+ if (!(price < edge))
177
+ return 0;
178
+ return (1 - fee) * quoteReserve * (1 - Math.sqrt(price / edge));
179
+ }
180
+ function poolAskDepth(price, poolPrice, quoteReserve, fee = 0) {
181
+ const edge = poolAskPrice(poolPrice, fee);
182
+ if (!(price > edge))
183
+ return 0;
184
+ return quoteReserve * (Math.sqrt((price * (1 - fee)) / poolPrice) - 1);
185
+ }
186
+ function poolBidBaseDepth(price, poolPrice, baseReserve, fee = 0) {
187
+ const edge = poolBidPrice(poolPrice, fee);
188
+ if (!(price < edge))
189
+ return 0;
190
+ return baseReserve * (Math.sqrt(((1 - fee) * poolPrice) / price) - 1);
191
+ }
192
+ function poolAskBaseDepth(price, poolPrice, baseReserve, fee = 0) {
193
+ const edge = poolAskPrice(poolPrice, fee);
194
+ if (!(price > edge))
195
+ return 0;
196
+ return (1 - fee) * baseReserve * (1 - Math.sqrt(poolPrice / (price * (1 - fee))));
197
+ }
198
+ /**
199
+ * Sample the two liquidity sources independently over a price window. The
200
+ * returned arrays are all the same length and share the `prices` axis.
201
+ *
202
+ * Book depth and pool depth are deliberately NOT summed: an on-chain order and
203
+ * an AMM reserve are different claims on liquidity, so the chart shows them
204
+ * side by side at each price instead of collapsing them into one stacked total.
205
+ */
206
+ function buildDepthSeries(input) {
207
+ const { window } = input;
208
+ if (!isFinitePositive(window.min) || !isFinitePositive(window.max) || window.max <= window.min) {
209
+ throw new Error('buildDepthSeries: window must be positive with max > min');
210
+ }
211
+ const poolPrice = computePoolPrice(input.pool);
212
+ const fee = poolFeeFraction(input.pool);
213
+ const quoteReserve = poolPrice != null && input.pool ? input.pool.quoteReserve : 0;
214
+ const prices = buildPriceGrid(input, poolPrice, fee);
215
+ if (prices.length === 0)
216
+ throw new Error('buildDepthSeries: empty price grid');
217
+ const { bidPrices, bidSuffix, bidSuffixBase, askPrices, askPrefix, askPrefixBase } = buildBookLookups({
218
+ bids: input.bids,
219
+ asks: input.asks,
220
+ });
221
+ const baseReserve = poolPrice != null && input.pool ? input.pool.baseReserve : 0;
222
+ const series = {
223
+ prices,
224
+ poolBidPrice: poolPrice != null ? poolBidPrice(poolPrice, fee) : null,
225
+ poolAskPrice: poolPrice != null ? poolAskPrice(poolPrice, fee) : null,
226
+ bookBid: [],
227
+ poolBid: [],
228
+ bookAsk: [],
229
+ poolAsk: [],
230
+ bookBidBase: [],
231
+ poolBidBase: [],
232
+ bookAskBase: [],
233
+ poolAskBase: [],
234
+ poolPrice,
235
+ priceCount: prices.length,
236
+ };
237
+ for (const price of prices) {
238
+ const bookBid = bidSuffix[lowerBound(bidPrices, price)] ?? 0;
239
+ const bookAsk = askPrefix[upperBound(askPrices, price)] ?? 0;
240
+ const bookBidBase = bidSuffixBase[lowerBound(bidPrices, price)] ?? 0;
241
+ const bookAskBase = askPrefixBase[upperBound(askPrices, price)] ?? 0;
242
+ const poolBid = poolPrice != null ? poolBidDepth(price, poolPrice, quoteReserve, fee) : 0;
243
+ const poolAsk = poolPrice != null ? poolAskDepth(price, poolPrice, quoteReserve, fee) : 0;
244
+ const poolBidBase = poolPrice != null ? poolBidBaseDepth(price, poolPrice, baseReserve, fee) : 0;
245
+ const poolAskBase = poolPrice != null ? poolAskBaseDepth(price, poolPrice, baseReserve, fee) : 0;
246
+ series.bookBid.push(bookBid);
247
+ series.poolBid.push(poolBid);
248
+ series.bookAsk.push(bookAsk);
249
+ series.poolAsk.push(poolAsk);
250
+ series.bookBidBase.push(bookBidBase);
251
+ series.poolBidBase.push(poolBidBase);
252
+ series.bookAskBase.push(bookAskBase);
253
+ series.poolAskBase.push(poolAskBase);
254
+ }
255
+ return series;
256
+ }
257
+ export { DEFAULT_STEPS, normalizeOrderBook, computePoolPrice, computeBookStats, resolvePriceWindow, buildDepthSeries, poolFeeFraction, poolBidPrice, poolAskPrice, poolBidDepth, poolAskDepth, poolBidBaseDepth, poolAskBaseDepth, };
258
+ //# sourceMappingURL=liquidity_depth_model.js.map
@@ -0,0 +1,53 @@
1
+ /**
2
+ * LIQUIDITY CHART VIEW TRANSFORM (pure, shared by Node tests and the chart)
3
+ *
4
+ * The browser chart can show four combinations of price orientation and depth
5
+ * asset. This function is the single source of truth for that transform; the
6
+ * generated HTML embeds the exact same source via embedFunctionSources(), so
7
+ * the Node tests exercise the code the chart actually runs.
8
+ *
9
+ * orientation 'normal' price = quote per base (B/A)
10
+ * orientation 'inverted' price = base per quote (A/B) = 1 / price
11
+ *
12
+ * Inversion swaps bid/ask roles: a bid for the old base is an ask for the new
13
+ * base. `depthMode` selects the asset the cumulative depth is measured in,
14
+ * relative to the current orientation ('quote' or 'base').
15
+ *
16
+ * The same transform carries the two spread bands the chart shades: the pool's
17
+ * fee-adjusted edges and the book's best bid/ask. Inversion flips both, so the
18
+ * bands stay on the correct sides instead of mirroring the wrong way round.
19
+ */
20
+ import type { DepthSeries, PriceWindow } from './liquidity_depth_model.js';
21
+ interface DepthView {
22
+ prices: number[];
23
+ bookBid: number[];
24
+ poolBid: number[];
25
+ bookAsk: number[];
26
+ poolAsk: number[];
27
+ poolPrice: number | null;
28
+ /** Fee-adjusted pool bid edge in the current price orientation. */
29
+ poolBidPrice: number | null;
30
+ /** Fee-adjusted pool ask edge in the current price orientation. */
31
+ poolAskPrice: number | null;
32
+ /** Best book bid (the low edge of the order-book spread band). */
33
+ bookBidPrice: number | null;
34
+ /** Best book ask (the high edge of the order-book spread band). */
35
+ bookAskPrice: number | null;
36
+ mid: number | null;
37
+ min: number;
38
+ max: number;
39
+ }
40
+ interface DepthViewOptions {
41
+ orientation: 'normal' | 'inverted';
42
+ depthMode: 'quote' | 'base';
43
+ poolPrice: number | null;
44
+ mid: number | null;
45
+ window: PriceWindow;
46
+ /** Best book bid/ask, so the book spread band follows the orientation. */
47
+ bookBestBid?: number | null;
48
+ bookBestAsk?: number | null;
49
+ }
50
+ declare function buildDepthView(series: DepthSeries, options: DepthViewOptions): DepthView;
51
+ export { buildDepthView };
52
+ export type { DepthView, DepthViewOptions };
53
+ //# sourceMappingURL=liquidity_view.d.ts.map
@@ -0,0 +1,66 @@
1
+ 'use strict';
2
+ function buildDepthView(series, options) {
3
+ const useQuote = options.depthMode === 'quote';
4
+ if (options.orientation === 'normal') {
5
+ return {
6
+ prices: series.prices,
7
+ bookBid: useQuote ? series.bookBid : series.bookBidBase,
8
+ poolBid: useQuote ? series.poolBid : series.poolBidBase,
9
+ bookAsk: useQuote ? series.bookAsk : series.bookAskBase,
10
+ poolAsk: useQuote ? series.poolAsk : series.poolAskBase,
11
+ poolPrice: options.poolPrice,
12
+ poolBidPrice: series.poolBidPrice,
13
+ poolAskPrice: series.poolAskPrice,
14
+ bookBidPrice: options.bookBestBid != null && options.bookBestBid > 0 ? options.bookBestBid : null,
15
+ bookAskPrice: options.bookBestAsk != null && options.bookBestAsk > 0 ? options.bookBestAsk : null,
16
+ mid: options.mid,
17
+ min: options.window.min,
18
+ max: options.window.max,
19
+ };
20
+ }
21
+ const n = series.prices.length;
22
+ const prices = new Array(n);
23
+ const bookBid = new Array(n);
24
+ const poolBid = new Array(n);
25
+ const bookAsk = new Array(n);
26
+ const poolAsk = new Array(n);
27
+ // 1/p reverses ordering, so walk the source backwards to keep the output
28
+ // ascending (uPlot requires an ascending x axis).
29
+ for (let out = 0, i = n - 1; i >= 0; i--, out++) {
30
+ prices[out] = 1 / series.prices[i];
31
+ bookBid[out] = useQuote ? series.bookAskBase[i] : series.bookAsk[i];
32
+ poolBid[out] = useQuote ? series.poolAskBase[i] : series.poolAsk[i];
33
+ bookAsk[out] = useQuote ? series.bookBidBase[i] : series.bookBid[i];
34
+ poolAsk[out] = useQuote ? series.poolBidBase[i] : series.poolBid[i];
35
+ }
36
+ // Keep the market center visually centered: a linearly symmetric window in
37
+ // normal price becomes an asymmetric window under 1/p, so rebuild the
38
+ // inverted view as a symmetric window around the reciprocal center instead
39
+ // of simply reciprocating the edges. The server samples a wider price range
40
+ // (up to p0 / (1 - range)) so this window is fully covered by data.
41
+ const span = options.window.max - options.window.min;
42
+ const range = span / (options.window.max + options.window.min);
43
+ const center = options.poolPrice != null ? options.poolPrice : options.mid;
44
+ const qCenter = center != null && center > 0 ? 1 / center : 1 / ((options.window.min + options.window.max) / 2);
45
+ const validRange = Number.isFinite(range) && range > 0 && range < 1;
46
+ return {
47
+ prices,
48
+ bookBid,
49
+ poolBid,
50
+ bookAsk,
51
+ poolAsk,
52
+ poolPrice: options.poolPrice != null ? 1 / options.poolPrice : null,
53
+ // Inversion swaps the sides, so the pool's bid edge becomes 1/askEdge.
54
+ poolBidPrice: series.poolAskPrice != null ? 1 / series.poolAskPrice : null,
55
+ poolAskPrice: series.poolBidPrice != null ? 1 / series.poolBidPrice : null,
56
+ // The best book bid becomes the inverted market's best ask, and vice
57
+ // versa, so the spread band survives an orientation flip intact.
58
+ bookBidPrice: options.bookBestAsk != null && options.bookBestAsk > 0 ? 1 / options.bookBestAsk : null,
59
+ bookAskPrice: options.bookBestBid != null && options.bookBestBid > 0 ? 1 / options.bookBestBid : null,
60
+ mid: options.mid != null ? 1 / options.mid : null,
61
+ min: validRange ? qCenter * (1 - range) : 1 / options.window.max,
62
+ max: validRange ? qCenter * (1 + range) : 1 / options.window.min,
63
+ };
64
+ }
65
+ export { buildDepthView };
66
+ //# sourceMappingURL=liquidity_view.js.map
@@ -20,7 +20,7 @@
20
20
  * shared client on exit. Run standalone only — never import/call from a
21
21
  * long-running process holding a live connection.
22
22
  */
23
- import { loadBotSettings, computeBotKey, persistBotAccountId } from './bot_key_utils.js';
23
+ import { loadBotSettings, computeBotKey, persistBotAccountId, matchBotEntryTarget, isAccountIdRef } from './bot_key_utils.js';
24
24
  import { setGlobalConsoleLevel, getGlobalConsoleLevel } from '../modules/order/logger.js';
25
25
  import { sleep } from '../modules/order/utils/system.js';
26
26
  import { getErrorMessage, getErrorCode } from '../modules/utils/errors.js';
@@ -90,7 +90,7 @@ async function resolveWithTimeout(chainOrders, ref, timeoutMs) {
90
90
  chainOrders.resolveAccountId(ref),
91
91
  sleep(timeoutMs).then(() => { throw timeoutErr; }),
92
92
  ]);
93
- if (id && /^1\.2\.\d+$/.test(String(id)))
93
+ if (id && isAccountIdRef(id))
94
94
  return { id: String(id), reason: 'resolved' };
95
95
  return { id: null, reason: 'not-found' };
96
96
  }
@@ -108,8 +108,9 @@ async function main() {
108
108
  }
109
109
  let targets = entries.map((bot, index) => ({ bot, index, key: computeBotKey(bot, index) }));
110
110
  if (opts.botKey) {
111
- const want = String(opts.botKey).toLowerCase();
112
- targets = targets.filter((t) => t.key === want || String(t.bot?.name ?? '').toLowerCase() === want);
111
+ // Shared `<bot>` rule set (analysis/bot_key_utils): bot key or display
112
+ // name, case/separator-insensitive.
113
+ targets = targets.filter((t) => matchBotEntryTarget(t.bot, opts.botKey, t.key) !== null);
113
114
  if (!targets.length) {
114
115
  console.error(`Error: bot '${opts.botKey}' not found in profiles/bots.json.`);
115
116
  process.exit(1);
@@ -141,13 +142,13 @@ async function main() {
141
142
  for (const t of targets) {
142
143
  const name = t.bot?.name ?? t.key;
143
144
  const prefRaw = t.bot?.preferredAccount != null ? String(t.bot.preferredAccount) : '';
144
- const stored = /^1\.2\.\d+$/.test(String(t.bot?.accountId ?? '')) ? String(t.bot.accountId) : null;
145
+ const stored = isAccountIdRef(t.bot?.accountId) ? String(t.bot.accountId) : null;
145
146
  if (!prefRaw) {
146
147
  results.push({ key: t.key, name, status: 'skipped', detail: 'no preferredAccount' });
147
148
  console.log(`- ${t.key}: skipped (no preferredAccount)`);
148
149
  continue;
149
150
  }
150
- if (/^1\.2\.\d+$/.test(prefRaw)) {
151
+ if (isAccountIdRef(prefRaw)) {
151
152
  if (stored !== prefRaw) {
152
153
  const wrote = opts.dryRun ? true : persistBotAccountId(t.key, prefRaw);
153
154
  const status = !wrote ? 'failed' : (opts.dryRun ? 'would-update' : 'updated');
@@ -4,11 +4,13 @@ import fs from 'node:fs';
4
4
  import path from 'node:path';
5
5
  import { pathToFileURL } from 'node:url';
6
6
  import { resolveAccountRef } from './account_resolver.js';
7
+ import { isAccountIdRef } from './bot_key_utils.js';
7
8
  import { BTS_ID, assetPrec as getPrec, assetSymbol, resolveAssetPrecisions, classifyFill, matchesAssetRef, } from './fills_source.js';
8
9
  import { writePnlReport } from './pnl_report.js';
9
10
  import { percentile } from './math_utils.js';
10
11
  import { fetchFillsCached } from './fills_cache.js';
11
12
  import { toFileUrl } from './chart_utils.js';
13
+ import { CLI_TAGS, savedLine } from '../modules/cli_progress.js';
12
14
  import { PATHS } from '../modules/paths.js';
13
15
  import { sanitizeKey } from '../modules/utils/sanitize_key.js';
14
16
  import { monthsToHours } from '../modules/utils/time_range.js';
@@ -1074,7 +1076,7 @@ async function run(argv = process.argv.slice(2)) {
1074
1076
  const opts = parseArgs(argv);
1075
1077
  let accountId = opts.accountId;
1076
1078
  let resolvedBotName = null;
1077
- if (!/^1\.2\.\d+$/.test(String(accountId))) {
1079
+ if (!isAccountIdRef(accountId)) {
1078
1080
  // The Kibana query below filters on the 1.2.x account_id field, so a
1079
1081
  // name must always resolve first (a raw name would silently return
1080
1082
  // zero fills). Shared resolver: a local bot profile is checked first
@@ -1175,7 +1177,7 @@ async function run(argv = process.argv.slice(2)) {
1175
1177
  assetFilter: opts.asset,
1176
1178
  pairs: analyses.map(pair => ({ pair, metrics: computeMetrics(pair, reportWindow) })),
1177
1179
  }, reportPath);
1178
- console.log(`\nšŸ“„ PnL report saved. Open report: (${toFileUrl(reportPath)})`);
1180
+ console.log(savedLine(CLI_TAGS.pnl, 'PnL report', toFileUrl(reportPath), 'report'));
1179
1181
  }
1180
1182
  else {
1181
1183
  // Output: summaries → grand total → per-match detail
@@ -12,6 +12,7 @@ import { toIntervalLabel } from '../../market_adapter/interval_utils.js';
12
12
  import { loadBotMeta } from '../bot_key_utils.js';
13
13
  import { resolveSource, listAvailableBots } from '../resolve_source.js';
14
14
  import { writeChartFile, toFileUrl } from '../chart_utils.js';
15
+ import { CLI_TAGS, savedLine } from '../../modules/cli_progress.js';
15
16
  import { PATHS } from '../../modules/paths.js';
16
17
  const DEFAULT_CHART_DIR = PATHS.ANALYSIS.CHARTS_DIR;
17
18
  const DEFAULT_CHART_FILE = path.join(DEFAULT_CHART_DIR, 'tradingview_chart.html');
@@ -316,7 +317,7 @@ async function main() {
316
317
  }, title);
317
318
  writeChartFile(config.chartFile, html);
318
319
  if (!config.quiet)
319
- console.log(`\n[TradingView] āœ“ Chart saved. Open chart: (${toFileUrl(config.chartFile)})`);
320
+ console.log(savedLine(CLI_TAGS.tradingView, 'Chart', toFileUrl(config.chartFile)));
320
321
  }
321
322
  catch (err) {
322
323
  console.error(`[TradingView] Error: ${getErrorMessage(err)}`);
@@ -785,8 +785,19 @@ function refreshNodeList() {
785
785
  try {
786
786
  const bestNodes = orderNodesForSettings(settings);
787
787
  if (bestNodes && bestNodes.length > 0) {
788
- _nativeNodeList = bestNodes;
789
- _nativeChainClient.setNodes(bestNodes);
788
+ // Never evict the node this daemon is currently connected to.
789
+ // setNodes() replaces the transport candidate list, and
790
+ // transport.connect() only keeps its socket when that list
791
+ // still contains the active node — so a refresh built from the
792
+ // health cache (which omits nodes that are momentarily
793
+ // unhealthy) used to force a full teardown on the next
794
+ // broadcast. Appending it as the last candidate is enough.
795
+ const activeNode = _nativeChainClient.transport?.getNodeUrl?.();
796
+ const nodes = activeNode && !bestNodes.includes(activeNode)
797
+ ? [...bestNodes, activeNode]
798
+ : bestNodes;
799
+ _nativeNodeList = nodes;
800
+ _nativeChainClient.setNodes(nodes);
790
801
  daemonLogger.log?.(`[credential-daemon] Node list refreshed: using best ${bestNodes.length} nodes from cache.`);
791
802
  }
792
803
  }