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,693 @@
1
+ 'use strict';
2
+ /**
3
+ * LIQUIDITY DEPTH CHART (uPlot)
4
+ *
5
+ * Renders one asset pair's liquidity: cumulative order-book depth and the
6
+ * constant-product AMM pool curve, overlaid side by side on the same price
7
+ * axis. The two sources are shown as independent curves (never summed), so the
8
+ * trader can see which one actually supplies the depth at a given price. The
9
+ * pool curve is fee-adjusted: each side terminates at its effective edge and
10
+ * the shaded band between them is the AMM spread a taker has to cross. The
11
+ * visual model follows PoolTool's depth chart, rebuilt with the vendored uPlot
12
+ * runtime used by every other DEXBot2 chart exporter.
13
+ *
14
+ * The page is fully self-contained (uPlot JS+CSS inlined) and needs no network
15
+ * access once written.
16
+ */
17
+ import { embedFunctionSources, escapeHtml, serializeJsonForScript, uplotInlineTags } from '../chart_utils.js';
18
+ import { sharedChartCSS } from '../chart_css.js';
19
+ import { formatCurrency, formatFundsValue, formatPercentLabel, isValidNumber, safeFormat } from '../../modules/order/format.js';
20
+ import { buildDepthView } from './liquidity_view.js';
21
+ const COLORS = {
22
+ bidBook: '#3fb950',
23
+ askBook: '#f85149',
24
+ bidPool: '#58a6ff',
25
+ askPool: '#d2a8ff',
26
+ // Spread bands: book = best bid..best ask, pool = the fee band between the
27
+ // fee-adjusted pool edges. Distinct hues so both can be compared at once;
28
+ // the fill fades downward so a band wider than the viewport reads as a
29
+ // highlight strip instead of tinting the whole chart.
30
+ bookSpreadFillTop: 'rgba(210,153,34,0.20)',
31
+ bookSpreadFillBottom: 'rgba(210,153,34,0.02)',
32
+ bookSpreadEdge: 'rgba(227,179,65,0.5)',
33
+ poolSpreadFillTop: 'rgba(210,168,255,0.24)',
34
+ poolSpreadFillBottom: 'rgba(210,168,255,0.03)',
35
+ poolSpreadEdge: 'rgba(210,168,255,0.65)',
36
+ };
37
+ function generateLiquidityHTML(input, title) {
38
+ const { base, quote, pool, book, series, window } = input;
39
+ const poolPrice = series.poolPrice;
40
+ const pageTitle = title || `Liquidity Depth — ${base.symbol} / ${quote.symbol}`;
41
+ const priceLabel = `${quote.symbol} per ${base.symbol}`;
42
+ const depthLabel = quote.symbol;
43
+ const payload = {
44
+ base: {
45
+ symbol: base.symbol,
46
+ id: base.id ?? null,
47
+ precision: base.precision ?? null,
48
+ },
49
+ quote: {
50
+ symbol: quote.symbol,
51
+ id: quote.id ?? null,
52
+ precision: quote.precision ?? null,
53
+ },
54
+ pool: pool
55
+ ? {
56
+ id: pool.id ?? null,
57
+ shareAsset: pool.shareAsset ?? null,
58
+ baseReserve: pool.baseReserve,
59
+ quoteReserve: pool.quoteReserve,
60
+ feePercent: pool.feePercent ?? null,
61
+ price: poolPrice,
62
+ }
63
+ : null,
64
+ book: {
65
+ bestBid: book.bestBid,
66
+ bestAsk: book.bestAsk,
67
+ mid: book.mid,
68
+ spreadPercent: book.spreadPercent,
69
+ bidOrders: book.bidOrders,
70
+ askOrders: book.askOrders,
71
+ bidQuoteTotal: book.bidQuoteTotal,
72
+ askQuoteTotal: book.askQuoteTotal,
73
+ },
74
+ series,
75
+ window,
76
+ priceLabel,
77
+ depthLabel,
78
+ generatedAt: input.generatedAt ?? new Date().toISOString(),
79
+ colors: COLORS,
80
+ };
81
+ const poolBadge = pool
82
+ ? `<span class="badge badge-pool">POOL ${escapeHtml(pool.id ?? 'unknown')}</span>
83
+ <span class="badge" id="badge-pool-price">${escapeHtml(formatCurrency(poolPrice))} ${escapeHtml(priceLabel)}</span>`
84
+ : `<span class="badge badge-muted">NO AMM POOL</span>`;
85
+ // The pool draws two curves that stop at their fee-adjusted edges, so the
86
+ // header states the fee and the spread it opens between them.
87
+ const poolBidEdge = series.poolBidPrice;
88
+ const poolAskEdge = series.poolAskPrice;
89
+ const poolSpreadPercent = poolBidEdge != null && poolAskEdge != null && poolAskEdge > 0
90
+ ? ((poolAskEdge - poolBidEdge) / poolAskEdge) * 100
91
+ : null;
92
+ const feeBadge = pool && pool.feePercent != null
93
+ ? `<span class="badge badge-pool" title="AMM taker fee (charged on the output side)">FEE ${escapeHtml(formatPercentLabel(pool.feePercent))}${poolSpreadPercent != null ? ` &middot; POOL SPREAD ${escapeHtml(formatPercentLabel(poolSpreadPercent))}` : ''}</span>`
94
+ : '';
95
+ const midBadge = book.mid != null
96
+ ? `<span class="badge" id="badge-mid">BOOK MID ${escapeHtml(formatCurrency(book.mid))}</span>`
97
+ : `<span class="badge badge-muted">ONE-SIDED BOOK</span>`;
98
+ const spreadBadge = book.spreadPercent != null
99
+ ? `<span class="badge badge-book">BOOK SPREAD ${escapeHtml(formatPercentLabel(book.spreadPercent))}</span>`
100
+ : '';
101
+ const windowBadge = `<span class="badge badge-muted">&plusmn;${escapeHtml(formatPercentLabel(((window.max - window.min) / (2 * (poolPrice ?? book.mid ?? window.min))) * 100))} WINDOW</span>`;
102
+ return `<!DOCTYPE html>
103
+ <html lang="en">
104
+ <head>
105
+ <meta charset="UTF-8">
106
+ <title>${escapeHtml(pageTitle)}</title>
107
+ ${uplotInlineTags()}
108
+ <style>
109
+ ${sharedChartCSS()}
110
+ #header { height: 64px; }
111
+ #panels { height: calc(100vh - 64px); }
112
+ #liquidity-panel { flex: 1 1 auto; min-height: 0; position: relative; }
113
+ #liquidity-chart { position: absolute; inset: 0; }
114
+ .badge { display: inline-block; padding: 3px 9px; border-radius: 3px; font-size: 11px; font-weight: 600;
115
+ letter-spacing: 0.4px; background: rgba(110,118,129,0.16); color: #adbac7; white-space: nowrap; }
116
+ .badge-pool { background: rgba(88,166,255,0.18); color: #79c0ff; }
117
+ .badge-book { background: rgba(210,153,34,0.18); color: #e3b341; }
118
+ .badge-muted { color: #6e7681; }
119
+ .readout { position: absolute; top: 10px; left: 12px; z-index: 10; pointer-events: none;
120
+ background: rgba(11,14,20,0.82); border: 1px solid #21262d; border-radius: 6px;
121
+ padding: 7px 10px; font-family: ui-monospace, SFMono-Regular, Menlo, monospace;
122
+ font-size: 13px; color: #adbac7; line-height: 1.45; white-space: nowrap; }
123
+ .readout .price { color: #e6edf3; font-size: 15px; font-weight: 600; }
124
+ .readout table { border-collapse: collapse; margin-top: 3px; }
125
+ .readout th { font-weight: 600; color: #6e7681; padding: 0 10px 0 0; text-align: right; }
126
+ .readout th.side { text-align: left; }
127
+ .readout td { padding: 0 10px 0 0; text-align: right; }
128
+ .readout td.side-bid { color: ${COLORS.bidBook}; text-align: left; }
129
+ .readout td.side-ask { color: ${COLORS.askBook}; text-align: left; }
130
+ .spread-block { margin-top: 5px; padding-top: 5px; border-top: 1px solid #21262d; }
131
+ .spread-row { display: flex; align-items: baseline; gap: 7px; line-height: 1.5; }
132
+ .spread-row .swatch { width: 9px; height: 9px; border-radius: 2px; align-self: center; flex: 0 0 auto; }
133
+ .spread-key { width: 30px; color: #6e7681; font-size: 11px; font-weight: 700; letter-spacing: 0.5px; }
134
+ .spread-pct { color: #adbac7; font-size: 14px; font-weight: 600; }
135
+ .spread-row.is-tighter .spread-pct { color: #7ee787; }
136
+ .spread-tag { display: none; font-size: 9px; letter-spacing: 0.4px; color: #3fb950; border: 1px solid rgba(63,185,80,0.5);
137
+ border-radius: 3px; padding: 0 4px; }
138
+ .spread-row.is-tighter .spread-tag { display: inline-block; }
139
+ .spread-range { color: #8b949e; font-size: 11px; }
140
+ .hint { font-size: 12px; color: #8b949e; white-space: nowrap; }
141
+ .legend-swatch { display: inline-block; width: 9px; height: 9px; border-radius: 2px; margin-right: 5px; vertical-align: middle; }
142
+ .legend-item { display: inline-flex; align-items: center; gap: 5px; margin-left: 8px; vertical-align: middle; }
143
+ </style>
144
+ </head>
145
+ <body>
146
+ <div id="header">
147
+ <div style="display:flex;flex-direction:column;gap:3px;">
148
+ <div style="font-weight:bold;color:#fff;font-size:13px;">${escapeHtml(pageTitle)}</div>
149
+ <div style="display:flex;gap:6px;align-items:center;flex-wrap:wrap;">
150
+ ${poolBadge}
151
+ ${feeBadge}
152
+ ${midBadge}
153
+ ${spreadBadge}
154
+ ${windowBadge}
155
+ <span class="badge badge-muted">${escapeHtml(String(book.bidOrders))} BID / ${escapeHtml(String(book.askOrders))} ASK ORDERS</span>
156
+ </div>
157
+ </div>
158
+ <div style="display:flex;flex-direction:column;gap:3px;align-items:flex-end;">
159
+ <div class="hint">Scroll&nbsp;=&nbsp;zoom &middot; Drag&nbsp;=&nbsp;pan &middot; Double-click&nbsp;=&nbsp;reset</div>
160
+ <div class="hint">
161
+ <span class="legend-item"><span class="legend-swatch" style="background:${COLORS.bidBook};"></span>book bids</span>
162
+ <span class="legend-item"><span class="legend-swatch" style="background:${COLORS.askBook};"></span>book asks</span>
163
+ <span class="legend-item"><span class="legend-swatch" style="background:${COLORS.bidPool};"></span>pool bids</span>
164
+ <span class="legend-item"><span class="legend-swatch" style="background:${COLORS.askPool};"></span>pool asks</span>
165
+ </div>
166
+ </div>
167
+ </div>
168
+
169
+ <div id="panels">
170
+ <div id="liquidity-panel">
171
+ <div class="readout" id="readout">
172
+ <div>Price <span class="price" id="r-price">-</span> <span id="r-unit">${escapeHtml(priceLabel)}</span></div>
173
+ <table>
174
+ <thead><tr><th class="side"></th><th>book</th><th>pool</th></tr></thead>
175
+ <tbody>
176
+ <tr>
177
+ <td class="side-bid">BIDS</td>
178
+ <td id="r-book-bid" style="color:${COLORS.bidBook};">-</td>
179
+ <td id="r-pool-bid" style="color:${COLORS.bidPool};">-</td>
180
+ </tr>
181
+ <tr>
182
+ <td class="side-ask">ASKS</td>
183
+ <td id="r-book-ask" style="color:${COLORS.askBook};">-</td>
184
+ <td id="r-pool-ask" style="color:${COLORS.askPool};">-</td>
185
+ </tr>
186
+ </tbody>
187
+ </table>
188
+ <div class="spread-block">
189
+ <div class="spread-row" id="spread-book">
190
+ <span class="swatch" style="background:${COLORS.bookSpreadEdge};"></span>
191
+ <span class="spread-key">BOOK</span>
192
+ <span class="spread-pct" id="r-book-spread">-</span>
193
+ <span class="spread-tag">tighter</span>
194
+ <span class="spread-range" id="r-book-spread-range"></span>
195
+ </div>
196
+ <div class="spread-row" id="spread-pool">
197
+ <span class="swatch" style="background:${COLORS.poolSpreadEdge};"></span>
198
+ <span class="spread-key">POOL</span>
199
+ <span class="spread-pct" id="r-pool-spread">-</span>
200
+ <span class="spread-tag">tighter</span>
201
+ <span class="spread-range" id="r-pool-spread-range"></span>
202
+ </div>
203
+ </div>
204
+ <div style="color:#8b949e;font-size:11px;margin-top:3px;">depth in <span id="r-depth-unit">${escapeHtml(depthLabel)}</span> &middot; shaded bands = spreads to cross</div>
205
+ <div style="color:#8b949e;font-size:11px;">click axes: y = depth asset &middot; x = invert price</div>
206
+ </div>
207
+ <div id="liquidity-chart"></div>
208
+ </div>
209
+ </div>
210
+
211
+ <script id="payload" type="application/json">${serializeJsonForScript(payload)}</script>
212
+
213
+ <script>
214
+ (function () {
215
+ const data = JSON.parse(document.getElementById('payload').textContent);
216
+ ${embedFunctionSources([buildDepthView, formatPercentLabel, isValidNumber, safeFormat, formatCurrency, formatFundsValue])}
217
+ const fmtPrice = formatCurrency;
218
+ const fmtDepth = formatFundsValue;
219
+ const colors = data.colors;
220
+ const series = data.series;
221
+ const quoteUnit = data.quote.symbol;
222
+ const baseUnit = data.base.symbol;
223
+
224
+ // orientation: 'normal' = quote per base, 'inverted' = base per quote.
225
+ // depthMode is relative to the current orientation: 'quote' means the
226
+ // current quote asset, 'base' the current base asset.
227
+ let orientation = 'normal';
228
+ let depthMode = 'quote';
229
+ let view = null;
230
+ const guides = [];
231
+ let xMin = data.window.min;
232
+ let xMax = data.window.max;
233
+
234
+ function currentPriceUnit() {
235
+ return orientation === 'normal' ? data.priceLabel : baseUnit + ' per ' + quoteUnit;
236
+ }
237
+ function currentDepthUnit() {
238
+ if (orientation === 'normal') return depthMode === 'base' ? baseUnit : quoteUnit;
239
+ return depthMode === 'base' ? quoteUnit : baseUnit;
240
+ }
241
+
242
+ // Build the currently displayed arrays. The transform is shared with
243
+ // the Node tests (liquidity_view.ts) and embedded verbatim above.
244
+ function buildView() {
245
+ return buildDepthView(series, {
246
+ orientation: orientation,
247
+ depthMode: depthMode,
248
+ poolPrice: data.pool ? data.pool.price : null,
249
+ mid: data.book.mid,
250
+ window: data.window,
251
+ bookBestBid: data.book.bestBid,
252
+ bookBestAsk: data.book.bestAsk,
253
+ });
254
+ }
255
+ function currentChartData() {
256
+ return [view.prices, view.poolBid, view.poolAsk, view.bookBid, view.bookAsk];
257
+ }
258
+ function rebuildGuides() {
259
+ guides.length = 0;
260
+ if (view.poolPrice != null) {
261
+ guides.push({ price: view.poolPrice, color: 'rgba(230,237,243,0.85)', dash: [6, 4], label: 'POOL' });
262
+ }
263
+ if (view.mid != null) {
264
+ guides.push({ price: view.mid, color: 'rgba(196,205,216,0.9)', dash: [2, 4], label: 'BOOK MID' });
265
+ }
266
+ }
267
+ view = buildView();
268
+ rebuildGuides();
269
+ xMin = view.min;
270
+ xMax = view.max;
271
+
272
+ // ── formatting ──────────────────────────────────────────────────────
273
+ // 4-significant-digit formatting comes from modules/order/format.ts
274
+ // (formatCurrency / formatFundsValue), embedded above so generated
275
+ // charts run the same formatters as DEXBot's order logs.
276
+
277
+ // ── view range (zoom / pan) ─────────────────────────────────────────
278
+ let pendingRange = null, pendingRangeRaf = 0;
279
+ function currentX(chart) {
280
+ const s = chart.scales.x || {};
281
+ return {
282
+ min: Number.isFinite(s.min) ? s.min : xMin,
283
+ max: Number.isFinite(s.max) ? s.max : xMax,
284
+ };
285
+ }
286
+ function clampXRange(min, max) {
287
+ const full = xMax - xMin;
288
+ const minSpan = full * 0.02;
289
+ let span = max - min;
290
+ if (!Number.isFinite(span) || span <= 0) return { min: xMin, max: xMax };
291
+ span = Math.max(minSpan, Math.min(full, span));
292
+ let nextMin = min;
293
+ let nextMax = min + span;
294
+ if (nextMin < xMin) { nextMin = xMin; nextMax = xMin + span; }
295
+ if (nextMax > xMax) { nextMax = xMax; nextMin = xMax - span; }
296
+ return { min: nextMin, max: nextMax };
297
+ }
298
+ function applyXRange(chart, min, max) {
299
+ pendingRange = clampXRange(min, max);
300
+ if (pendingRangeRaf) return;
301
+ const raf = typeof requestAnimationFrame !== 'undefined'
302
+ ? requestAnimationFrame.bind(window)
303
+ : (fn) => setTimeout(fn, 0);
304
+ pendingRangeRaf = raf(() => {
305
+ const next = pendingRange;
306
+ pendingRange = null;
307
+ pendingRangeRaf = 0;
308
+ if (next) chart.setScale('x', next);
309
+ });
310
+ }
311
+
312
+ // ── guide lines + label block ───────────────────────────────────────
313
+ function drawGuides(u) {
314
+ const { ctx, bbox } = u;
315
+ const xScale = u.scales.x;
316
+ if (!xScale || !Number.isFinite(xScale.min) || !Number.isFinite(xScale.max)) return;
317
+ // uPlot leaves this context unscaled, so every coordinate here is a
318
+ // DEVICE pixel. Text sizes and paddings must be multiplied by the
319
+ // device pixel ratio or the labels render at half size on a HiDPI
320
+ // display while uPlot's own axis text stays correct.
321
+ const canvas = ctx.canvas;
322
+ const pr = canvas.width && canvas.clientWidth ? canvas.width / canvas.clientWidth : 1;
323
+ const px = (value) => value * pr;
324
+ ctx.save();
325
+ ctx.beginPath();
326
+ ctx.rect(bbox.left, bbox.top, bbox.width, bbox.height);
327
+ ctx.clip();
328
+ // Spread bands, book first then the (usually much narrower) pool fee
329
+ // band on top. Each band is filled and bounded by two edge lines so
330
+ // it stays readable when zoomed in, and the pool curves terminate at
331
+ // exactly the pool band edges (inverted view swaps the sides).
332
+ function paintBand(lo, hi, fillTop, fillBottom, edge) {
333
+ if (lo == null || hi == null || !Number.isFinite(lo) || !Number.isFinite(hi) || !(hi > lo)) return;
334
+ const x0 = u.valToPos(Math.max(lo, xScale.min), 'x', true);
335
+ const x1 = u.valToPos(Math.min(hi, xScale.max), 'x', true);
336
+ if (!(x1 > x0)) return;
337
+ const fill = ctx.createLinearGradient(0, bbox.top, 0, bbox.top + bbox.height);
338
+ fill.addColorStop(0, fillTop);
339
+ // Fade out by half height: a band wider than the viewport then
340
+ // reads as a highlight strip instead of a full-chart tint.
341
+ fill.addColorStop(0.5, fillBottom);
342
+ ctx.fillStyle = fill;
343
+ ctx.fillRect(x0, bbox.top, x1 - x0, bbox.height);
344
+ ctx.strokeStyle = edge;
345
+ ctx.lineWidth = Math.max(1, px(1));
346
+ ctx.setLineDash([px(3), px(3)]);
347
+ ctx.beginPath();
348
+ ctx.moveTo(x0, bbox.top);
349
+ ctx.lineTo(x0, bbox.top + bbox.height);
350
+ ctx.moveTo(x1, bbox.top);
351
+ ctx.lineTo(x1, bbox.top + bbox.height);
352
+ ctx.stroke();
353
+ ctx.setLineDash([]);
354
+ }
355
+ paintBand(view.bookBidPrice, view.bookAskPrice, colors.bookSpreadFillTop, colors.bookSpreadFillBottom, colors.bookSpreadEdge);
356
+ paintBand(view.poolBidPrice, view.poolAskPrice, colors.poolSpreadFillTop, colors.poolSpreadFillBottom, colors.poolSpreadEdge);
357
+ for (let i = 0; i < guides.length; i++) {
358
+ const guide = guides[i];
359
+ if (guide.price < xScale.min || guide.price > xScale.max) continue;
360
+ const x = u.valToPos(guide.price, 'x', true);
361
+ ctx.strokeStyle = guide.color;
362
+ ctx.lineWidth = Math.max(1, px(1));
363
+ ctx.setLineDash(guide.dash.map(px));
364
+ ctx.beginPath();
365
+ ctx.moveTo(x, bbox.top);
366
+ ctx.lineTo(x, bbox.top + bbox.height);
367
+ ctx.stroke();
368
+ ctx.setLineDash([]);
369
+ }
370
+ // One aligned label block, parked beside the pool fee band instead
371
+ // of on top of it, so neither the band nor the curves hide the text.
372
+ if (guides.length > 0) {
373
+ ctx.font = '600 ' + px(15) + 'px ui-monospace, SFMono-Regular, Menlo, monospace';
374
+ ctx.textAlign = 'left';
375
+ const entries = guides.map((guide) => ({
376
+ color: guide.color,
377
+ dash: guide.dash,
378
+ text: guide.label + ' ' + fmtPrice(guide.price),
379
+ }));
380
+ const swatchW = px(14);
381
+ const gap = px(9);
382
+ const pad = px(9);
383
+ const lineH = px(20);
384
+ const textW = Math.max.apply(null, entries.map((entry) => ctx.measureText(entry.text).width));
385
+ const blockW = Math.min(pad + swatchW + gap + textW + pad, bbox.width - px(12));
386
+ const blockH = pad * 2 + (entries.length - 1) * lineH + px(15);
387
+ const minLeft = bbox.left + px(6);
388
+ const maxLeft = bbox.left + bbox.width - blockW - px(6);
389
+ let left;
390
+ const bandLo = view.poolBidPrice;
391
+ const bandHi = view.poolAskPrice;
392
+ if (bandLo != null && bandHi != null && bandHi > bandLo) {
393
+ const bandLeft = Math.max(bbox.left, Math.min(u.valToPos(bandLo, 'x', true), bbox.left + bbox.width));
394
+ const bandRight = Math.max(bbox.left, Math.min(u.valToPos(bandHi, 'x', true), bbox.left + bbox.width));
395
+ left = bbox.left + bbox.width - bandRight >= blockW + px(16)
396
+ ? bandRight + px(12)
397
+ : bandLeft - px(12) - blockW;
398
+ } else {
399
+ left = maxLeft;
400
+ }
401
+ left = Math.max(minLeft, Math.min(left, maxLeft));
402
+ const top = bbox.top + px(8);
403
+ ctx.fillStyle = 'rgba(11,14,20,0.84)';
404
+ ctx.strokeStyle = 'rgba(48,54,61,0.95)';
405
+ ctx.lineWidth = Math.max(1, px(1));
406
+ ctx.beginPath();
407
+ ctx.rect(left, top, blockW, blockH);
408
+ ctx.fill();
409
+ ctx.stroke();
410
+ for (let i = 0; i < entries.length; i++) {
411
+ const baseY = top + pad + px(11) + i * lineH;
412
+ ctx.strokeStyle = entries[i].color;
413
+ ctx.lineWidth = Math.max(1, px(1));
414
+ ctx.setLineDash(entries[i].dash.map(px));
415
+ ctx.beginPath();
416
+ ctx.moveTo(left + pad, baseY - px(5));
417
+ ctx.lineTo(left + pad + swatchW, baseY - px(5));
418
+ ctx.stroke();
419
+ ctx.setLineDash([]);
420
+ ctx.fillStyle = entries[i].color;
421
+ ctx.fillText(entries[i].text, left + pad + swatchW + gap, baseY);
422
+ }
423
+ }
424
+ ctx.restore();
425
+ }
426
+
427
+ // ── chart ───────────────────────────────────────────────────────────
428
+ const chartEl = document.getElementById('liquidity-panel');
429
+ const chart = new uPlot({
430
+ width: chartEl.offsetWidth,
431
+ height: chartEl.offsetHeight,
432
+ padding: [10, 44, 10, 8],
433
+ legend: { show: false },
434
+ select: { show: false },
435
+ cursor: {
436
+ show: true,
437
+ x: true,
438
+ y: false,
439
+ points: { show: false },
440
+ drag: { x: false, y: false, setScale: false },
441
+ focus: { prox: -1 },
442
+ },
443
+ scales: {
444
+ x: { time: false },
445
+ y: {
446
+ auto: true,
447
+ range: (u, min, max) => [0, Number.isFinite(max) && max > 0 ? max * 1.08 : 1],
448
+ },
449
+ },
450
+ series: [
451
+ { label: 'Price' },
452
+ { label: 'Pool bids', stroke: colors.bidPool, width: 1.5, fill: 'rgba(88,166,255,0.09)', points: { show: false } },
453
+ { label: 'Pool asks', stroke: colors.askPool, width: 1.5, fill: 'rgba(210,168,255,0.09)', points: { show: false } },
454
+ { label: 'Book bids', stroke: colors.bidBook, width: 1.6, dash: [4, 3], fill: 'rgba(63,185,80,0.10)', points: { show: false } },
455
+ { label: 'Book asks', stroke: colors.askBook, width: 1.6, dash: [4, 3], fill: 'rgba(248,81,73,0.10)', points: { show: false } },
456
+ ],
457
+ axes: [
458
+ {
459
+ stroke: '#ffffff',
460
+ grid: { stroke: '#1c2128' },
461
+ ticks: { stroke: '#30363d', width: 1 },
462
+ size: 34,
463
+ font: '13px Segoe UI, sans-serif',
464
+ label: 'Price (' + currentPriceUnit() + ')',
465
+ labelSize: 20,
466
+ labelFont: '12px Segoe UI, sans-serif',
467
+ values: (u, splits) => splits.map((v) => fmtPrice(v)),
468
+ },
469
+ {
470
+ side: 1,
471
+ stroke: '#ffffff',
472
+ grid: { stroke: '#1c2128', dash: [4, 4] },
473
+ ticks: { stroke: '#30363d', width: 1 },
474
+ size: 70,
475
+ font: '13px Segoe UI, sans-serif',
476
+ label: 'Cumulative depth (' + currentDepthUnit() + ')',
477
+ labelSize: 20,
478
+ labelFont: '12px Segoe UI, sans-serif',
479
+ values: (u, splits) => splits.map((v) => fmtDepth(v)),
480
+ },
481
+ ],
482
+ hooks: { draw: [drawGuides] },
483
+ }, currentChartData(), document.getElementById('liquidity-chart'));
484
+
485
+ // ── cursor readout ──────────────────────────────────────────────────
486
+ function nearestIndex(price) {
487
+ const prices = view.prices;
488
+ let lo = 0, hi = prices.length - 1;
489
+ while (lo < hi) {
490
+ const mid = (lo + hi) >> 1;
491
+ if (prices[mid] < price) lo = mid + 1;
492
+ else hi = mid;
493
+ }
494
+ if (lo > 0 && Math.abs(prices[lo - 1] - price) <= Math.abs(prices[lo] - price)) return lo - 1;
495
+ return lo;
496
+ }
497
+ function setText(id, value) {
498
+ const el = document.getElementById(id);
499
+ if (el) el.textContent = value;
500
+ }
501
+
502
+ // Spread comparison: the book's own bid/ask gap next to the pool fee
503
+ // band, so the cheaper entry is obvious without reading two badges.
504
+ function updateSpreads() {
505
+ const rows = [
506
+ { row: 'spread-book', pct: 'r-book-spread', range: 'r-book-spread-range',
507
+ lo: view.bookBidPrice, hi: view.bookAskPrice, value: null },
508
+ { row: 'spread-pool', pct: 'r-pool-spread', range: 'r-pool-spread-range',
509
+ lo: view.poolBidPrice, hi: view.poolAskPrice, value: null },
510
+ ];
511
+ for (const r of rows) {
512
+ r.value = r.lo != null && r.hi != null && r.lo > 0 && r.hi > r.lo
513
+ ? ((r.hi - r.lo) / r.hi) * 100
514
+ : null;
515
+ }
516
+ // Only call one of them "tighter" when both are measurable.
517
+ const comparable = rows.every((r) => r.value != null);
518
+ const tightest = comparable ? Math.min(rows[0].value, rows[1].value) : null;
519
+ for (const r of rows) {
520
+ setText(r.pct, r.value != null ? formatPercentLabel(r.value) : '—');
521
+ setText(r.range, r.lo != null && r.hi != null && r.hi > r.lo
522
+ ? fmtPrice(r.lo) + ' – ' + fmtPrice(r.hi)
523
+ : '');
524
+ const rowEl = document.getElementById(r.row);
525
+ if (rowEl) rowEl.classList.toggle('is-tighter', tightest != null && r.value <= tightest + 1e-12);
526
+ }
527
+ }
528
+ function updateReadout(idx) {
529
+ if (idx == null || idx < 0 || idx >= view.prices.length) {
530
+ // Park the readout on the best bid (top-of-book depth) rather
531
+ // than the pool price: the pool price sits inside the fee band,
532
+ // where both pool sides are legitimately zero, which reads as an
533
+ // empty readout on first paint.
534
+ const anchor = view.bookBidPrice != null
535
+ ? view.bookBidPrice
536
+ : (view.poolPrice != null ? view.poolPrice : (view.mid != null ? view.mid : view.min));
537
+ idx = nearestIndex(anchor);
538
+ }
539
+ setText('r-price', fmtPrice(view.prices[idx]));
540
+ setText('r-book-bid', fmtDepth(view.bookBid[idx]));
541
+ setText('r-pool-bid', fmtDepth(view.poolBid[idx]));
542
+ setText('r-book-ask', fmtDepth(view.bookAsk[idx]));
543
+ setText('r-pool-ask', fmtDepth(view.poolAsk[idx]));
544
+ }
545
+
546
+ function updateHeaderPrices() {
547
+ if (view.poolPrice != null) setText('badge-pool-price', fmtPrice(view.poolPrice) + ' ' + currentPriceUnit());
548
+ if (view.mid != null) setText('badge-mid', 'BOOK MID ' + fmtPrice(view.mid));
549
+ }
550
+
551
+ // ── axis toggles (y = depth asset, x = invert price) ────────────────
552
+ function inYAxisZone(e) {
553
+ const over = chart.over && chart.over.getBoundingClientRect();
554
+ return !!over && e.clientX >= over.right - 2;
555
+ }
556
+ function inXAxisZone(e) {
557
+ const over = chart.over && chart.over.getBoundingClientRect();
558
+ return !!over && e.clientY >= over.bottom - 2;
559
+ }
560
+ function maxOf(arrays) {
561
+ let max = 0;
562
+ for (const arr of arrays) {
563
+ for (const v of arr) if (Number.isFinite(v) && v > max) max = v;
564
+ }
565
+ return max;
566
+ }
567
+ function applyView() {
568
+ view = buildView();
569
+ xMin = view.min;
570
+ xMax = view.max;
571
+ chart.setData(currentChartData());
572
+ chart.axes[0].label = 'Price (' + currentPriceUnit() + ')';
573
+ chart.axes[1].label = 'Cumulative depth (' + currentDepthUnit() + ')';
574
+ rebuildGuides();
575
+ // setSize re-lays out the axis labels; it also redraws the chart.
576
+ chart.setSize({ width: chartEl.offsetWidth, height: chartEl.offsetHeight });
577
+ const maxY = maxOf([view.bookBid, view.poolBid, view.bookAsk, view.poolAsk]);
578
+ chart.setScale('y', { min: 0, max: Number.isFinite(maxY) && maxY > 0 ? maxY * 1.08 : 1 });
579
+ chart.setScale('x', { min: xMin, max: xMax });
580
+ setText('r-unit', currentPriceUnit());
581
+ setText('r-depth-unit', currentDepthUnit());
582
+ updateHeaderPrices();
583
+ updateSpreads();
584
+ updateReadout(null);
585
+ }
586
+ // Axis clicks toggle, but a drag that starts on an axis gutter must not
587
+ // be mistaken for a click when the mouse is released.
588
+ let pointerDownX = 0;
589
+ let pointerDownY = 0;
590
+ chart.root.addEventListener('click', (e) => {
591
+ if (Math.hypot(e.clientX - pointerDownX, e.clientY - pointerDownY) > 4) return;
592
+ if (inYAxisZone(e)) {
593
+ depthMode = depthMode === 'quote' ? 'base' : 'quote';
594
+ applyView();
595
+ return;
596
+ }
597
+ if (inXAxisZone(e)) {
598
+ orientation = orientation === 'normal' ? 'inverted' : 'normal';
599
+ applyView();
600
+ }
601
+ });
602
+ updateHeaderPrices();
603
+ updateSpreads();
604
+
605
+ let leavePending = null;
606
+ chart.over.addEventListener('mousemove', () => {
607
+ if (leavePending !== null) { clearTimeout(leavePending); leavePending = null; }
608
+ updateReadout(chart.cursor.idx);
609
+ });
610
+ chart.over.addEventListener('mouseleave', () => {
611
+ leavePending = setTimeout(() => { leavePending = null; updateReadout(null); }, 60);
612
+ });
613
+
614
+ // ── zoom / pan / reset ──────────────────────────────────────────────
615
+ chart.root.addEventListener('wheel', (e) => {
616
+ if (e.ctrlKey || e.metaKey || e.altKey) return;
617
+ e.preventDefault();
618
+ e.stopPropagation();
619
+ const rect = chart.root.getBoundingClientRect();
620
+ const left = e.clientX - rect.left - (chart.bbox.left / (chart.pxRatio || 1));
621
+ const center = chart.posToVal(left, 'x');
622
+ const current = currentX(chart);
623
+ const span = current.max - current.min;
624
+ if (!Number.isFinite(span) || span <= 0) return;
625
+ const factor = e.deltaY < 0 ? 0.85 : 1.15;
626
+ const nextSpan = Math.max((xMax - xMin) * 0.02, Math.min(xMax - xMin, span * factor));
627
+ const ratio = (center - current.min) / span;
628
+ applyXRange(chart, center - nextSpan * ratio, center - nextSpan * ratio + nextSpan);
629
+ }, { passive: false });
630
+
631
+ chart.root.addEventListener('dblclick', () => {
632
+ chart.setScale('x', { min: xMin, max: xMax });
633
+ });
634
+
635
+ let dragging = false;
636
+ let dragStartX = 0;
637
+ let dragStartMin = xMin;
638
+ let dragStartMax = xMax;
639
+ let xUnitsPerPx = 0;
640
+ function endDrag() {
641
+ if (!dragging) return;
642
+ dragging = false;
643
+ document.body.style.cursor = '';
644
+ window.removeEventListener('mousemove', onMouseMove);
645
+ window.removeEventListener('mouseup', endDrag);
646
+ }
647
+ function onMouseMove(e) {
648
+ if (!dragging) return;
649
+ e.preventDefault();
650
+ const deltaPx = e.clientX - dragStartX;
651
+ applyXRange(chart, dragStartMin - deltaPx * xUnitsPerPx, dragStartMax - deltaPx * xUnitsPerPx);
652
+ }
653
+ chart.root.addEventListener('mousedown', (e) => {
654
+ if (!e || e.button !== 0 || e.ctrlKey || e.metaKey || e.altKey) return;
655
+ pointerDownX = e.clientX;
656
+ pointerDownY = e.clientY;
657
+ const rect = chart.root.getBoundingClientRect();
658
+ if (e.clientX < rect.left || e.clientX > rect.right || e.clientY < rect.top || e.clientY > rect.bottom) return;
659
+ // Axis gutters are click zones (y = depth asset, x = invert price), not pan.
660
+ const overRect = chart.over && chart.over.getBoundingClientRect();
661
+ if (overRect && (e.clientX >= overRect.right - 2 || e.clientY >= overRect.bottom - 2)) return;
662
+ e.preventDefault();
663
+ e.stopPropagation();
664
+ dragging = true;
665
+ dragStartX = e.clientX;
666
+ const current = currentX(chart);
667
+ dragStartMin = current.min;
668
+ dragStartMax = current.max;
669
+ xUnitsPerPx = (current.max - current.min) / (chart.bbox.width / (chart.pxRatio || 1));
670
+ document.body.style.cursor = 'grabbing';
671
+ window.addEventListener('mousemove', onMouseMove);
672
+ window.addEventListener('mouseup', endDrag, { once: true });
673
+ });
674
+ window.addEventListener('blur', endDrag);
675
+ window.addEventListener('keydown', (e) => {
676
+ if ((e.ctrlKey || e.metaKey) && e.key === '0') chart.setScale('x', { min: xMin, max: xMax });
677
+ });
678
+
679
+ // ── resize ──────────────────────────────────────────────────────────
680
+ function sizeChart() {
681
+ chart.setSize({ width: chartEl.offsetWidth, height: chartEl.offsetHeight });
682
+ }
683
+ window.addEventListener('resize', sizeChart);
684
+ sizeChart();
685
+ updateReadout(null);
686
+ requestAnimationFrame(() => requestAnimationFrame(sizeChart));
687
+ })();
688
+ </script>
689
+ </body>
690
+ </html>`;
691
+ }
692
+ export { generateLiquidityHTML };
693
+ //# sourceMappingURL=liquidity_chart_generator.js.map