dexbot 1.6.14 → 1.6.16

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 (134) hide show
  1. package/CHANGELOG.md +60 -4
  2. package/README.md +4 -4
  3. package/analysis/README.md +6 -6
  4. package/analysis/tradingview/README.md +2 -1
  5. package/claw/README.md +7 -7
  6. package/claw/docs/DEXBOT2_TUNING_CHEAT_SHEET.md +3 -2
  7. package/claw/modules/chain_queries.ts +3 -3
  8. package/claw/package.json +1 -1
  9. package/claw/runtimes/openclaw-plugin/openclaw.plugin.json +1 -1
  10. package/claw/runtimes/openclaw-plugin/package.json +1 -1
  11. package/dist/analysis/ama_fitting/fetch_lp_candles.js +8 -1
  12. package/dist/analysis/ama_fitting/optimizer_high_resolution.d.ts +50 -1
  13. package/dist/analysis/ama_fitting/optimizer_high_resolution.js +33 -7
  14. package/dist/analysis/bot_fitting/backtest_bot_fitting.d.ts +8 -6
  15. package/dist/analysis/bot_fitting/backtest_bot_fitting.js +8 -10
  16. package/dist/analysis/bot_key_utils.js +9 -7
  17. package/dist/analysis/chart_utils.d.ts +9 -2
  18. package/dist/analysis/chart_utils.js +51 -1
  19. package/dist/analysis/tradingview/tradingview_uplot_chart_generator.d.ts +2 -1
  20. package/dist/analysis/tradingview/tradingview_uplot_chart_generator.js +99 -11
  21. package/dist/analysis/trend_detection/dynamic_weight_chart_generator.js +57 -4
  22. package/dist/analysis/trend_detection/kalman_chart_generator.js +1 -0
  23. package/dist/analysis/trend_detection/regime_chart_generator.js +1 -1
  24. package/dist/analysis/trend_detection/volatility_chart_generator.js +1 -0
  25. package/dist/dexbot.js +112 -141
  26. package/dist/market_adapter/core/strategies/dynamic_weight_series.js +26 -11
  27. package/dist/market_adapter/inputs/fetch_book_data.js +36 -12
  28. package/dist/market_adapter/inputs/fetch_lp_data.d.ts +6 -0
  29. package/dist/market_adapter/inputs/fetch_lp_data.js +65 -19
  30. package/dist/market_adapter/inputs/kibana_feed_source.js +45 -12
  31. package/dist/market_adapter/inputs/window_cache.d.ts +14 -1
  32. package/dist/market_adapter/inputs/window_cache.js +53 -17
  33. package/dist/market_adapter/lp_chart_core.js +1 -0
  34. package/dist/market_adapter/utils/chain.js +4 -3
  35. package/dist/market_adapter/utils/pair_orientation.d.ts +60 -0
  36. package/dist/market_adapter/utils/pair_orientation.js +142 -0
  37. package/dist/modules/account_bots.d.ts +40 -3
  38. package/dist/modules/account_bots.js +80 -37
  39. package/dist/modules/account_orders.d.ts +4 -1
  40. package/dist/modules/account_orders.js +4 -1
  41. package/dist/modules/bitshares-native/resolvers.js +3 -3
  42. package/dist/modules/bitshares-native/subscriptions.js +1 -1
  43. package/dist/modules/bitshares_client.d.ts +12 -10
  44. package/dist/modules/bitshares_client.js +12 -10
  45. package/dist/modules/bot_defaults.d.ts +13 -2
  46. package/dist/modules/bot_defaults.js +31 -2
  47. package/dist/modules/bot_settings.js +6 -3
  48. package/dist/modules/chain_keys.d.ts +5 -1
  49. package/dist/modules/chain_keys.js +5 -1
  50. package/dist/modules/chain_orders.d.ts +6 -2
  51. package/dist/modules/chain_orders.js +6 -2
  52. package/dist/modules/constants.d.ts +11 -0
  53. package/dist/modules/constants.js +31 -1
  54. package/dist/modules/credit_runtime.d.ts +35 -5
  55. package/dist/modules/credit_runtime.js +219 -38
  56. package/dist/modules/dexbot_class.d.ts +22 -2
  57. package/dist/modules/dexbot_class.js +61 -21
  58. package/dist/modules/dexbot_cow_runtime.js +19 -18
  59. package/dist/modules/dexbot_fill_runtime.d.ts +1 -1
  60. package/dist/modules/dexbot_fill_runtime.js +4 -7
  61. package/dist/modules/dexbot_maintenance_runtime.d.ts +7 -2
  62. package/dist/modules/dexbot_maintenance_runtime.js +52 -7
  63. package/dist/modules/dexbot_startup_runtime.js +3 -2
  64. package/dist/modules/dexbot_state_recovery.js +1 -1
  65. package/dist/modules/graceful_shutdown.d.ts +6 -2
  66. package/dist/modules/graceful_shutdown.js +6 -2
  67. package/dist/modules/launcher/bot_supervisor.js +4 -0
  68. package/dist/modules/launcher/launch_modes.js +6 -3
  69. package/dist/modules/launcher/monolithic_runtime.d.ts +39 -1
  70. package/dist/modules/launcher/monolithic_runtime.js +60 -1
  71. package/dist/modules/launcher/runtime_mode.d.ts +79 -0
  72. package/dist/modules/launcher/runtime_mode.js +223 -0
  73. package/dist/modules/market_adapter_whitelist.d.ts +8 -0
  74. package/dist/modules/market_adapter_whitelist.js +8 -0
  75. package/dist/modules/order/accounting.d.ts +15 -1
  76. package/dist/modules/order/accounting.js +15 -1
  77. package/dist/modules/order/async_lock.d.ts +9 -3
  78. package/dist/modules/order/async_lock.js +9 -3
  79. package/dist/modules/order/export.d.ts +0 -5
  80. package/dist/modules/order/export.js +2 -7
  81. package/dist/modules/order/format.d.ts +6 -4
  82. package/dist/modules/order/format.js +6 -4
  83. package/dist/modules/order/grid.d.ts +147 -19
  84. package/dist/modules/order/grid.js +321 -68
  85. package/dist/modules/order/grid_reconcile.js +4 -3
  86. package/dist/modules/order/grid_reconcile_internal.js +13 -18
  87. package/dist/modules/order/index.d.ts +4 -2
  88. package/dist/modules/order/index.js +1 -1
  89. package/dist/modules/order/logger_state.d.ts +1 -1
  90. package/dist/modules/order/logger_state.js +1 -1
  91. package/dist/modules/order/manager.d.ts +1 -0
  92. package/dist/modules/order/manager.js +5 -14
  93. package/dist/modules/order/sync_engine.d.ts +26 -11
  94. package/dist/modules/order/sync_engine.js +44 -20
  95. package/dist/modules/order/utils/math.d.ts +157 -47
  96. package/dist/modules/order/utils/math.js +236 -78
  97. package/dist/modules/order/utils/order.d.ts +64 -20
  98. package/dist/modules/order/utils/order.js +80 -24
  99. package/dist/modules/order/utils/system.d.ts +41 -11
  100. package/dist/modules/order/utils/system.js +43 -13
  101. package/dist/modules/order/utils/validate.d.ts +6 -3
  102. package/dist/modules/order/utils/validate.js +53 -60
  103. package/dist/modules/types.d.ts +7 -0
  104. package/dist/modules/utils/asset_symbols.d.ts +5 -5
  105. package/dist/modules/utils/asset_symbols.js +5 -5
  106. package/dist/modules/utils/errors.d.ts +2 -1
  107. package/dist/modules/utils/errors.js +2 -1
  108. package/dist/scripts/analyze-credit.js +44 -27
  109. package/dist/scripts/diagnose-pool-history.js +35 -30
  110. package/dist/scripts/pnl.js +1 -1
  111. package/dist/scripts/rich_list.d.ts +50 -0
  112. package/dist/scripts/rich_list.js +469 -0
  113. package/dist/scripts/run-tests.js +80 -4
  114. package/dist/unlock.d.ts +2 -1
  115. package/dist/unlock.js +53 -21
  116. package/docs/BITSHARES_ONBOARDING.md +7 -0
  117. package/docs/COW_INVARIANTS.md +7 -1
  118. package/docs/DEXBOT_COMPARISON.md +6 -6
  119. package/docs/EVOLUTION.md +11 -9
  120. package/docs/FUND_MOVEMENT_AND_ACCOUNTING.md +3 -3
  121. package/docs/GRID_RECALCULATION.md +18 -6
  122. package/docs/LIFECYCLE.md +8 -8
  123. package/docs/LOGGING.md +16 -1
  124. package/docs/MPA_CREDIT_USAGE.md +10 -5
  125. package/docs/ORDER_ENGINE_POST_1.0_RETROSPECTIVE.md +163 -13
  126. package/docs/README.md +1 -1
  127. package/docs/WORKFLOW.md +6 -5
  128. package/docs/architecture.md +56 -2
  129. package/docs/developer_guide.md +5 -1
  130. package/market_adapter/README.md +14 -7
  131. package/modules/README.md +1 -1
  132. package/package.json +4 -1
  133. package/scripts/README.md +59 -32
  134. package/tests/README.md +40 -2
