dexbot 1.6.8 → 1.6.10

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 (70) hide show
  1. package/CHANGELOG.md +42 -0
  2. package/analysis/README.md +1 -1
  3. package/analysis/tradingview/README.md +14 -9
  4. package/claw/modules/chain_queries.ts +9 -4
  5. package/claw/modules/claw_bridge.ts +9 -9
  6. package/claw/package.json +1 -1
  7. package/claw/runtimes/openclaw-plugin/openclaw.plugin.json +1 -1
  8. package/claw/runtimes/openclaw-plugin/package.json +1 -1
  9. package/dist/analysis/ama_fitting/optimizer_high_resolution.js +2 -1
  10. package/dist/analysis/bot_fitting/backtest_ama_sweep.js +2 -2
  11. package/dist/analysis/bot_fitting/backtest_bot_fitting.js +4 -4
  12. package/dist/analysis/bot_key_utils.js +14 -4
  13. package/dist/analysis/tradingview/analyze_tradingview.d.ts +0 -3
  14. package/dist/analysis/tradingview/analyze_tradingview.js +3 -14
  15. package/dist/analysis/tradingview/grid_reset_sim.d.ts +11 -1
  16. package/dist/analysis/tradingview/grid_reset_sim.js +22 -9
  17. package/dist/analysis/tradingview/tradingview_uplot_chart_generator.js +178 -32
  18. package/dist/analysis/trend_detection/dynamic_weight_chart_generator.js +8 -3
  19. package/dist/dexbot.js +57 -29
  20. package/dist/market_adapter/core/market_adapter_service.d.ts +81 -1
  21. package/dist/market_adapter/core/market_adapter_service.js +225 -18
  22. package/dist/market_adapter/core/signals/hurst_analyzer.d.ts +10 -1
  23. package/dist/market_adapter/core/signals/hurst_analyzer.js +40 -18
  24. package/dist/market_adapter/core/signals/permutation_entropy_analyzer.d.ts +26 -2
  25. package/dist/market_adapter/core/signals/permutation_entropy_analyzer.js +132 -29
  26. package/dist/market_adapter/core/strategies/ama_slope_model.d.ts +2 -2
  27. package/dist/market_adapter/core/strategies/ama_slope_model.js +12 -10
  28. package/dist/market_adapter/core/strategies/dynamic_weight_series.d.ts +41 -14
  29. package/dist/market_adapter/core/strategies/dynamic_weight_series.js +138 -30
  30. package/dist/market_adapter/core/strategies/regime_gate.d.ts +61 -3
  31. package/dist/market_adapter/core/strategies/regime_gate.js +207 -7
  32. package/dist/market_adapter/interval_utils.d.ts +18 -1
  33. package/dist/market_adapter/interval_utils.js +31 -1
  34. package/dist/market_adapter/lp_chart_strategy_loader.js +2 -1
  35. package/dist/market_adapter/market_adapter.d.ts +151 -2
  36. package/dist/market_adapter/market_adapter.js +378 -62
  37. package/dist/market_adapter/test_helpers.d.ts +2 -2
  38. package/dist/market_adapter/test_helpers.js +2 -2
  39. package/dist/market_adapter/utils/chain.d.ts +1 -1
  40. package/dist/market_adapter/utils/chain.js +8 -6
  41. package/dist/market_adapter/utils/file_json_cache.d.ts +29 -0
  42. package/dist/market_adapter/utils/file_json_cache.js +106 -0
  43. package/dist/modules/account_bots.js +5 -4
  44. package/dist/modules/bitshares-native/resolvers.js +5 -0
  45. package/dist/modules/bot_settings.js +13 -1
  46. package/dist/modules/chain_orders.js +2 -1
  47. package/dist/modules/config.d.ts +6 -0
  48. package/dist/modules/config.js +1 -0
  49. package/dist/modules/constants.d.ts +11 -1
  50. package/dist/modules/constants.js +64 -15
  51. package/dist/modules/credential_policy.js +4 -1
  52. package/dist/modules/credit_runtime.js +5 -1
  53. package/dist/modules/order/grid.js +95 -25
  54. package/dist/modules/order/utils/system.js +11 -1
  55. package/dist/modules/utils/asset_symbols.d.ts +59 -0
  56. package/dist/modules/utils/asset_symbols.js +128 -0
  57. package/dist/modules/version_notice.d.ts +166 -20
  58. package/dist/modules/version_notice.js +401 -56
  59. package/dist/pm2.js +9 -2
  60. package/dist/scripts/analyze-credit.js +10 -7
  61. package/dist/scripts/chart_command.js +12 -4
  62. package/dist/scripts/verify-browser-bundle.js +8 -0
  63. package/dist/unlock.js +7 -7
  64. package/docs/DEXBOT_COMPARISON.md +3 -3
  65. package/docs/EVOLUTION.md +14 -12
  66. package/docs/FUND_MOVEMENT_AND_ACCOUNTING.md +1 -1
  67. package/docs/GRID_RECALCULATION.md +28 -5
  68. package/docs/README.md +2 -2
  69. package/market_adapter/README.md +30 -2
  70. package/package.json +1 -1
@@ -10,9 +10,16 @@ import { getStorage } from '../../modules/storage/index.js';
10
10
  const { readJSON } = getStorage();
11
11
  import { getErrorMessage } from '../../modules/utils/errors.js';
12
12
  import { parseRelativeMultiplier } from '../../modules/order/utils/math.js';
13
- import { computeAverageAmaSlopePct, computeAmaSlopeClipThreshold, createAmaSlopeClipTracker, percentileFromSorted } from '../../market_adapter/core/strategies/dynamic_weight_series.js';
13
+ import { computeAverageAmaSlopePct, computeHuberWindowSlopePct, computeAmaSlopeClipThreshold, createAmaSlopeClipTracker, percentileFromSorted } from '../../market_adapter/core/strategies/dynamic_weight_series.js';
14
14
  import { resolveBaseBounds, computeAsymmetricBoundsMetrics, applyAsymmetricBounds, applyNarrowingSideGuard, } from '../../market_adapter/core/asymmetric_bounds.js';