@@ -45,10 +45,6 @@ const DEFAULT_BTS_FEE_CAPITAL = 10000;
45
45
  // DYNAMIC_WEIGHT_AMA_LOOKBACK_BARS (computeHuberWindowSlopePct) and the
46
46
  // baseline mirrors botState.gridRangeScalingAmaSlope (re-seeded every reset).
47
47
  const SLOPE_NEUTRAL_ZONE_PCT = MARKET_ADAPTER.DYNAMIC_WEIGHT_AMA_NEUTRAL_ZONE_PCT;
48
- // Spread-gap floor knobs (GRID_LIMITS): the effective target spread is
49
- // clamped up to incrementPercent × MIN_SPREAD_FACTOR and the gap is never
50
- // narrower than MIN_SPREAD_ORDERS slots — mirrored from calculateGapSlots
51
- // (modules/order/utils/math.ts).
52
48
  const RISK_W_DURATION = 1.0; // avg open bars
53
49
  const RISK_W_PEAK_OPEN = 2.0; // peak simultaneous open orders
54
50
  const RISK_W_IMBALANCE = 1.2; // avg |openBuy-openSell|
@@ -171,7 +167,7 @@ function resolveAutoResultsPath(dataPath) {
171
167
  }
172
168
  /**
173
169
  * Spread-gap width in slots — direct port of calculateGapSlots
174
- * (modules/order/utils/math.ts:1228). The effective target spread is clamped
170
+ * (modules/order/utils/math.ts). The effective target spread is clamped
175
171
  * up to incrementPercent × MIN_SPREAD_FACTOR and the gap never drops below
176
172
  * MIN_SPREAD_ORDERS slots. `incrementPercent`/`targetSpreadPercent` in PERCENT
177
173
  * units, matching the production signature.
@@ -185,7 +181,7 @@ function computeGapSlots(incrementPercent, targetSpreadPercent) {
185
181
  }
186
182
  /**
187
183
  * Slope-ratio grid price offset — port of computeGridPriceOffsetPlan
188
- * (market_adapter/core/market_adapter_service.ts:92-119) combined with the
184
+ * (market_adapter/core/market_adapter_service.ts) combined with the
189
185
  * trend/slopeRatio semantics of computeAmaSlopeWeights
190
186
  * (market_adapter/core/strategies/ama_slope_model.ts):
191
187
  *
@@ -194,8 +190,9 @@ function computeGapSlots(incrementPercent, targetSpreadPercent) {
194
190
  * direction = sign(slopePct) (0 inside the neutral zone)
195
191
  * offsetPct = direction × slopeRatio × maxGridPriceOffsetPct
196
192
  *
197
- * Production applies this to startPrice (grid.ts:982: startPrice × (1 +
198
- * offset/100)) only for asymmetricBounds-whitelisted bots; the sim applies it
193
+ * Production applies this to startPrice (modules/order/grid.ts,
194
+ * initializeGrid: startPrice × (1 + offset/100)) only for
195
+ * asymmetricBounds-whitelisted bots; the sim applies it
199
196
  * to the placement center on every grid build when asymmetricBounds is on.
200
197
  */