15
- import { simulateGridResetSeries, gridSimSlopeSignal, gridSimPositiveNumber, gridSimNonNegativeInt, GRID_RESET_NONE, GRID_RESET_BOOTSTRAP, GRID_RESET_PRICE, GRID_RESET_SLOPE, } from './grid_reset_sim.js';
15
+ import { simulateGridResetSeries, gridSimSlopeSignal, gridSimPositiveNumber, gridSimNonNegativeInt, gridSimResolveSlopeEstimator, GRID_RESET_NONE, GRID_RESET_BOOTSTRAP, GRID_RESET_PRICE, GRID_RESET_SLOPE, } from './grid_reset_sim.js';
16
+ // x-range (span) around the AMA price, in chart x-units. One slider (0.05 step)
17
+ // drives the band, the price-axis fit and the grid-reset sim, so the bounds
18
+ // live here and are interpolated into the generated page (slider markup,
19
+ // state hydration and the two compute paths all clamp to the same numbers).
20
+ const RANGE_SPAN_MIN = 1.3;
21
+ const RANGE_SPAN_MAX = 2.1;
22
+ const RANGE_SPAN_DEFAULT = 1.55;
16
23
  function inferBaseIntervalSeconds(candles, fallback = 3600) {
17
24
  if (!Array.isArray(candles) || candles.length < 2)
18
25
  return fallback;
@@ -136,21 +143,24 @@ function generateHTML(data, title = 'TradingView Style Research') {
136
143
  minScaleSlots: MARKET_ADAPTER.ASYMMETRIC_BOUNDS_MIN_SCALE_SLOTS,
137
144
  clipPercentile: MARKET_ADAPTER.DYNAMIC_WEIGHT_CLIP_PERCENTILE,
138
145
  };
146
+ // Slider bounds for the x-range around AMA live in RANGE_SPAN_MIN/MAX above
147
+ // and are interpolated into the generated page; the clamps here and there
148
+ // must not drift apart.
139
149
  function defaultRangeSpan(input) {
140
150
  const cli = Number(input.rangeSpan);
141
151
  if (Number.isFinite(cli))
142
- return Math.min(2, Math.max(1.2, cli));
152
+ return Math.min(RANGE_SPAN_MAX, Math.max(RANGE_SPAN_MIN, cli));
143
153
  const down = parseRelativeMultiplier(input.grid?.minPrice);
144
154
  const up = parseRelativeMultiplier(input.grid?.maxPrice);
145
155
  if (down != null && down > 1 && up != null && up > 1)
146
- return Math.min(2, Math.max(1.2, (down + up) / 2));
156
+ return Math.min(RANGE_SPAN_MAX, Math.max(RANGE_SPAN_MIN, (down + up) / 2));
147
157
  const vd = Number(input.grid?.minPrice);
148
158
  const vu = Number(input.grid?.maxPrice);
149
159
  if (Number.isFinite(vd) && Number.isFinite(vu) && vd > 0 && vu > vd) {
150
160
  const ref = Math.sqrt(vd * vu);
151
- return Math.min(2, Math.max(1.2, (ref / vd + vu / ref) / 2));
161
+ return Math.min(RANGE_SPAN_MAX, Math.max(RANGE_SPAN_MIN, (ref / vd + vu / ref) / 2));
152
162
  }
153
- return 1.55;
163
+ return RANGE_SPAN_DEFAULT;
154
164
  }
155
165
  const defaults = {
156
166
  smaPeriod: Math.max(1, Math.round(data.smaPeriod ?? 500)),
@@ -160,8 +170,11 @@ function generateHTML(data, title = 'TradingView Style Research') {
160
170
  vwapEnabled: data.vwapEnabled === true,
161
171
  vwapBars: Math.max(5, Math.round(data.vwapBars ?? 500)),
162
172
  priceScale: data.priceScale === 'linear' ? 'linear' : 'log',
163
- rangeEnabled: data.rangeEnabled === true,
164
- rangeScaleEnabled: data.rangeScaleEnabled === true,
173
+ // Range / Scale always start off: they are AMA-derived in-chart toggles
174
+ // with an auto opt-in chain, and the user's choice is persisted per
175
+ // chart in localStorage, so no generation-time default is needed.
176
+ rangeEnabled: false,
177
+ rangeScaleEnabled: false,
165
178
  rangeWidthPct: Number.isFinite(Number(data.rangeWidthPct)) && Number(data.rangeWidthPct) > 0
166
179
  ? Number(data.rangeWidthPct)
167
180
  : 2,
@@ -577,11 +590,11 @@ function generateHTML(data, title = 'TradingView Style Research') {
577
590
  <button type="button" class="reset-btn ama-preset-btn" data-ama-preset="AMA3" title="AMA3 (slow 83.6)">3</button>
578
591
  <button type="button" class="reset-btn ama-preset-btn" data-ama-preset="AMA4" title="AMA4 (slow 96.9)">4</button>
579
592
  </div>
580
- <div class="indicator" title="Range min/max built only from the live AMA price (red above, green below); Scale sizes it by AMA slope like the grid build">
593
+ <div class="indicator" title="Range min/max built only from the live AMA price (red above, green below); Scale sizes it by AMA slope like the grid build. Turning either on also turns on what it needs (Range → AMA, Scale → Range + AMA)">
581
594
  <label><input type="checkbox" id="range-toggle"${defaults.rangeEnabled ? ' checked' : ''}> Range</label>
582
- <label title="Range Scaling: size the band by AMA slope like the grid build (trend side widens, opposite tightens) and fit the price axis to it"><input type="checkbox" id="range-scale-toggle"${defaults.rangeScaleEnabled ? ' checked' : ''}> Scale</label>
583
- <span id="range-grid-wrap" style="display:inline" title="x-range around AMA (1.2x–2.0x)">
584
- <input type="range" id="range-span" min="1.2" max="2" step="0.05" value="${defaults.rangeSpan.toFixed(2)}" style="width:90px;vertical-align:middle">
595
+ <label title="Range Scaling: size the band by AMA slope like the grid build (trend side widens, opposite tightens) and fit the price axis to it. Turning it on also turns on Range and AMA"><input type="checkbox" id="range-scale-toggle"${defaults.rangeScaleEnabled ? ' checked' : ''}> Scale</label>
596
+ <span id="range-grid-wrap" style="display:inline" title="x-range around AMA (${RANGE_SPAN_MIN}x–${RANGE_SPAN_MAX}x)">
597
+ <input type="range" id="range-span" min="${RANGE_SPAN_MIN}" max="${RANGE_SPAN_MAX}" step="0.05" value="${defaults.rangeSpan.toFixed(2)}" style="width:90px;vertical-align:middle">
585
598
  <span id="range-span-val" style="font-size:11px;color:#8b949e;width:40px;display:inline-block;text-align:right">${defaults.rangeSpan.toFixed(2)}x</span>
586
599
  </span>
587
600
  </div>
@@ -653,12 +666,18 @@ function generateHTML(data, title = 'TradingView Style Research') {
653
666
  let currentVwapBars = Number.isFinite(state.vwapBars) ? state.vwapBars : Number(payload.vwapBars || 500);
654
667
  let currentRangeEnabled = state.rangeEnabled ?? !!payload.rangeEnabled;
655
668
  let currentRangeScaleEnabled = state.rangeScaleEnabled ?? !!payload.rangeScaleEnabled;
669
+ // Dependency chain: the band is built from the AMA price, and Scale sizes
670
+ // the band by AMA slope, so Scale needs Range and both need AMA. A
671
+ // persisted state (or CLI default) that enabled Scale without them would
672
+ // render a dead toggle, so re-apply the same auto opt-in on load.
673
+ if (currentRangeScaleEnabled) currentRangeEnabled = true;
674
+ if (currentRangeEnabled || currentRangeScaleEnabled) currentAmaEnabled = true;
656
675
  let currentRangeWidthPct = Number.isFinite(state.rangeWidthPct) && Number(state.rangeWidthPct) > 0
657
676
  ? Number(state.rangeWidthPct)
658
677
  : (Number.isFinite(Number(payload.rangeWidthPct)) && Number(payload.rangeWidthPct) > 0 ? Number(payload.rangeWidthPct) : 2);
659
678
  let currentRangeSpan = Number.isFinite(state.rangeSpan) && Number(state.rangeSpan) > 0
660
- ? Math.min(2, Math.max(1.2, Number(state.rangeSpan)))
661
- : (Number.isFinite(Number(payload.rangeSpan)) && Number(payload.rangeSpan) > 0 ? Math.min(2, Math.max(1.2, Number(payload.rangeSpan))) : 1.55);
679
+ ? Math.min(${RANGE_SPAN_MAX}, Math.max(${RANGE_SPAN_MIN}, Number(state.rangeSpan)))
680
+ : (Number.isFinite(Number(payload.rangeSpan)) && Number(payload.rangeSpan) > 0 ? Math.min(${RANGE_SPAN_MAX}, Math.max(${RANGE_SPAN_MIN}, Number(payload.rangeSpan))) : ${RANGE_SPAN_DEFAULT});
662
681
  let currentOrdersVisible = state.ordersVisible ?? true;
663
682
  // Grid-reset simulation (AMA-price Δ / AMA-slope Δ). Static per
664
683
  // generation: payload.gridSim is null for non-AMA charts, which removes
@@ -718,6 +737,7 @@ function generateHTML(data, title = 'TradingView Style Research') {
718
737
  let pendingRangeRaf = 0;
719
738
  let rangePanelRaf = 0;
720
739
  let yRefitRaf = 0;
740
+ let pendingViewY = null;
721
741
  let xMin = 0;
722
742
  let xMax = 0;
723
743
  let smaWorker = null;
@@ -1477,7 +1497,24 @@ function generateHTML(data, title = 'TradingView Style Research') {
1477
1497
  // red [AMA, upper], green [lower, AMA].
1478
1498
  // Never reads candles, pair-display mapping, or axis/zoom state —
1479
1499
  // inversion and timeframe sampling apply to the AMA first.
1480
- ${embedFunctionSources([computeAverageAmaSlopePct, computeAmaSlopeClipThreshold, resolveBaseBounds, computeAsymmetricBoundsMetrics, applyAsymmetricBounds, applyNarrowingSideGuard, parseRelativeMultiplier, percentileFromSorted, createAmaSlopeClipTracker, gridSimPositiveNumber, gridSimNonNegativeInt, gridSimSlopeSignal, simulateGridResetSeries])}
1500
+ // Canonical Huber-slope parameters, injected from MARKET_ADAPTER so the
1501
+ // embedded estimator runs the same values as the live adapter.
1502
+ const AMA_SLOPE_HUBER = ${serializeJsonForScript(MARKET_ADAPTER.DYNAMIC_WEIGHT_AMA_HUBER)};
1503
+ ${embedFunctionSources([computeAverageAmaSlopePct, computeAmaSlopeClipThreshold, resolveBaseBounds, computeAsymmetricBoundsMetrics, applyAsymmetricBounds, applyNarrowingSideGuard, parseRelativeMultiplier, percentileFromSorted, createAmaSlopeClipTracker, gridSimPositiveNumber, gridSimNonNegativeInt, gridSimSlopeSignal, gridSimResolveSlopeEstimator, computeHuberWindowSlopePct, simulateGridResetSeries])}
1504
+ // One slope window for every consumer on this page. The band must not
1505
+ // stay pinned to the shared constant while the replay honours a
1506
+ // bot-configured lookbackBars: that split let the plotted range and the
1507
+ // replayed \u0394s trigger disagree about how far back to measure the
1508
+ // slope. The replay's already-resolved value wins; the constant is the
1509
+ // fallback for charts that carry no grid-sim data (pool/pair charts).
1510
+ function resolveSlopeLookbackBars() {
1511
+ const fromGridSim = Number(gridSimCfg && gridSimCfg.lookbackBars);
1512
+ const fromConstants = Number(payload.rangeSlope && payload.rangeSlope.lookbackBars);
1513
+ const value = Number.isFinite(fromGridSim) && fromGridSim > 0 ? fromGridSim : fromConstants;
1514
+ return Number.isFinite(value) && value > 0
1515
+ ? Math.max(1, Math.round(value))
1516
+ : ${MARKET_ADAPTER.DYNAMIC_WEIGHT_AMA_LOOKBACK_BARS};
1517
+ }
1481
1518
  // ── Grid-reset simulation ──
1482
1519
  // Replays the two market-adapter recentering triggers (docs/GRID_RECALCULATION.md
1483
1520
  // §3 AMA Δ / §4 AMA-Slope Δ) over the 1h AMA series: the accepted grid center
@@ -1485,6 +1522,23 @@ function generateHTML(data, title = 'TradingView Style Research') {
1485
1522
  // reset (the advanceTriggeredBotState chain). Thresholds arrive pre-resolved
1486
1523
  // through the live config chain in payload.gridSim. The replay itself is the
1487
1524
  // canonical simulateGridResetSeries() embedded above — not a hand copy.
1525
+ // The chart plots the SAME slope the live adapter computes: the embedded
1526
+ // canonical estimator (computeHuberWindowSlopePct), used for BOTH the
1527
+ // replayed delta-s reset trigger and the plotted band tilt, so the chart
1528
+ // cannot diverge from the runtime or from itself. 'endpoint' (the old
1529
+ // two-point difference: same magnitude, far jitterier) remains a
1530
+ // chart-only comparison mode.
1531
+ const CHART_SLOPE_ESTIMATOR = 'canonical';
1532
+ function resolveChartSlopeEstimator() {
1533
+ if (CHART_SLOPE_ESTIMATOR === 'endpoint') {
1534
+ // Wrap to the seam signature (series, index, bars): the raw
1535
+ // helper takes two endpoints and would be mis-called directly.
1536
+ return function (series, index, bars) {
1537
+ return computeAverageAmaSlopePct(Number(series[index]), Number(series[index - bars]), bars);
1538
+ };
1539
+ }
1540
+ return computeHuberWindowSlopePct;
1541
+ }
1488
1542
  const GRID_RESET_NONE = ${GRID_RESET_NONE};
1489
1543
  const GRID_RESET_BOOTSTRAP = ${GRID_RESET_BOOTSTRAP};
1490
1544
  const GRID_RESET_PRICE = ${GRID_RESET_PRICE};
@@ -1517,7 +1571,16 @@ function generateHTML(data, title = 'TradingView Style Research') {
1517
1571
  const warmupBars = (override != null && Number.isFinite(Number(override)) && Number(override) >= 0)
1518
1572
  ? Math.ceil(Number(override))
1519
1573
  : warmup;
1520
- const cfg = Object.assign({}, gridSimCfg, { warmupBars: warmupBars });
1574
+ // warmupBars stays config-derived (getAmaWarmupBars); lookbackBars
1575
+ // comes straight from gridSimCfg, i.e. from the same resolved value
1576
+ // the Range tilt reads through resolveSlopeLookbackBars(), so both
1577
+ // consumers sample the identical window.
1578
+ const cfg = Object.assign({}, gridSimCfg, {
1579
+ warmupBars: warmupBars,
1580
+ // Same averaging model as the band above, so the replayed Δs
1581
+ // trigger and the plotted tilt keep measuring one quantity.
1582
+ slopeEstimator: resolveChartSlopeEstimator(),
1583
+ });
1521
1584
  return simulateGridResetSeries(baseAma, cfg);
1522
1585
  }
1523
1586
  // Simulated grid range for each bar: the accepted center with the accepted
@@ -1544,7 +1607,7 @@ function generateHTML(data, title = 'TradingView Style Research') {
1544
1607
  ? Number(gridCfg.maxAsymmetryFactor)
1545
1608
  : (Number(gridSimCfg.maxAsymmetryFactor) > 0 ? Number(gridSimCfg.maxAsymmetryFactor) : 0.333);
1546
1609
  const maxSlopeOffset = gridSimPositiveNumber(gridSimCfg.maxSlopeOffset, 0.5);
1547
- const span = Math.min(2, Math.max(1.2, Number(currentRangeSpan) > 0 ? Number(currentRangeSpan) : 1.55));
1610
+ const span = Math.min(${RANGE_SPAN_MAX}, Math.max(${RANGE_SPAN_MIN}, Number(currentRangeSpan) > 0 ? Number(currentRangeSpan) : ${RANGE_SPAN_DEFAULT}));
1548
1611
  // Absolute bot bounds are fixed price levels; relative ("Nx") bounds
1549
1612
  // travel with the accepted center. Each side resolves independently so
1550
1613
  // a mixed absolute/"Nx" config matches the runtime grid build.
@@ -1593,7 +1656,7 @@ function generateHTML(data, title = 'TradingView Style Research') {
1593
1656
  const trend = new Array(n).fill(0);
1594
1657
  const slopeCfg = payload.rangeSlope || {};
1595
1658
  const gridCfg = payload.grid || null;
1596
- const lookback = Math.max(1, Math.round(Number(slopeCfg.lookbackBars) || 9));
1659
+ const lookback = resolveSlopeLookbackBars();
1597
1660
  const maxSlope = Number(slopeCfg.maxSlopePct) > 0 ? Number(slopeCfg.maxSlopePct) : 0.09;
1598
1661
  const neutral = Number(slopeCfg.neutralZonePct) >= 0 ? Number(slopeCfg.neutralZonePct) : 0;
1599
1662
  const maxSlopeOffset = Number(slopeCfg.maxSlopeOffset) > 0 ? Number(slopeCfg.maxSlopeOffset) : 0.5;
@@ -1602,9 +1665,9 @@ function generateHTML(data, title = 'TradingView Style Research') {
1602
1665
  : (Number(slopeCfg.maxAsymmetryFactor) > 0 ? Number(slopeCfg.maxAsymmetryFactor) : 0.333);
1603
1666
  const inc = gridCfg && Number(gridCfg.incrementPercent) > 0 ? Number(gridCfg.incrementPercent) : null;
1604
1667
  const minSlots = Math.floor(Number(gridCfg && gridCfg.minScaleSlots) > 0 ? Number(gridCfg.minScaleSlots) : (Number(slopeCfg.minScaleSlots) || 0));
1605
- // User x-range span (slider 1.2x–2.0x, default 1.55x): the only
1668
+ // User x-range span (slider ${RANGE_SPAN_MIN}x–${RANGE_SPAN_MAX}x, default ${RANGE_SPAN_DEFAULT}x): the only
1606
1669
  // width input — symmetric base min = AMA/span, max = AMA*span.
1607
- const span = Math.min(2, Math.max(1.2, Number(currentRangeSpan) > 0 ? Number(currentRangeSpan) : 1.55));
1670
+ const span = Math.min(${RANGE_SPAN_MAX}, Math.max(${RANGE_SPAN_MIN}, Number(currentRangeSpan) > 0 ? Number(currentRangeSpan) : ${RANGE_SPAN_DEFAULT}));
1608
1671
  // Canonical grid pipeline (ama_slope_model): adaptive percentile
1609
1672
  // clip over the AMA history, then offset + trend — the same numbers
1610
1673
  // the live grid build feeds into applyAsymmetricBounds.
@@ -1615,11 +1678,14 @@ function generateHTML(data, title = 'TradingView Style Research') {
1615
1678
  const clipThreshold = computeAmaSlopeClipThreshold(baseAma, clipEr, lookback, clipPct);
1616
1679
  const slopeScaling = !!currentRangeScaleEnabled;
1617
1680
  if (!currentAmaEnabled || n === 0) return { upper, lower, trend };
1681
+ const bandSlopeEstimator = resolveChartSlopeEstimator();
1618
1682
  for (let i = 0; i < n; i++) {
1619
1683
  const ama = baseAma[i];
1620
- const past = i - lookback >= 0 ? baseAma[i - lookback] : null;
1621
- if (!Number.isFinite(ama) || ama <= 0 || !Number.isFinite(past) || past <= 0) continue;
1622
- const slopePct = computeAverageAmaSlopePct(ama, past, lookback);
1684
+ if (!Number.isFinite(ama) || ama <= 0) continue;
1685
+ // Same estimator object the replay uses, so the band and the
1686
+ // delta-s trigger measure one quantity. The endpoint wrapper and
1687
+ // the windowed estimators both return null on an unusable window.
1688
+ const slopePct = bandSlopeEstimator(baseAma, i, lookback);
1623
1689
  if (slopePct == null || !Number.isFinite(slopePct)) continue;
1624
1690
  const csp = Math.max(-clipThreshold, Math.min(clipThreshold, slopePct));
1625
1691
  const dir = Math.abs(csp) <= neutral ? 0 : (csp > 0 ? 1 : -1);
@@ -1818,6 +1884,17 @@ function generateHTML(data, title = 'TradingView Style Research') {
1818
1884
  refreshLegend();
1819
1885
  saveState();
1820
1886
  }
1887
+ // Range and Scale are AMA-derived: the band min/max come from the AMA
1888
+ // price and Scale additionally reads the AMA slope. Turning either on
1889
+ // therefore opts AMA in as well. One-way only — switching an indicator
1890
+ // off never switches off the ones it depends on. Returns true when AMA
1891
+ // was actually turned on, so the caller can pick the AMA-toggle render
1892
+ // path (full rerender, series added) instead of the keep-view one.
1893
+ function autoOptInAma() {
1894
+ if (currentAmaEnabled) return false;
1895
+ currentAmaEnabled = true;
1896
+ return true;
1897
+ }
1821
1898
  function hideRangeBandImmediate() {
1822
1899
  currentRangeUpper = new Array(currentCandles.length).fill(null);
1823
1900
  currentRangeLower = new Array(currentCandles.length).fill(null);
@@ -3332,7 +3409,7 @@ function generateHTML(data, title = 'TradingView Style Research') {
3332
3409
  currentVwapBars = clamp(Math.round(Number(document.getElementById('vwap-bars').value) || 500), 24, 2000);
3333
3410
  currentRangeEnabled = document.getElementById('range-toggle').checked;
3334
3411
  currentRangeScaleEnabled = document.getElementById('range-scale-toggle').checked;
3335
- currentRangeSpan = Math.min(2, Math.max(1.2, Math.round((Number(document.getElementById('range-span').value) || 1.55) * 20) / 20));
3412
+ currentRangeSpan = Math.min(${RANGE_SPAN_MAX}, Math.max(${RANGE_SPAN_MIN}, Math.round((Number(document.getElementById('range-span').value) || ${RANGE_SPAN_DEFAULT}) * 20) / 20));
3336
3413
  const ordersEl = document.getElementById('orders-toggle');
3337
3414
  if (ordersEl) currentOrdersVisible = ordersEl.checked;
3338
3415
  setControls();
@@ -3355,6 +3432,13 @@ function generateHTML(data, title = 'TradingView Style Research') {
3355
3432
  const nextEnabled = document.getElementById('ama-toggle').checked;
3356
3433
  if (currentAmaEnabled === nextEnabled) return;
3357
3434
  currentAmaEnabled = nextEnabled;
3435
+ if (!currentAmaEnabled) {
3436
+ // AMA is the base of the band and of its slope scaling: the
3437
+ // mirror image of the auto opt-in, so the toggles never sit in
3438
+ // the dead state Scale/Range-without-AMA would be.
3439
+ currentRangeEnabled = false;
3440
+ currentRangeScaleEnabled = false;
3441
+ }
3358
3442
  setControls();
3359
3443
  if (!currentAmaEnabled) {
3360
3444
  hideAmaSeriesImmediate();
@@ -3378,20 +3462,40 @@ function generateHTML(data, title = 'TradingView Style Research') {
3378
3462
  const nextEnabled = document.getElementById('range-toggle').checked;
3379
3463
  if (currentRangeEnabled === nextEnabled) return;
3380
3464
  currentRangeEnabled = nextEnabled;
3381
- setControls();
3382
- if (!currentRangeEnabled) {
3383
- hideRangeBandImmediate();
3465
+ if (currentRangeEnabled) {
3466
+ // Range draws from the AMA price: opting in opts AMA in too.
3467
+ const enabledAma = autoOptInAma();
3468
+ setControls();
3469
+ if (enabledAma) {
3470
+ rerender(false);
3471
+ return;
3472
+ }
3473
+ preserveView(() => rerender(true));
3384
3474
  return;
3385
3475
  }
3386
- rerender(false);
3476
+ setControls();
3477
+ preserveView(hideRangeBandImmediate);
3387
3478
  });
3388
3479
  document.getElementById('range-scale-toggle').addEventListener('change', () => {
3389
3480
  const nextEnabled = document.getElementById('range-scale-toggle').checked;
3390
3481
  if (currentRangeScaleEnabled === nextEnabled) return;
3391
3482
  currentRangeScaleEnabled = nextEnabled;
3392
- manualYRange = null;
3393
- setControls();
3394
- rerender(false);
3483
+ if (currentRangeScaleEnabled) {
3484
+ // Scale is the Range band sized by AMA slope: opt into both.
3485
+ currentRangeEnabled = true;
3486
+ const enabledAma = autoOptInAma();
3487
+ setControls();
3488
+ if (enabledAma) {
3489
+ rerender(false);
3490
+ return;
3491
+ }
3492
+ } else {
3493
+ setControls();
3494
+ }
3495
+ // No manualYRange reset: the price axis keeps the window it had,
3496
+ // so un/setting Scale never refits the view (the band still
3497
+ // draws, the legend readout still updates).
3498
+ preserveView(() => rerender(true));
3395
3499
  });
3396
3500
  ['sma-period', 'ama-er', 'ama-fast', 'ama-slow', 'vwap-bars'].forEach((id) => {
3397
3501
  document.getElementById(id).addEventListener('change', syncInputs);
@@ -3446,7 +3550,7 @@ function generateHTML(data, title = 'TradingView Style Research') {
3446
3550
  document.getElementById('range-span').addEventListener('input', () => {
3447
3551
  const input = document.getElementById('range-span');
3448
3552
  document.getElementById('range-span-val').textContent = Number(input.value).toFixed(2) + 'x';
3449
- syncInputs();
3553
+ preserveView(syncInputs);
3450
3554
  });
3451
3555
 
3452
3556
  // Room to the right past the last bar (~12%): for the market panel
@@ -3626,6 +3730,39 @@ function generateHTML(data, title = 'TradingView Style Research') {
3626
3730
  const span = Math.max(1e-12, Math.abs(vis[1] - vis[0]));
3627
3731
  return Math.abs(s.min - vis[0]) / span > 1e-9 || Math.abs(s.max - vis[1]) / span > 1e-9;
3628
3732
  }
3733
+ // Snapshot/restore of the visible window across a control toggle.
3734
+ // Y needs an explicit put back because the auto-fit follows the range
3735
+ // band — switching the band (or Scale) on/off would otherwise refit
3736
+ // the price axis and jump the view under the cursor. The restore is
3737
+ // applied from the same rAF as the refit (and after it) so a toggle
3738
+ // only ever paints the original window, and it does NOT set
3739
+ // manualYRange: panning afterwards still autofits as before.
3740
+ function captureView() {
3741
+ if (!priceChart) return null;
3742
+ const x = priceChart.scales.x || {};
3743
+ const y = priceChart.scales.y || {};
3744
+ const view = {
3745
+ x: Number.isFinite(x.min) && Number.isFinite(x.max) ? { min: x.min, max: x.max } : null,
3746
+ y: Number.isFinite(y.min) && Number.isFinite(y.max) ? { min: y.min, max: y.max } : null,
3747
+ };
3748
+ return view.x || view.y ? view : null;
3749
+ }
3750
+ function preserveView(fn) {
3751
+ const view = captureView();
3752
+ const res = fn();
3753
+ if (!view || !priceChart) return res;
3754
+ // X: re-assert the captured window (rerender/setData already keep
3755
+ // it) so the full view survives whatever path the callback took.
3756
+ if (view.x) {
3757
+ const next = clampRange(view.x.min, view.x.max);
3758
+ if (next) charts.forEach((chart) => chart.batch(() => chart.setScale('x', next)));
3759
+ }
3760
+ if (view.y) {
3761
+ pendingViewY = view.y;
3762
+ scheduleYRefit();
3763
+ }
3764
+ return res;
3765
+ }
3629
3766
  function scheduleYRefit() {
3630
3767
  if (yRefitRaf) return;
3631
3768
  yRefitRaf = requestAnimationFrame(() => {
@@ -3638,6 +3775,15 @@ function generateHTML(data, title = 'TradingView Style Research') {
3638
3775
  const vvis = visibleVolumeRange(volumeChart);
3639
3776
  if (vvis && yRangeDirty(volumeChart, vvis)) volumeChart.setScale('y', { min: vvis[0], max: vvis[1] });
3640
3777
  }
3778
+ // View lock from preserveView(): win over the refit above.
3779
+ const keep = pendingViewY;
3780
+ pendingViewY = null;
3781
+ if (keep && priceChart && Number.isFinite(keep.min) && Number.isFinite(keep.max) && keep.max > keep.min) {
3782
+ const s = priceChart.scales.y || {};
3783
+ if (!Number.isFinite(s.min) || Math.abs(s.min - keep.min) > 1e-12 || Math.abs(s.max - keep.max) > 1e-12) {
3784
+ priceChart.setScale('y', { min: keep.min, max: keep.max });
3785
+ }
3786
+ }
3641
3787
  });
3642
3788
  }
3643
3789
  padXRight();
@@ -2,7 +2,7 @@
2
2
  import { DEFAULT_CONFIG, MARKET_ADAPTER } from '../../modules/constants.js';
3
3
  import { getAmaWarmupBars } from '../../market_adapter/core/strategies/ama.js';
4
4
  import { bilinearInterpolate } from '../../market_adapter/core/strategies/regime_interp.js';
5
- import { computeDynamicWeightSeries, computeAverageAmaSlopePct, computeAmaSlopeClipThreshold, echoLatchSeries, roundToN } from '../../market_adapter/core/strategies/dynamic_weight_series.js';
5
+ import { computeDynamicWeightSeries, computeAverageAmaSlopePct, 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
7
  import { embedFunctionSources, escapeHtml, serializeJsonForScript, toEpochSeconds, UPLOT_SHARED_SCRIPT, uplotInlineTags } from '../chart_utils.js';
8
8
  import { sharedChartCSS } from '../chart_css.js';
@@ -11,6 +11,7 @@ import { Y_AXIS_SIZE, makeCursorConfig, bindHoverStateFn, wireChartEvents, zoomR
11
11
  // pure logic as the live market adapter service instead of a hand-copied copy.
12
12
  const EMBEDDED_SHARED_FUNCS = embedFunctionSources([
13
13
  computeAverageAmaSlopePct,
14
+ computeHuberWindowSlopePct,
14
15
  computeAmaSlopeClipThreshold,
15
16
  bilinearInterpolate,
16
17
  echoLatchSeries,
@@ -387,6 +388,10 @@ function generateHTML(data, title = 'Dynamic Weight Research') {
387
388
  <script>
388
389
  const data = JSON.parse(document.getElementById('payload').textContent);
389
390
 
391
+ // Canonical Huber-slope parameters, injected from MARKET_ADAPTER so the
392
+ // embedded estimator runs the same values as the live adapter.
393
+ const AMA_SLOPE_HUBER = ${serializeJsonForScript(MARKET_ADAPTER.DYNAMIC_WEIGHT_AMA_HUBER)};
394
+
390
395
  ${EMBEDDED_SHARED_FUNCS}
391
396
 
392
397
  const SYNC_KEY = "dyn-wt-res-v4";
@@ -611,8 +616,8 @@ function generateHTML(data, title = 'Dynamic Weight Research') {
611
616
  }
612
617
 
613
618
  function computeSlopeAtIndex(idx, lb, values) {
614
- // Canonical AMA slope % (computeAverageAmaSlopePct injected above).
615
- const sp = computeAverageAmaSlopePct(values[idx], values[idx - lb], lb);
619
+ // Canonical AMA slope % (computeHuberWindowSlopePct injected above).
620
+ const sp = computeHuberWindowSlopePct(values, idx, lb);
616
621
  return sp == null ? 0 : sp;
617
622
  }
618
623
 
package/dist/dexbot.js CHANGED
@@ -88,7 +88,6 @@ const { initializeFeeCache, ensureProfilesDirectory, readInput } = require('./mo
88
88
  const accountBots = require('./modules/account_bots');
89
89
  const SharedDEXBot = require('./modules/dexbot_class').default;
90
90
  const fundRegistry = require('./modules/fund_registry');
91
- const { maybePrintVersionStatus } = require('./modules/version_notice');
92
91
  /**
93
92
  * Resolve a collateral asset reference (symbol or ID) to its canonical asset ID.
94
93
  * Uses the already-connected BitShares DB instance.
@@ -96,15 +95,19 @@ const { maybePrintVersionStatus } = require('./modules/version_notice');
96
95
  */
97
96
  const _collateralAssetIdCache = new Map();
98
97
  async function _resolveCollateralAssetId(ref) {
99
- if (_collateralAssetIdCache.has(ref))
100
- return _collateralAssetIdCache.get(ref) ?? null;
98
+ // The collateral ref is free-text input from the fund-registration flow
99
+ // ("tokena" resolves on the chain without error). Canonicalize before the
100
+ // lookup AND before the cache key, so one asset never occupies two slots.
101
+ const key = normalizeAssetRef(ref);
102
+ if (_collateralAssetIdCache.has(key))
103
+ return _collateralAssetIdCache.get(key) ?? null;
101
104
  let result = null;
102
105
  try {
103
- if (typeof ref === 'string' && ref.startsWith('1.3.')) {
104
- result = ref;
106
+ if (key.startsWith('1.3.')) {
107
+ result = key;
105
108
  }
106
- else if (typeof ref === 'string') {
107
- const res = await BitShares.db.lookup_asset_symbols([ref]);
109
+ else if (key) {
110
+ const res = await BitShares.db.lookup_asset_symbols([key]);
108
111
  if (res && res[0] && res[0].id)
109
112
  result = String(res[0].id);
110
113
  }
@@ -112,7 +115,7 @@ async function _resolveCollateralAssetId(ref) {
112
115
  catch (_err) {
113
116
  result = null;
114
117
  }
115
- _collateralAssetIdCache.set(ref, result);
118
+ _collateralAssetIdCache.set(key, result);
116
119
  return result;
117
120
  }
118
121
  const { setupGracefulShutdown, registerCleanup, unregisterCleanup } = require('./modules/graceful_shutdown');
@@ -124,6 +127,7 @@ const credentialPolicy = require('./modules/credential_policy');
124
127
  const { Config } = require('./modules/config');
125
128
  const { getErrorMessage } = require('./modules/utils/errors');
126
129
  const { isSameBotName } = require('./modules/utils/sanitize_key');
130
+ const { normalizeAssetRef } = require('./modules/utils/asset_symbols');
127
131
  // Setup graceful shutdown handlers
128
132
  // Setup graceful shutdown handlers
129
133
  setupGracefulShutdown();
@@ -590,7 +594,7 @@ async function runBotInstances(botEntries, { forceDryRun = false, sourceName = '
590
594
  const collateralRef = item.collateralAsset;
591
595
  if (!collateralRef)
592
596
  continue;
593
- const collateralAssetId = _collateralAssetIdCache.get(collateralRef) ?? null;
597
+ const collateralAssetId = _collateralAssetIdCache.get(normalizeAssetRef(collateralRef)) ?? null;
594
598
  if (!collateralAssetId) {
595
599
  console.error(` ERROR: unable to resolve collateral asset '${collateralRef}' for credit bot ${botName}. Credit bot will run WITHOUT proportional allocation. Check chain connectivity and asset configuration.`);
596
600
  continue;
@@ -1076,20 +1080,49 @@ async function handleCLICommands() {
1076
1080
  // Installed-vs-published version status, from the single shared
1077
1081
  // renderer in modules/version_notice.ts: green when current, orange
1078
1082
  // when a newer release exists, gray when the probe cannot answer.
1079
- // Nothing overlaps here, so await it inline — the probe is throttled
1080
- // to once per UPDATER.NOTICE_INTERVAL_MS and hard-timeouts at the
1081
- // shorter UPDATER.NOTICE_STATUS_TIMEOUT_MS so status output cannot
1082
- // stall. The status line names the installed version, so a bare
1083
- // header is only needed when the check is switched off entirely.
1083
+ //
1084
+ // The probe is STAGED around the report instead of being awaited
1085
+ // inline (see startStagedVersionStatus):
1086
+ // top 1s grace. A valid cache or a quick registry answer lands
1087
+ // inside it and the report never notices the wait.
1088
+ // bottom 1s more for the probe still in flight, then a forced
1089
+ // re-probe with the full NOTICE_STATUS_TIMEOUT_MS budget.
1090
+ // If even that is silent, the verdict says so explicitly
1091
+ // rather than leaving a missing line to be read as
1092
+ // "you are up to date".
1093
+ // So the report costs at most 1s up front, and the verdict is
1094
+ // printed at exactly one terminal point, which no early
1095
+ // `process.exit()` in a branch below can truncate.
1084
1096
  const { UPDATER } = require('./modules/constants');
1085
- const versionStatus = await maybePrintVersionStatus({
1097
+ const { startStagedVersionStatus, printVersionStatusOrHeader } = require('./modules/version_notice');
1098
+ const versionWait = startStagedVersionStatus({
1099
+ graceMs: UPDATER.NOTICE_STAGE_GRACE_MS,
1086
1100
  timeoutMs: UPDATER.NOTICE_STATUS_TIMEOUT_MS,
1087
- indent: '',
1088
- surround: false,
1101
+ // DEXBOT_VERSION_CHECK_FORCE=1 re-probes instead of answering
1102
+ // from the cache: the escape hatch when a cached failure is
1103
+ // indistinguishable from a live one.
1104
+ force: Config.DEXBOT_VERSION_CHECK_FORCE,
1089
1105
  });
1090
- if (!versionStatus)
1091
- console.log(`DEXBot2 v${Config.VERSION}`);
1106
+ // Top-of-report grace. The VALUE is unused on purpose, only the
1107
+ // timing matters: `settled` is what gets displayed at the end.
1108
+ await versionWait.quick;
1092
1109
  console.log();
1110
+ // The ONE terminal point of this command: every branch below ends
1111
+ // in `finish(...)` instead of `process.exit(...)`, so the deferred
1112
+ // version line is always printed — including on the "no processes"
1113
+ // and delegated-`unlock status` paths, which used to exit before
1114
+ // the probe had anything to say.
1115
+ const finish = async (code) => {
1116
+ // Blank line, then the verdict: it is the last thing the
1117
+ // operator reads, so it gets its own block at the bottom. With
1118
+ // the check switched off, the shared helper falls back to the
1119
+ // bare "DEXBot2 vX.Y.Z" header, so the running build is always
1120
+ // named - the inline path's long-standing behaviour.
1121
+ console.log();
1122
+ printVersionStatusOrHeader(await versionWait.settled, { indent: '', surround: false });
1123
+ process.exit(code);
1124
+ return true;
1125
+ };
1093
1126
  const { spawnSync, execSync } = require('child_process');
1094
1127
  const MONOLITHIC_PID_FILE = PATHS.PROFILES.MONOLITHIC_PID;
1095
1128
  const MONOLITHIC_CRED_PID_FILE = PATHS.PROFILES.MONOLITHIC_CRED_PID;
@@ -1149,22 +1182,19 @@ async function handleCLICommands() {
1149
1182
  cwd: PATHS.PROJECT_ROOT,
1150
1183
  stdio: 'inherit',
1151
1184
  });
1152
- process.exit(result.status ?? 0);
1153
- return true;
1185
+ return finish(result.status ?? 0);
1154
1186
  }
1155
1187
  try {
1156
1188
  const output = execSync('pm2 jlist 2>/dev/null', { encoding: 'utf8', timeout: 5000 }).toString().trim();
1157
1189
  const jsonStart = output.indexOf('[');
1158
1190
  if (jsonStart === -1) {
1159
1191
  console.log('No DEXBot2 processes running.');
1160
- process.exit(0);
1161
- return true;
1192
+ return finish(0);
1162
1193
  }
1163
1194
  const allProcs = JSON.parse(output.slice(jsonStart));
1164
1195
  if (!Array.isArray(allProcs) || allProcs.length === 0) {
1165
1196
  console.log('No DEXBot2 processes running.');
1166
- process.exit(0);
1167
- return true;
1197
+ return finish(0);
1168
1198
  }
1169
1199
  const serviceNames = new Set(['dexbot-cred', 'dexbot-adapter', 'dexbot-update']);
1170
1200
  const botNames = new Set();
@@ -1183,8 +1213,7 @@ async function handleCLICommands() {
1183
1213
  });
1184
1214
  if (dexbotProcs.length === 0) {
1185
1215
  console.log('No DEXBot2 processes running.');
1186
- process.exit(0);
1187
- return true;
1216
+ return finish(0);
1188
1217
  }
1189
1218
  console.log('='.repeat(50));
1190
1219
  console.log('DEXBot2 PM2 Processes');
@@ -1235,8 +1264,7 @@ async function handleCLICommands() {
1235
1264
  catch {
1236
1265
  console.log('No DEXBot2 processes running.');
1237
1266
  }
1238
- process.exit(0);
1239
- return true;
1267
+ return finish(0);
1240
1268
  }
1241
1269
  case 'delete':
1242
1270
  case 'stop':