201
198
  function computeGridPriceOffsetPct(slopePct, targetSpreadPercent) {
@@ -211,11 +208,12 @@ function computeGridPriceOffsetPct(slopePct, targetSpreadPercent) {
211
208
  }
212
209
  /**
213
210
  * Build a persistent grid with FIXED chain prices from a master rail —
214
- * port of createOrderGrid (modules/order/grid.ts:374-505):
211
+ * port of createOrderGrid (modules/order/grid.ts):
215
212
  *
216
213
  * - Master rail: geometric progression starting at √(1±inc) × center and
217
214
  * expanding by (1±inc) steps outward, bounded by
218
- * [center/maxMinRatio, center×maxMinRatio] (grid.ts:428-444).
215
+ * [center/maxMinRatio, center×maxMinRatio] (rail expansion:
216
+ * derivePriceLevels in modules/order/utils/math.ts).
219
217
  * - Spread gap: gapSlots empty slots centered on the center price
220
218
  * (calculateIdealBoundary: boundaryIdx = splitIdx − floor(gap/2) − 1;
221
219
  * sells start at boundaryIdx + gapSlots + 1).
@@ -468,7 +468,8 @@ function resolveAmaConfig(botKey) {
468
468
  const isAmaKeyword = AMA_KEYWORDS.has(rawGridPrice);
469
469
  const botAmaInline = (botMeta.ama && typeof botMeta.ama === 'object') ? botMeta.ama : null;
470
470
  // Priority: inline bot.ama overrides market profile for analysis visibility.
471
- // Production inverts this (profiles first, inline as fallback — market_adapter.ts:694-730).
471
+ // Production inverts this (profiles first, inline as fallback —
472
+ // resolveAmaForBot in market_adapter.ts).
472
473
  if (botAmaInline) {
473
474
  const cfg = {
474
475
  erPeriod: Number(botAmaInline.erPeriod),
@@ -501,13 +502,14 @@ function resolveAmaConfig(botKey) {
501
502
  return cfg;
502
503
  }
503
504
  const marketProfiles = loadMarketProfiles();
504
- // Pair match is case-insensitive: market_profiles.json and bots.json are
505
- // hand-edited, and a case-only difference must not silently drop the
506
- // profile (a strict === here made the AMA/grid config vanish).
505
+ // Pair match is case-insensitive AND orientation-insensitive: a profile may
506
+ // have been fitted from either side of the pair (the candle cache stores
507
+ // canonically). Matching only the bot's typed order would silently drop the
508
+ // profile and fall back to builtin AMA defaults.
507
509
  const selectedProfile = (marketProfiles?.profiles
508
- ? marketProfiles.profiles.find((entry) => isSameAssetSymbol(entry.assetA, botMeta.assetA) &&
509
- isSameAssetSymbol(entry.assetB, botMeta.assetB) &&
510
- Number(entry.intervalSeconds) === 3600)
510
+ ? marketProfiles.profiles.find((entry) => Number(entry.intervalSeconds) === 3600 &&
511
+ ((isSameAssetSymbol(entry.assetA, botMeta.assetA) && isSameAssetSymbol(entry.assetB, botMeta.assetB)) ||
512
+ (isSameAssetSymbol(entry.assetA, botMeta.assetB) && isSameAssetSymbol(entry.assetB, botMeta.assetA))))
511
513
  : null);
512
514
  if (selectedProfile?.amas) {
513
515
  const fallbackKey = selectedProfile.defaultAma || DEFAULT_AMA_KEY;
@@ -33,6 +33,13 @@ declare function embedFunctionSources(fns: Array<Function>): string;
33
33
  * Consumers must define `xMin`, `xMax`, `charts`, `pendingRange`, and `pendingRangeRaf`
34
34
  * before embedding this script block.
35
35
  */
36
- declare const UPLOT_SHARED_SCRIPT = "\nfunction clampXRange(min, max) {\n let nextMin = min, nextMax = max;\n if (!Number.isFinite(nextMin) || !Number.isFinite(nextMax) || nextMax <= nextMin) {\n return { min: xMin, max: xMax };\n }\n if (nextMin < xMin) { nextMax += xMin - nextMin; nextMin = xMin; }\n if (nextMax > xMax) { nextMin -= nextMax - xMax; nextMax = xMax; }\n if (nextMin < xMin) nextMin = xMin;\n if (nextMax > xMax) nextMax = xMax;\n if (nextMax <= nextMin) return { min: xMin, max: xMax };\n return { min: nextMin, max: nextMax };\n}\n\nfunction syncXRange(min, max) {\n pendingRange = clampXRange(min, max);\n if (pendingRangeRaf) return;\n const raf = typeof requestAnimationFrame !== 'undefined' ? requestAnimationFrame.bind(window) : (fn) => setTimeout(fn, 0);\n pendingRangeRaf = raf(() => {\n const next = pendingRange;\n pendingRange = null;\n pendingRangeRaf = 0;\n if (!next) return;\n charts.forEach(c => c && c.batch(() => c.setScale('x', next)));\n });\n}\n\nfunction bindWheelZoom(chart) {\n chart.root.addEventListener('wheel', (e) => {\n if (e.ctrlKey || e.metaKey || e.altKey) return;\n e.preventDefault();\n e.stopPropagation();\n const rect = chart.root.getBoundingClientRect();\n \n // Correctly calculate plot-relative 'left' for accurate centering\n const left = e.clientX - rect.left - (chart.bbox.left / (chart.pxRatio || 1));\n const center = chart.posToVal(left, 'x');\n \n const s = chart.scales.x || {};\n const currMin = Number.isFinite(s.min) ? s.min : xMin;\n const currMax = Number.isFinite(s.max) ? s.max : xMax;\n const span = currMax - currMin;\n if (!Number.isFinite(span) || span <= 0) return;\n const factor = e.deltaY < 0 ? 0.85 : 1.15;\n const nextSpan = Math.max(1, Math.min(xMax - xMin, span * factor));\n const ratio = (center - currMin) / span;\n syncXRange(center - nextSpan * ratio, center - nextSpan * ratio + nextSpan);\n }, { passive: false });\n}\n\nfunction bindPan(chart) {\n let dragging = false, startClientX = 0, startClientY = 0, startMin = xMin, startMax = xMax, xUnitsPerPx = 0;\n const getScale = () => {\n const s = chart.scales.x || {};\n return { currMin: Number.isFinite(s.min) ? s.min : xMin, currMax: Number.isFinite(s.max) ? s.max : xMax };\n };\n const onMouseMove = (e) => {\n if (!dragging) return;\n \n // Ignore if vertical movement is dominant (likely scrolling)\n if (Math.abs(e.clientY - startClientY) > 20) return;\n \n e.preventDefault();\n const deltaPx = e.clientX - startClientX;\n const deltaVal = deltaPx * xUnitsPerPx;\n syncXRange(startMin - deltaVal, startMax - deltaVal);\n };\n const endDrag = () => {\n if (!dragging) return;\n dragging = false;\n document.body.style.cursor = '';\n window.removeEventListener('mousemove', onMouseMove);\n window.removeEventListener('mouseup', endDrag);\n };\n chart.root.addEventListener('mousedown', (e) => {\n if (!e || e.button !== 0 || e.ctrlKey || e.metaKey || e.altKey) return;\n const rect = chart.root.getBoundingClientRect();\n if (e.clientX < rect.left || e.clientX > rect.right || e.clientY < rect.top || e.clientY > rect.bottom) return;\n \n e.preventDefault();\n e.stopPropagation();\n \n dragging = true;\n startClientX = e.clientX;\n startClientY = e.clientY;\n const cur = getScale();\n startMin = cur.currMin; startMax = cur.currMax;\n \n // Calculate units per pixel once at start of drag to avoid sliding bug\n // chart.bbox.width is in device pixels; divide by pxRatio for CSS pixels\n xUnitsPerPx = (cur.currMax - cur.currMin) / (chart.bbox.width / (chart.pxRatio || 1));\n \n document.body.style.cursor = 'grabbing';\n window.addEventListener('mousemove', onMouseMove);\n window.addEventListener('mouseup', endDrag, { once: true });\n });\n\n // Keep the grab cursor while dragging even as the pointer leaves the plot,\n // and end the drag if the window loses focus mid-drag (otherwise the chart\n // keeps panning on the next mousemove after refocus).\n chart.root.addEventListener('mouseleave', () => {\n if (!dragging) return;\n document.body.style.cursor = 'grabbing';\n });\n window.addEventListener('blur', endDrag);\n}\n";
37
- export { escapeHtml, serializeJsonForScript, toEpochSeconds, writeChartFile, toFileUrl, embedFunctionSources, UPLOT_SHARED_SCRIPT, uplotInlineTags };
36
+ declare const UPLOT_SHARED_SCRIPT = "\nfunction clampXRange(min, max) {\n let nextMin = min, nextMax = max;\n if (!Number.isFinite(nextMin) || !Number.isFinite(nextMax) || nextMax <= nextMin) {\n return { min: xMin, max: xMax };\n }\n if (nextMin < xMin) { nextMax += xMin - nextMin; nextMin = xMin; }\n if (nextMax > xMax) { nextMin -= nextMax - xMax; nextMax = xMax; }\n if (nextMin < xMin) nextMin = xMin;\n if (nextMax > xMax) nextMax = xMax;\n if (nextMax <= nextMin) return { min: xMin, max: xMax };\n return { min: nextMin, max: nextMax };\n}\n\n// Safe tick generator for uPlot log axes (scale distr: 3). uPlot 1.6.32's\n// built-in log splits (Je) can loop forever on a narrow price range: its step\n// is reassigned to an intermediate tick that is missing from the nice-number\n// cache, so subsequent rounding collapses the step to 0 and the tick array\n// grows until the engine throws \"Invalid array length\" / runs out of memory\n// (browser tab hang). Emitting only 1/2/5 x 10^d values inside [min, max]\n// never diverges. Assigned per-axis via `splits: logAxisSplits`.\nfunction logAxisSplits(u, axisIdx, min, max) {\n const out = [];\n if (!(min > 0) || !(max > min)) return out;\n const lo = Math.floor(Math.log10(min));\n const hi = Math.ceil(Math.log10(max));\n const mults = [1, 2, 5];\n for (let d = lo; d <= hi; d++) {\n const base = Math.pow(10, d);\n for (let m = 0; m < mults.length; m++) {\n const v = mults[m] * base;\n if (v >= min && v <= max) out.push(v);\n }\n }\n return out.length >= 2 ? out : [min, max];\n}\n\nfunction syncXRange(min, max) {\n pendingRange = clampXRange(min, max);\n if (pendingRangeRaf) return;\n const raf = typeof requestAnimationFrame !== 'undefined' ? requestAnimationFrame.bind(window) : (fn) => setTimeout(fn, 0);\n pendingRangeRaf = raf(() => {\n const next = pendingRange;\n pendingRange = null;\n pendingRangeRaf = 0;\n if (!next) return;\n charts.forEach(c => c && c.batch(() => c.setScale('x', next)));\n });\n}\n\nfunction bindWheelZoom(chart) {\n chart.root.addEventListener('wheel', (e) => {\n if (e.ctrlKey || e.metaKey || e.altKey) return;\n e.preventDefault();\n e.stopPropagation();\n const rect = chart.root.getBoundingClientRect();\n \n // Correctly calculate plot-relative 'left' for accurate centering\n const left = e.clientX - rect.left - (chart.bbox.left / (chart.pxRatio || 1));\n const center = chart.posToVal(left, 'x');\n \n const s = chart.scales.x || {};\n const currMin = Number.isFinite(s.min) ? s.min : xMin;\n const currMax = Number.isFinite(s.max) ? s.max : xMax;\n const span = currMax - currMin;\n if (!Number.isFinite(span) || span <= 0) return;\n const factor = e.deltaY < 0 ? 0.85 : 1.15;\n const nextSpan = Math.max(1, Math.min(xMax - xMin, span * factor));\n const ratio = (center - currMin) / span;\n syncXRange(center - nextSpan * ratio, center - nextSpan * ratio + nextSpan);\n }, { passive: false });\n}\n\nfunction bindPan(chart) {\n let dragging = false, startClientX = 0, startClientY = 0, startMin = xMin, startMax = xMax, xUnitsPerPx = 0;\n const getScale = () => {\n const s = chart.scales.x || {};\n return { currMin: Number.isFinite(s.min) ? s.min : xMin, currMax: Number.isFinite(s.max) ? s.max : xMax };\n };\n const onMouseMove = (e) => {\n if (!dragging) return;\n \n // Ignore if vertical movement is dominant (likely scrolling)\n if (Math.abs(e.clientY - startClientY) > 20) return;\n \n e.preventDefault();\n const deltaPx = e.clientX - startClientX;\n const deltaVal = deltaPx * xUnitsPerPx;\n syncXRange(startMin - deltaVal, startMax - deltaVal);\n };\n const endDrag = () => {\n if (!dragging) return;\n dragging = false;\n document.body.style.cursor = '';\n window.removeEventListener('mousemove', onMouseMove);\n window.removeEventListener('mouseup', endDrag);\n };\n chart.root.addEventListener('mousedown', (e) => {\n if (!e || e.button !== 0 || e.ctrlKey || e.metaKey || e.altKey) return;\n const rect = chart.root.getBoundingClientRect();\n if (e.clientX < rect.left || e.clientX > rect.right || e.clientY < rect.top || e.clientY > rect.bottom) return;\n \n e.preventDefault();\n e.stopPropagation();\n \n dragging = true;\n startClientX = e.clientX;\n startClientY = e.clientY;\n const cur = getScale();\n startMin = cur.currMin; startMax = cur.currMax;\n \n // Calculate units per pixel once at start of drag to avoid sliding bug\n // chart.bbox.width is in device pixels; divide by pxRatio for CSS pixels\n xUnitsPerPx = (cur.currMax - cur.currMin) / (chart.bbox.width / (chart.pxRatio || 1));\n \n document.body.style.cursor = 'grabbing';\n window.addEventListener('mousemove', onMouseMove);\n window.addEventListener('mouseup', endDrag, { once: true });\n });\n\n // Keep the grab cursor while dragging even as the pointer leaves the plot,\n // and end the drag if the window loses focus mid-drag (otherwise the chart\n // keeps panning on the next mousemove after refocus).\n chart.root.addEventListener('mouseleave', () => {\n if (!dragging) return;\n document.body.style.cursor = 'grabbing';\n });\n window.addEventListener('blur', endDrag);\n}\n";
37
+ /**
38
+ * Optional per-bar viewport-clipping helper for draw hooks that walk the whole
39
+ * series every redraw (dynamic-weight fills). Kept out of UPLOT_SHARED_SCRIPT so
40
+ * charts that don't use it don't embed it. Consumers must have x data in
41
+ * u.data[0] and the x-scale min/max on u.scales.x.
42
+ */
43
+ declare const VIEWPORT_CLIP_SCRIPT = "\n// Index window for per-bar draw hooks: binary-search the visible x-range and\n// widen it by one bar on each side so line segments that cross the viewport\n// edge still start/end off-screen. Cuts per-redraw work from O(all bars) to\n// O(visible bars) when a chart is zoomed in.\nfunction visibleBarRange(u, len) {\n const xs = u.data && u.data[0];\n const x = (u.scales && u.scales.x) || {};\n if (!xs || xs.length !== len || !Number.isFinite(x.min) || !Number.isFinite(x.max)) {\n return [0, len - 1];\n }\n const smin = x.min, smax = x.max;\n let a = 0, b = len - 1;\n while (a < b) { const m = (a + b) >> 1; if (xs[m] < smin) a = m + 1; else b = m; }\n const lo = a - 1;\n a = 0; b = len - 1;\n while (a < b) { const m = (a + b + 1) >> 1; if (xs[m] > smax) b = m - 1; else a = m; }\n const hi = a + 1;\n return [Math.max(0, lo), Math.min(len - 1, hi)];\n}\n";
44
+ export { escapeHtml, serializeJsonForScript, toEpochSeconds, writeChartFile, toFileUrl, embedFunctionSources, UPLOT_SHARED_SCRIPT, VIEWPORT_CLIP_SCRIPT, uplotInlineTags };
38
45
  //# sourceMappingURL=chart_utils.d.ts.map
@@ -116,6 +116,29 @@ function clampXRange(min, max) {
116
116
  return { min: nextMin, max: nextMax };
117
117
  }
118
118
 
119
+ // Safe tick generator for uPlot log axes (scale distr: 3). uPlot 1.6.32's
120
+ // built-in log splits (Je) can loop forever on a narrow price range: its step
121
+ // is reassigned to an intermediate tick that is missing from the nice-number
122
+ // cache, so subsequent rounding collapses the step to 0 and the tick array
123
+ // grows until the engine throws "Invalid array length" / runs out of memory
124
+ // (browser tab hang). Emitting only 1/2/5 x 10^d values inside [min, max]
125
+ // never diverges. Assigned per-axis via \`splits: logAxisSplits\`.
126
+ function logAxisSplits(u, axisIdx, min, max) {
127
+ const out = [];
128
+ if (!(min > 0) || !(max > min)) return out;
129
+ const lo = Math.floor(Math.log10(min));
130
+ const hi = Math.ceil(Math.log10(max));
131
+ const mults = [1, 2, 5];
132
+ for (let d = lo; d <= hi; d++) {
133
+ const base = Math.pow(10, d);
134
+ for (let m = 0; m < mults.length; m++) {
135
+ const v = mults[m] * base;
136
+ if (v >= min && v <= max) out.push(v);
137
+ }
138
+ }
139
+ return out.length >= 2 ? out : [min, max];
140
+ }
141
+
119
142
  function syncXRange(min, max) {
120
143
  pendingRange = clampXRange(min, max);
121
144
  if (pendingRangeRaf) return;
@@ -209,5 +232,32 @@ function bindPan(chart) {
209
232
  window.addEventListener('blur', endDrag);
210
233
  }
211
234
  `;
212
- export { escapeHtml, serializeJsonForScript, toEpochSeconds, writeChartFile, toFileUrl, embedFunctionSources, UPLOT_SHARED_SCRIPT, uplotInlineTags };
235
+ /**
236
+ * Optional per-bar viewport-clipping helper for draw hooks that walk the whole
237
+ * series every redraw (dynamic-weight fills). Kept out of UPLOT_SHARED_SCRIPT so
238
+ * charts that don't use it don't embed it. Consumers must have x data in
239
+ * u.data[0] and the x-scale min/max on u.scales.x.
240
+ */
241
+ const VIEWPORT_CLIP_SCRIPT = `
242
+ // Index window for per-bar draw hooks: binary-search the visible x-range and
243
+ // widen it by one bar on each side so line segments that cross the viewport
244
+ // edge still start/end off-screen. Cuts per-redraw work from O(all bars) to
245
+ // O(visible bars) when a chart is zoomed in.
246
+ function visibleBarRange(u, len) {
247
+ const xs = u.data && u.data[0];
248
+ const x = (u.scales && u.scales.x) || {};
249
+ if (!xs || xs.length !== len || !Number.isFinite(x.min) || !Number.isFinite(x.max)) {
250
+ return [0, len - 1];
251
+ }
252
+ const smin = x.min, smax = x.max;
253
+ let a = 0, b = len - 1;
254
+ while (a < b) { const m = (a + b) >> 1; if (xs[m] < smin) a = m + 1; else b = m; }
255
+ const lo = a - 1;
256
+ a = 0; b = len - 1;
257
+ while (a < b) { const m = (a + b + 1) >> 1; if (xs[m] > smax) b = m - 1; else a = m; }
258
+ const hi = a + 1;
259
+ return [Math.max(0, lo), Math.min(len - 1, hi)];
260
+ }
261
+ `;
262
+ export { escapeHtml, serializeJsonForScript, toEpochSeconds, writeChartFile, toFileUrl, embedFunctionSources, UPLOT_SHARED_SCRIPT, VIEWPORT_CLIP_SCRIPT, uplotInlineTags };
213
263
  //# sourceMappingURL=chart_utils.js.map
@@ -26,6 +26,7 @@ interface AmaDefaultsInput {
26
26
  declare function loadMarketProfiles(filePath?: string | null | undefined): {
27
27
  profiles?: Array<Record<string, unknown>>;
28
28
  } | null;
29
+ declare function findMarketProfile(profiles: unknown, meta?: MarketMeta): Record<string, unknown> | null;
29
30
  declare const TRADINGVIEW_PREFS_KEY_PREFIX = "dexbot2-tradingview-uplot-v3";
30
31
  declare const TRADINGVIEW_SYNC_KEY = "dexbot2-tradingview-sync";
31
32
  declare function sanitizeStorageComponent(value: unknown, fallback: string): string;
@@ -70,5 +71,5 @@ interface TvChartInput extends AmaDefaultsInput {
70
71
  [key: string]: unknown;
71
72
  }
72
73
  declare function generateHTML(data: TvChartInput, title?: string): string;
73
- export { generateHTML, normalizeCandle, loadMarketProfiles, resolveChartStorageKey, sanitizeStorageComponent, TRADINGVIEW_PREFS_KEY_PREFIX, TRADINGVIEW_SYNC_KEY };
74
+ export { generateHTML, normalizeCandle, loadMarketProfiles, findMarketProfile, resolveChartStorageKey, sanitizeStorageComponent, TRADINGVIEW_PREFS_KEY_PREFIX, TRADINGVIEW_SYNC_KEY };
74
75
  //# sourceMappingURL=tradingview_uplot_chart_generator.d.ts.map
@@ -65,8 +65,14 @@ function findMarketProfile(profiles, meta = {}) {
65
65
  return false;
66
66
  const e = entry;
67
67
  if (assetA && assetB) {
68
- const matchesPair = (String(e.assetA) === String(assetA) || String(e.assetAId) === String(assetA))
69
- && (String(e.assetB) === String(assetB) || String(e.assetBId) === String(assetB));
68
+ // Orientation-insensitive like the other market-profile consumers:
69
+ // a profile may have been fitted from either side of the pair.
70
+ const eA = [String(e.assetA), String(e.assetAId)];
71
+ const eB = [String(e.assetB), String(e.assetBId)];
72
+ const targetA = String(assetA);
73
+ const targetB = String(assetB);
74
+ const matchesPair = (eA.includes(targetA) && eB.includes(targetB))
75
+ || (eA.includes(targetB) && eB.includes(targetA));
70
76
  if (!matchesPair)
71
77
  return false;
72
78
  }
@@ -118,7 +124,27 @@ function resolveChartStorageKey(meta = {}, baseIntervalSeconds = 0) {
118
124
  }
119
125
  function generateHTML(data, title = 'TradingView Style Research') {
120
126
  const rawCandles = Array.isArray(data.candles) ? data.candles : [];
121
- const candles = rawCandles.map(normalizeCandle).filter(Boolean);
127
+ const normalizedCandles = rawCandles
128
+ .map(normalizeCandle)
129
+ .filter((c) => c != null);
130
+ // Data-quality guard: uPlot, inferBaseIntervalSeconds and aggregateCandles all
131
+ // assume ascending bucket time, and an out-of-order series silently corrupts
132
+ // the chart (zig-zag lines, wrong base interval, buckets split during
133
+ // aggregation). Normalize order at the single entry point so every source is
134
+ // safe. A stable sort is a no-op for already-ascending input, so valid charts
135
+ // render unchanged; only bad input is reordered (and reported).
136
+ let outOfOrder = false;
137
+ for (let i = 1; i < normalizedCandles.length; i++) {
138
+ if (normalizedCandles[i].time < normalizedCandles[i - 1].time) {
139
+ outOfOrder = true;
140
+ break;
141
+ }
142
+ }
143
+ const candles = outOfOrder
144
+ ? normalizedCandles.slice().sort((a, b) => a.time - b.time)
145
+ : normalizedCandles;
146
+ if (outOfOrder)
147
+ console.warn('[TradingView] candle input was out of order; sorted ascending before rendering');
122
148
  if (candles.length === 0)
123
149
  throw new Error('No candle data in input');
124
150
  const meta = data.meta || {};
@@ -126,6 +152,7 @@ function generateHTML(data, title = 'TradingView Style Research') {
126
152
  ? Number(meta.intervalSeconds)
127
153
  : inferBaseIntervalSeconds(candles, 3600);
128
154
  const timeframes = [
155
+ { label: '1h', seconds: 3600 },
129
156
  { label: '4h', seconds: 14400 },
130
157
  { label: '1d', seconds: 86400 },
131
158
  { label: '1w', seconds: 604800 },
@@ -211,6 +238,15 @@ function generateHTML(data, title = 'TradingView Style Research') {
211
238
  const storageKey = typeof data.storageKey === 'string' && data.storageKey.length > 0
212
239
  ? data.storageKey
213
240
  : resolveChartStorageKey(meta, baseIntervalSeconds);
241
+ // Data-freshness anchor for the in-page live age badge: the newest candle's
242
+ // bucket time (epoch seconds), falling back to the source file's
243
+ // `meta.updatedAt`. Null hides the age (non-JSON sources may carry neither).
244
+ const lastCandleEntry = candles.length ? candles[candles.length - 1] : null;
245
+ const lastCandleSec = Number(lastCandleEntry?.time);
246
+ const metaUpdatedMs = Date.parse(String(meta.updatedAt ?? ''));
247
+ const dataUpdatedAtSec = Number.isFinite(lastCandleSec) && lastCandleSec > 0
248
+ ? Math.floor(lastCandleSec)
249
+ : (Number.isFinite(metaUpdatedMs) ? Math.floor(metaUpdatedMs / 1000) : null);
214
250
  const payload = {
215
251
  storageKey,
216
252
  syncKey: TRADINGVIEW_SYNC_KEY,
@@ -247,6 +283,8 @@ function generateHTML(data, title = 'TradingView Style Research') {
247
283
  pairLabelInverse,
248
284
  poolLabel,
249
285
  intervalLabel,
286
+ intervalSeconds: baseIntervalSeconds,
287
+ dataUpdatedAtSec,
250
288
  amaDefaultsSource: marketProfiles ? 'market_profiles' : 'constants',
251
289
  volumeIsCount: !!meta?.feed,
252
290
  };
@@ -280,8 +318,16 @@ function generateHTML(data, title = 'TradingView Style Research') {
280
318
  backdrop-filter: blur(10px);
281
319
  }
282
320
  #brand { display: flex; flex-direction: column; gap: 4px; min-width: 240px; }
321
+ #title-row { display: flex; align-items: baseline; gap: 10px; }
283
322
  #title { font-size: 15px; font-weight: 700; color: #f5f8fb; }
284
- #subtitle { font-size: 11px; color: #b9c6d4; text-transform: uppercase; letter-spacing: 0.6px; }
323
+ #subtitle { font-size: 12px; color: #b9c6d4; text-transform: uppercase; letter-spacing: 0.6px; }
324
+ #data-age { display: inline-flex; align-items: center; gap: 6px; font-size: 14px; font-weight: 600; color: #8290a2; letter-spacing: 0.2px; }
325
+ #data-age::before { content: ""; width: 8px; height: 8px; border-radius: 50%; background: #22c55e; box-shadow: 0 0 0 2px rgba(34,197,94,0.18); }
326
+ #data-age.is-stale { color: #d8b36a; }
327
+ #data-age.is-stale::before { background: #f59e0b; box-shadow: 0 0 0 2px rgba(245,158,11,0.18); }
328
+ #data-age.is-outdated { color: #e08585; }
329
+ #data-age.is-outdated::before { background: #ef5350; box-shadow: 0 0 0 2px rgba(239,83,80,0.18); }
330
+ #data-age.is-unknown::before { background: #475569; box-shadow: none; }
285
331
  #toolbar { display: flex; flex-direction: column; align-items: flex-end; gap: 6px; }
286
332
  .toolbar-row { display: flex; flex-wrap: wrap; justify-content: flex-end; gap: 8px 12px; align-items: center; }
287
333
  .group { display: inline-flex; align-items: center; gap: 8px; padding-left: 12px; border-left: 1px solid #263241; }
@@ -522,12 +568,16 @@ function generateHTML(data, title = 'TradingView Style Research') {
522
568
  <div id="app">
523
569
  <div id="topbar">
524
570
  <div id="brand">
525
- <div id="title">${escapeHtml(title)}</div>
526
- <div id="subtitle">${escapeHtml(poolLabel)} · ${escapeHtml(pairLabelNormal)} · ${escapeHtml(intervalLabel)} base · indicators from 1h · volume · uPlot</div>
571
+ <div id="title-row">
572
+ <div id="title">${escapeHtml(title)}</div>
573
+ <span id="data-age" title="Age of the newest candle, recomputed live in the browser. Fresh: under 24h, stale: 1–7 days, out of date: over a week.">—</span>
574
+ </div>
575
+ <div id="subtitle">${escapeHtml(poolLabel)} · ${escapeHtml(pairLabelNormal)} · ${escapeHtml(intervalLabel)} base · indicators from 1h</div>
527
576
  </div>
528
577
  <div id="toolbar">
529
578
  <div class="toolbar-row primary-toolbar-row">
530
579
  <div class="group">
580
+ <div class="indicator"><label><input type="checkbox" id="volume-toggle" checked> Volume</label> <button type="button" class="reset-btn" id="volume-unit-toggle" data-volume-mode="base" title="Volume units: base asset — click for quote asset">${escapeHtml(defaultPairMode === 'inverse' ? assetLabelB : assetLabelA)}</button></div>
531
581
  <div class="indicator">
532
582
  <span class="tag">pair</span>
533
583
  <button type="button" class="pair-toggle${defaultPairMode === 'inverse' ? ' is-inverse' : ''}" id="pair-toggle" aria-label="Swap pair orientation" title="Swap pair orientation" data-pair-mode="${escapeHtml(defaultPairMode)}">
@@ -561,7 +611,6 @@ function generateHTML(data, title = 'TradingView Style Research') {
561
611
  <button type="button" class="step-btn" id="vwap-bars-dec">▼</button>
562
612
  </span>
563
613
  </div>
564
- <div class="indicator"><label><input type="checkbox" id="volume-toggle" checked> Volume</label> <button type="button" class="reset-btn" id="volume-unit-toggle" data-volume-mode="base" title="Volume units: base asset — click for quote asset">${escapeHtml(defaultPairMode === 'inverse' ? assetLabelB : assetLabelA)}</button></div>
565
614
  ${(((payload.orderBuys?.length || 0) + (payload.orderSells?.length || 0) > 0 || payload.gridBounds?.low != null || payload.gridBounds?.high != null) ? '<div class="indicator"><label><input type="checkbox" id="orders-toggle" checked> Orders</label></div>' : '')}
566
615
  </div>
567
616
  </div>
@@ -641,6 +690,37 @@ function generateHTML(data, title = 'TradingView Style Research') {
641
690
  const volumeEl = document.getElementById('volume-chart');
642
691
  const baseCandles = Array.isArray(payload.candles) ? payload.candles.slice() : [];
643
692
  const baseCloseValues = baseCandles.map((c) => c.close);
693
+ // Live data-age badge: recomputed from the clock every minute, so a chart
694
+ // saved or opened later shows how stale its newest candle is. The
695
+ // freshness anchor is the newest candle's bucket time, embedded at
696
+ // generation time; the interval sets the color thresholds.
697
+ const dataAgeEl = document.getElementById('data-age');
698
+ const dataUpdatedAtSec = Number(payload.dataUpdatedAtSec) > 0 ? Number(payload.dataUpdatedAtSec) : NaN;
699
+ function formatDataAge(sec) {
700
+ const totalMin = Math.floor(sec / 60);
701
+ if (totalMin < 60) return totalMin + 'm';
702
+ const totalHours = Math.floor(totalMin / 60);
703
+ if (totalHours < 24) return totalHours + 'h ' + String(totalMin % 60).padStart(2, '0') + 'm';
704
+ return Math.floor(totalHours / 24) + 'd ' + (totalHours % 24) + 'h';
705
+ }
706
+ function refreshDataAge() {
707
+ if (!dataAgeEl) return;
708
+ if (!Number.isFinite(dataUpdatedAtSec)) {
709
+ dataAgeEl.className = 'is-unknown';
710
+ dataAgeEl.textContent = '—';
711
+ return;
712
+ }
713
+ const ageSec = Math.max(0, Date.now() / 1000 - dataUpdatedAtSec);
714
+ // Fresh: under 24h. Stale: 1d–7d. Out of date: over a week.
715
+ const DAY = 86400;
716
+ const level = ageSec < DAY ? 'fresh'
717
+ : ageSec < DAY * 7 ? 'stale' : 'outdated';
718
+ dataAgeEl.className = level === 'fresh' ? '' : 'is-' + level;
719
+ dataAgeEl.textContent = formatDataAge(ageSec);
720
+ dataAgeEl.title = 'Newest candle in this chart is ' + Math.round(ageSec / 60) + ' minute(s) old (computed live in the browser).';
721
+ }
722
+ refreshDataAge();
723
+ setInterval(refreshDataAge, 60000);
644
724
  const timeframes = Array.isArray(payload.timeframes) ? payload.timeframes.slice() : [];
645
725
  const timeframeMap = new Map(timeframes.map((item) => [item.label, item]));
646
726
  const STORAGE_KEY = typeof payload.storageKey === 'string' && payload.storageKey.length > 0
@@ -1134,7 +1214,7 @@ function generateHTML(data, title = 'TradingView Style Research') {
1134
1214
  function refreshSubtitle() {
1135
1215
  const subtitleEl = document.getElementById('subtitle');
1136
1216
  if (!subtitleEl) return;
1137
- subtitleEl.textContent = payload.poolLabel + ' · ' + getPairLabel() + ' · ' + payload.intervalLabel + ' base · indicators from 1h · volume · uPlot';
1217
+ subtitleEl.textContent = payload.poolLabel + ' · ' + getPairLabel() + ' · ' + payload.intervalLabel + ' base · indicators from 1h';
1138
1218
  }
1139
1219
  function snapInitOffset(value) {
1140
1220
  const next = Math.round(Number(value) || 0);
@@ -2153,7 +2233,15 @@ function generateHTML(data, title = 'TradingView Style Research') {
2153
2233
  segTop = [];
2154
2234
  segBot = [];
2155
2235
  };
2156
- for (let i = 0; i < xs.length; i++) {
2236
+ // Clip to the visible bar window (same rule as the grid-reset
2237
+ // band below) so a zoomed-in redraw does not walk every bar.
2238
+ // One bar of padding each side keeps segments that cross the
2239
+ // viewport edge connected; only contiguous valid runs are
2240
+ // painted, so off-screen bars add no pixels either way.
2241
+ const idxs = (u.series[0] && u.series[0].idxs) ? u.series[0].idxs : [0, xs.length - 1];
2242
+ const iLo = Math.max(0, idxs[0] - 1);
2243
+ const iHi = Math.min(xs.length - 1, idxs[1] + 1);
2244
+ for (let i = iLo; i <= iHi; i++) {
2157
2245
  const a = currentAma[i];
2158
2246
  const up = currentRangeUpper[i];
2159
2247
  const lo = currentRangeLower[i];
@@ -2314,7 +2402,7 @@ function generateHTML(data, title = 'TradingView Style Research') {
2314
2402
  return { hooks: { draw: [drawSimBand, drawSimResets] } };
2315
2403
  }
2316
2404
  function buildData() {
2317
- const tf = timeframeMap.get(currentTimeframe) || timeframeMap.get(defaultTimeframe.label) || timeframes[0];
2405
+ const tf = timeframeMap.get(currentTimeframe) || timeframeMap.get(payload.defaultTimeframe) || timeframes[0];
2318
2406
  currentSeriesState = getSeriesState(currentPairMode);
2319
2407
  currentSeriesCandles = currentSeriesState.candles;
2320
2408
  currentSeriesCloseValues = currentSeriesState.closeValues;
@@ -3804,5 +3892,5 @@ function generateHTML(data, title = 'TradingView Style Research') {
3804
3892
  </body>
3805
3893
  </html>`;
3806
3894
  }
3807
- export { generateHTML, normalizeCandle, loadMarketProfiles, resolveChartStorageKey, sanitizeStorageComponent, TRADINGVIEW_PREFS_KEY_PREFIX, TRADINGVIEW_SYNC_KEY };
3895
+ export { generateHTML, normalizeCandle, loadMarketProfiles, findMarketProfile, resolveChartStorageKey, sanitizeStorageComponent, TRADINGVIEW_PREFS_KEY_PREFIX, TRADINGVIEW_SYNC_KEY };
3808
3896
  //# sourceMappingURL=tradingview_uplot_chart_generator.js.map
@@ -4,7 +4,7 @@ import { getAmaWarmupBars } from '../../market_adapter/core/strategies/ama.js';
4
4
  import { bilinearInterpolate } from '../../market_adapter/core/strategies/regime_interp.js';
5
5
  import { computeDynamicWeightSeries, computeHuberWindowSlopePct, computeAmaSlopeClipThreshold, echoLatchSeries, roundToN } from '../../market_adapter/core/strategies/dynamic_weight_series.js';
6
6
  import { buildKalmanVelocitySeries, computeAbsolutePercentileThreshold, resolveKalmanVelocitySmoothingConfig, smoothKalmanVelocityPoint, } from '../../market_adapter/core/signals/kalman_velocity_smoothing.js';
7
- import { embedFunctionSources, escapeHtml, serializeJsonForScript, toEpochSeconds, UPLOT_SHARED_SCRIPT, uplotInlineTags } from '../chart_utils.js';
7
+ import { embedFunctionSources, escapeHtml, serializeJsonForScript, toEpochSeconds, UPLOT_SHARED_SCRIPT, VIEWPORT_CLIP_SCRIPT, uplotInlineTags } from '../chart_utils.js';
8
8
  import { sharedChartCSS } from '../chart_css.js';
9
9
  import { Y_AXIS_SIZE, makeCursorConfig, bindHoverStateFn, wireChartEvents, zoomResetScript, sizeChartsFn, formatTimeLabelFn, refreshChartsPreservingZoomFn } from '../chart_ui.js';
10
10
  // Browser-embedded shared functions — the interactive chart runs the exact same
@@ -199,6 +199,9 @@ function generateHTML(data, title = 'Dynamic Weight Research') {
199
199
  ${uplotInlineTags()}
200
200
  <style>
201
201
  ${sharedChartCSS()}
202
+ /* Panel titles sit at the top-right; make them clearly readable
203
+ (shared CSS uses a very dark #30363d that vanishes on the dark bg). */
204
+ .section-label { color: #c9d1d9; font-size: 10px; }
202
205
  #price-panel { flex: 0 0 34%; min-height: 0; position: relative; border-bottom: 1px solid #30363d; }
203
206
  #ama-panel { flex: 0 0 14%; min-height: 0; position: relative; border-bottom: 1px solid #30363d; }
204
207
  #kalman-panel { flex: 0 0 21%; min-height: 0; position: relative; border-bottom: 1px solid #30363d; }
@@ -256,11 +259,12 @@ function generateHTML(data, title = 'Dynamic Weight Research') {
256
259
  .ctrl.off .val { color: #3fb950; }
257
260
  .ctrl.nz input[type="range"] { accent-color: #8b949e; }
258
261
  .ctrl.nz .val { color: #8b949e; }
259
- .copy-btn, .paste-btn { pointer-events: auto; margin-left: 6px; padding: 2px 10px; font-size: 10px; background: #21262d; color: #8b949e; border: 1px solid #30363d; border-radius: 4px; cursor: pointer; }
260
- .copy-btn:hover, .paste-btn:hover { background: #30363d; color: #e6edf3; }
262
+ .copy-btn, .paste-btn, .reset-btn { pointer-events: auto; margin-left: 6px; padding: 2px 10px; font-size: 10px; background: #21262d; color: #8b949e; border: 1px solid #30363d; border-radius: 4px; cursor: pointer; }
263
+ .copy-btn:hover, .paste-btn:hover, .reset-btn:hover { background: #30363d; color: #e6edf3; }
261
264
  .copy-btn.copied { color: #3fb950; border-color: #3fb950; }
262
265
  .paste-btn.pasted { color: #58a6ff; border-color: #58a6ff; }
263
266
  .paste-btn.error { color: #f85149; border-color: #f85149; }
267
+ .reset-btn.reset { color: #d29922; border-color: #d29922; }
264
268
  #paste-confirm { display: none; position: fixed; background: #161b22; border: 1px solid #30363d; border-radius: 6px; padding: 14px 16px; z-index: 1000; box-shadow: 0 4px 24px rgba(0,0,0,0.7); min-width: 200px; }
265
269
  #paste-confirm-title { font-size: 10px; color: #8b949e; margin-bottom: 8px; text-transform: uppercase; letter-spacing: 0.5px; }
266
270
  #paste-confirm-vals { font-size: 11px; font-family: monospace; color: #e6edf3; line-height: 1.7; margin-bottom: 12px; }
@@ -346,6 +350,7 @@ function generateHTML(data, title = 'Dynamic Weight Research') {
346
350
  <div class="ctrl regime"><label for="regime-slider">regi</label><input type="range" id="regime-slider" min="0" max="${REGI_MAX * 100}" value="${regimeInitSlider}" title="Regime Sensitivity"><span class="val" id="regime-value">${defaultRegimeSensitivity.toFixed(2)}</span></div>
347
351
  <button class="copy-btn" id="copy-params-btn">copy</button>
348
352
  <button class="paste-btn" id="paste-params-btn">paste</button>
353
+ <button class="reset-btn" id="reset-params-btn">reset</button>
349
354
  </div>
350
355
  <div id="output-chart"></div>
351
356
  </div>
@@ -687,6 +692,8 @@ function generateHTML(data, title = 'Dynamic Weight Research') {
687
692
 
688
693
  ${UPLOT_SHARED_SCRIPT}
689
694
 
695
+ ${VIEWPORT_CLIP_SCRIPT}
696
+
690
697
  ${refreshChartsPreservingZoomFn({
691
698
  anchor: 'outputChart?.scales?.x',
692
699
  reload: [
@@ -779,6 +786,11 @@ function generateHTML(data, title = 'Dynamic Weight Research') {
779
786
  ctx.save();
780
787
  ctx.beginPath(); ctx.rect(bbox.left, bbox.top, bbox.width, bbox.height); ctx.clip();
781
788
  ctx.globalCompositeOperation = 'destination-over';
789
+ // Cull segments that cannot intersect the viewport so we skip
790
+ // their (expensive, destination-over) fillRect and valToPos work.
791
+ const xScale = u.scales.x || {};
792
+ const smin = xScale.min, smax = xScale.max;
793
+ const canCull = Number.isFinite(smin) && Number.isFinite(smax);
782
794
  let i = 0;
783
795
  while (i < data.signals.length) {
784
796
  const s = currentLatchedSignals[i] || data.signals[i];
@@ -791,6 +803,16 @@ function generateHTML(data, title = 'Dynamic Weight Research') {
791
803
  if (sj !== s) break;
792
804
  j++;
793
805
  }
806
+ if (canCull) {
807
+ // A run that reaches the last real bar is drawn all the way
808
+ // to bbox.right, so it is visible for any viewport past its
809
+ // start (never cull it on the right). Only runs that end at a
810
+ // real bar can be entirely left of the viewport.
811
+ const reachesRightEdge = j >= data.realBarCount;
812
+ const segEnd = reachesRightEdge ? Infinity : data.dates[j];
813
+ if (segEnd < smin) { i = j; continue; }
814
+ if (data.dates[i] > smax) break;
815
+ }
794
816
  const x0 = u.valToPos(data.dates[i], 'x', true);
795
817
  const x1 = j < data.realBarCount ? u.valToPos(data.dates[j], 'x', true) : bbox.left + bbox.width;
796
818
  if (isBull) { ctx.fillStyle = 'rgba(46,160,67,0.06)'; ctx.fillRect(x0, bbox.top, x1 - x0, bbox.height); }
@@ -817,7 +839,8 @@ function generateHTML(data, title = 'Dynamic Weight Research') {
817
839
  const zeroY = u.valToPos(0, scaleKey, true);
818
840
  const path = new Path2D();
819
841
  let inSeg = false, lastX = 0;
820
- for (let i = 0; i < values.length; i++) {
842
+ const [lo, hi] = visibleBarRange(u, values.length);
843
+ for (let i = lo; i <= hi; i++) {
821
844
  const v = values[i];
822
845
  if (v === null) { if (inSeg) { path.lineTo(lastX, zeroY); inSeg = false; } continue; }
823
846
  const x = u.valToPos(data.dates[i], 'x', true);
@@ -949,6 +972,7 @@ function generateHTML(data, title = 'Dynamic Weight Research') {
949
972
  axes: [
950
973
  makeTimeAxis(false),
951
974
  { scale: 'y', stroke: '#ffffff', grid: { stroke: '#1c2128' }, ticks: { stroke: '#30363d', width: 1 }, size: Y_AXIS_SIZE, font: '11px Segoe UI, sans-serif',
975
+ splits: logAxisSplits,
952
976
  values: (u, v) => v.map(x => x != null ? x.toFixed(4) : ''), }
953
977
  ],
954
978
  cursor: cursorCfg,
@@ -1285,6 +1309,27 @@ function applyParams(p, btn) {
1285
1309
 
1286
1310
  const LS_KEY = 'dw_research_params';
1287
1311
 
1312
+ // Factory defaults captured server-side; the reset button restores
1313
+ // every knob to these values.
1314
+ const RESET_PARAMS = ${JSON.stringify({
1315
+ alpha: defaultAlpha,
1316
+ amaMaxSlopePct: defaultAmaMaxSlopePct,
1317
+ kalmanMaxSlopePct: defaultKalmanMaxSlopePct,
1318
+ minOutputThreshold: defaultMinOutputThreshold,
1319
+ gain: defaultGain,
1320
+ kalmanSmoothPct: defaultKalmanSmoothPct,
1321
+ kalmanDispScaleMult: defaultKalmanDispScaleMult,
1322
+ dispScaleMinPct: defaultDispScaleMinPct,
1323
+ kalmanDispThresholdMult: defaultKalmanDispThresholdMult,
1324
+ kalmanSmoothSpanPct: defaultKalmanSmoothSpanPct,
1325
+ signalConfirmBars: defaultSignalConfirmBars,
1326
+ clipPct: defaultClipPct,
1327
+ neutralZonePct: defaultNeutralZone,
1328
+ regimeSensitivity: defaultRegimeSensitivity,
1329
+ dispWeight: defaultDispWeight,
1330
+ lookbackBars,
1331
+ })};
1332
+
1288
1333
  document.getElementById('copy-params-btn').addEventListener('click', () => {
1289
1334
  const btn = document.getElementById('copy-params-btn');
1290
1335
  const params = {
@@ -1340,6 +1385,14 @@ function applyParams(p, btn) {
1340
1385
  ta.addEventListener('keydown', (e) => { if (e.key === 'Escape') cleanup(); });
1341
1386
  setTimeout(cleanup, 10000);
1342
1387
  });
1388
+
1389
+ document.getElementById('reset-params-btn').addEventListener('click', () => {
1390
+ const btn = document.getElementById('reset-params-btn');
1391
+ applyParams(RESET_PARAMS);
1392
+ btn.textContent = 'reset!';
1393
+ btn.classList.add('reset');
1394
+ setTimeout(() => { btn.textContent = 'reset'; btn.classList.remove('reset'); }, 1500);
1395
+ });
1343
1396
  }
1344
1397
 
1345
1398
  ${sizeChartsFn([['priceChart', 'price-panel'], ['amaChart', 'ama-panel'], ['kalmanChart', 'kalman-panel'], ['outputChart', 'output-panel']])}
@@ -340,6 +340,7 @@ function generateHTML(data, title = 'Kalman Trajectory Analysis') {
340
340
  ticks: { stroke: '#30363d', width: 1 },
341
341
  size: ${Y_AXIS_SIZE},
342
342
  font: '11px Segoe UI, sans-serif',
343
+ splits: logAxisSplits,
343
344
  values: (u, v) => v.map(x => x != null ? x.toFixed(4) : ''),
344
345
  }
345
346
  ],
@@ -256,7 +256,7 @@ function generateRegimeHTML(data, title = 'Regime Analysis') {
256
256
  ],
257
257
  axes: [
258
258
  X_AXIS_CFG,
259
- { ...yAxis('y'), values: (u, v) => v.map(x => x != null ? fmtPrice(x) : '') },
259
+ { ...yAxis('y'), splits: logAxisSplits, values: (u, v) => v.map(x => x != null ? fmtPrice(x) : '') },
260
260
  ],
261
261
  cursor: cursorCfg,
262
262
  hooks: { draw: [(u) => { updateLegend(u.cursor.idx); }] },
@@ -519,6 +519,7 @@ function generateHTML(data, title = 'ATR Volatility Research') {
519
519
  axes: [
520
520
  { show: false, stroke: '#ffffff', grid: { stroke: '#1c2128' }, ticks: { stroke: '#30363d', width: 1 }, size: 28, font: '11px Segoe UI, sans-serif' },
521
521
  { scale: 'y', stroke: '#ffffff', grid: { stroke: '#1c2128' }, ticks: { stroke: '#30363d', width: 1 }, size: Y_AXIS_SIZE, font: '11px Segoe UI, sans-serif',
522
+ splits: logAxisSplits,
522
523
  values: (u, v) => v.map(x => x != null ? fmtNum(x, 6) : '') },
523
524
  ],
524
525
  cursor: cursorCfg,