dexbot 1.6.9 → 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 (47) hide show
  1. package/CHANGELOG.md +18 -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 +13 -8
  20. package/dist/market_adapter/core/strategies/ama_slope_model.d.ts +2 -2
  21. package/dist/market_adapter/core/strategies/ama_slope_model.js +12 -10
  22. package/dist/market_adapter/core/strategies/dynamic_weight_series.d.ts +41 -14
  23. package/dist/market_adapter/core/strategies/dynamic_weight_series.js +138 -30
  24. package/dist/market_adapter/lp_chart_strategy_loader.js +2 -1
  25. package/dist/market_adapter/utils/chain.d.ts +1 -1
  26. package/dist/market_adapter/utils/chain.js +8 -6
  27. package/dist/modules/account_bots.js +5 -4
  28. package/dist/modules/bitshares-native/resolvers.js +5 -0
  29. package/dist/modules/bot_settings.js +13 -1
  30. package/dist/modules/chain_orders.js +2 -1
  31. package/dist/modules/constants.d.ts +6 -0
  32. package/dist/modules/constants.js +23 -1
  33. package/dist/modules/credential_policy.js +4 -1
  34. package/dist/modules/credit_runtime.js +5 -1
  35. package/dist/modules/order/utils/system.js +11 -1
  36. package/dist/modules/utils/asset_symbols.d.ts +59 -0
  37. package/dist/modules/utils/asset_symbols.js +128 -0
  38. package/dist/scripts/analyze-credit.js +10 -7
  39. package/dist/scripts/chart_command.js +12 -4
  40. package/dist/scripts/verify-browser-bundle.js +8 -0
  41. package/docs/DEXBOT_COMPARISON.md +3 -3
  42. package/docs/EVOLUTION.md +9 -8
  43. package/docs/FUND_MOVEMENT_AND_ACCOUNTING.md +1 -1
  44. package/docs/GRID_RECALCULATION.md +22 -3
  45. package/docs/README.md +1 -1
  46. package/market_adapter/README.md +2 -2
  47. 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
@@ -95,15 +95,19 @@ const fundRegistry = require('./modules/fund_registry');
95
95
  */
96
96
  const _collateralAssetIdCache = new Map();
97
97
  async function _resolveCollateralAssetId(ref) {
98
- if (_collateralAssetIdCache.has(ref))
99
- 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;
100
104
  let result = null;
101
105
  try {
102
- if (typeof ref === 'string' && ref.startsWith('1.3.')) {
103
- result = ref;
106
+ if (key.startsWith('1.3.')) {
107
+ result = key;
104
108
  }
105
- else if (typeof ref === 'string') {
106
- const res = await BitShares.db.lookup_asset_symbols([ref]);
109
+ else if (key) {
110
+ const res = await BitShares.db.lookup_asset_symbols([key]);
107
111
  if (res && res[0] && res[0].id)
108
112
  result = String(res[0].id);
109
113
  }
@@ -111,7 +115,7 @@ async function _resolveCollateralAssetId(ref) {
111
115
  catch (_err) {
112
116
  result = null;
113
117
  }
114
- _collateralAssetIdCache.set(ref, result);
118
+ _collateralAssetIdCache.set(key, result);
115
119
  return result;
116
120
  }
117
121
  const { setupGracefulShutdown, registerCleanup, unregisterCleanup } = require('./modules/graceful_shutdown');
@@ -123,6 +127,7 @@ const credentialPolicy = require('./modules/credential_policy');
123
127
  const { Config } = require('./modules/config');
124
128
  const { getErrorMessage } = require('./modules/utils/errors');
125
129
  const { isSameBotName } = require('./modules/utils/sanitize_key');
130
+ const { normalizeAssetRef } = require('./modules/utils/asset_symbols');
126
131
  // Setup graceful shutdown handlers
127
132
  // Setup graceful shutdown handlers
128
133
  setupGracefulShutdown();
@@ -589,7 +594,7 @@ async function runBotInstances(botEntries, { forceDryRun = false, sourceName = '
589
594
  const collateralRef = item.collateralAsset;
590
595
  if (!collateralRef)
591
596
  continue;
592
- const collateralAssetId = _collateralAssetIdCache.get(collateralRef) ?? null;
597
+ const collateralAssetId = _collateralAssetIdCache.get(normalizeAssetRef(collateralRef)) ?? null;
593
598
  if (!collateralAssetId) {
594
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.`);
595
600
  continue;
@@ -1,4 +1,4 @@
1
- import { computeAverageAmaSlopePct, computeAmaSlopeClipThreshold, createAmaSlopeClipTracker } from './dynamic_weight_series.js';
1
+ import { computeAverageAmaSlopePct, computeHuberWindowSlopePct, computeAmaSlopeClipThreshold, createAmaSlopeClipTracker } from './dynamic_weight_series.js';
2
2
  /**
3
3
  * Compute AMA slope and volatility offsets from the AMA series.
4
4
  *
@@ -31,5 +31,5 @@ declare function computeAmaSlopeWeights(amaValues: any, weightVariance: any, opt
31
31
  trend: string;
32
32
  isReady: boolean;
33
33
  };
34
- export { computeAmaSlopeWeights, computeAverageAmaSlopePct, computeAmaSlopeClipThreshold, createAmaSlopeClipTracker, };
34
+ export { computeAmaSlopeWeights, computeAverageAmaSlopePct, computeHuberWindowSlopePct, computeAmaSlopeClipThreshold, createAmaSlopeClipTracker, };
35
35
  //# sourceMappingURL=ama_slope_model.d.ts.map
@@ -6,7 +6,7 @@ import { normalizeMaxVolatilityOffset, normalizeVolatilityThreshold, } from '../
6
6
  import { computeVolatilityShift } from './volatility_shift.js';
7
7
  // Canonical AMA slope % lives in dynamic_weight_series.ts (self-contained so the
8
8
  // chart generators can embed its exact source); re-exported here for compat.
9
- import { computeAverageAmaSlopePct, computeAmaSlopeClipThreshold, createAmaSlopeClipTracker, } from './dynamic_weight_series.js';
9
+ import { computeAverageAmaSlopePct, computeHuberWindowSlopePct, computeAmaSlopeClipThreshold, createAmaSlopeClipTracker, } from './dynamic_weight_series.js';
10
10
  const _DEFAULT_AMA_KEY = MARKET_ADAPTER.DEFAULT_AMA_KEY;
11
11
  const DEFAULT_ER_PERIOD = MARKET_ADAPTER.AMAS[_DEFAULT_AMA_KEY].erPeriod;
12
12
  /**
@@ -74,14 +74,16 @@ function computeAmaSlopeWeights(amaValues, weightVariance, opts = {}) {
74
74
  return notReady;
75
75
  }
76
76
  const N = amaValues.length;
77
- const last = amaValues[N - 1];
78
- const past = amaValues[N - 1 - lookbackBars];
79
- if (!Number.isFinite(last) || !Number.isFinite(past) || past === 0) {
80
- return notReady;
81
- }
82
- // 2. Average slope percent per bar over the lookback window. This keeps
83
- // lookback as a smoothing/lag knob instead of adding gain in sustained trends.
84
- const slopePct = computeAverageAmaSlopePct(last, past, lookbackBars);
77
+ // 2. Slope percent per bar over the lookback window, as a Huber-robust
78
+ // linear regression of ln(AMA) (canonical: computeHuberWindowSlopePct). The
79
+ // two-point endpoint difference is kept in dynamic_weight_series as the
80
+ // reference definition, but it gives the window-edge bar full weight: a
81
+ // single-bar impulse moves it 7x-70x the reset gate while the robust fit
82
+ // bounds that influence without the lag of a rank-based estimator.
83
+ // lookback stays a smoothing/lag knob rather than adding gain in sustained
84
+ // trends. The estimator validates every bar in the window (both ends
85
+ // strictly positive), so it subsumes the old two-endpoint guard here.
86
+ const slopePct = computeHuberWindowSlopePct(amaValues, N - 1, lookbackBars);
85
87
  if (!Number.isFinite(slopePct)) {
86
88
  return notReady;
87
89
  }
@@ -130,5 +132,5 @@ function computeAmaSlopeWeights(amaValues, weightVariance, opts = {}) {
130
132
  // computeAmaSlopeClipThreshold and createAmaSlopeClipTracker live in
131
133
  // dynamic_weight_series.ts (self-contained so the chart generators can embed
132
134
  // their exact source); re-exported here so Node callers keep this import path.
133
- export { computeAmaSlopeWeights, computeAverageAmaSlopePct, computeAmaSlopeClipThreshold, createAmaSlopeClipTracker, };
135
+ export { computeAmaSlopeWeights, computeAverageAmaSlopePct, computeHuberWindowSlopePct, computeAmaSlopeClipThreshold, createAmaSlopeClipTracker, };
134
136
  //# sourceMappingURL=ama_slope_model.js.map
@@ -1,20 +1,47 @@
1
+ declare function computeAverageAmaSlopePct(current: any, past: any, lookbackBars: any): number | null;
1
2
  /**
2
- * Dynamic weight per-bar series — canonical implementation shared by the live
3
- * market adapter service, the research test harness, and the browser-embedded
4
- * dynamic-weight chart script.
3
+ * Per-bar AMA trend in %/bar over `lookbackBars`, fitted as a Huber-robust
4
+ * linear regression of ln(AMA) against bar index (uniform weights, no kernel).
5
+ *
6
+ * This is the canonical slope used by the live adapter (dynamic weight series,
7
+ * AMA slope model, both clip paths), the grid-reset replay and the research
8
+ * charts, which embed this exact source via `embedFunctionSources`. One
9
+ * definition, one set of numbers — do not re-implement it per caller. Selected
10
+ * experimentally on a real 1h pool: it is the smoothest robust option measured
11
+ * (second-difference energy ~25x lower than the median's, max |dSlope|
12
+ * comparable to the two-point endpoint), because its influence function is
13
+ * continuous and bounded rather than an order statistic.
14
+ *
15
+ * The fit is local linear over `lookbackBars` intervals (bars+1 points, the same
16
+ * 20h span the endpoint uses), so a window-wide regime change tilts the line
17
+ * continuously instead of waiting for a majority, and a lone off-trend spike is
18
+ * bounded rather than given full endpoint weight. Output is the log-return per
19
+ * bar x 100. That differs from the arithmetic per-bar return by ~beta^2/2,
20
+ * which is negligible at the sub-0.1 %/bar magnitudes the defaults use (order
21
+ * 1e-9 at 0.1 %/bar) but grows quadratically with the reading — ln(1.06)*100 =
22
+ * 5.83, ~3% below a 6%/bar arithmetic rate. A pre-existing user override of
23
+ * maxSlopePct / neutralZonePct was tuned against the arithmetic reading, so a
24
+ * saturated override now clamps a hair tighter than before.
5
25
  *
6
- * Computes the per-bar AMA/Kalman offset channels, the alpha-blended combined
7
- * series, the pre-gain dead-band gate, the final gain/clamp, and the signal
8
- * confirmation latch — the exact shape both the live `_computeDynamicWeights`
9
- * and the interactive research chart render.
26
+ * Persistence note: `slopePct` is a different quantity from any pre-Huber
27
+ * reading (log-return regression vs the old median/endpoint). The first cycle
28
+ * after deploying compares a Huber reading against the still-persisted old
29
+ * baseline (botState.gridRangeScalingAmaSlope); the two magnitudes agree
30
+ * closely, so that delta sits below the reset gate on ~98% of bars (p50
31
+ * 0.00043, p90 0.00277 %/bar) — roughly one whitelisted bot in fifty costs one
32
+ * extra recenter, once. No version marker is persisted to suppress it.
10
33
  *
11
- * This module is intentionally fully self-contained (no imports): the chart
12
- * generator embeds its exact source into generated HTML via fn.toString(), so
13
- * every consumer runs one logic path. The pure helper computeAverageAmaSlopePct
14
- * is re-exported by strategies/ama_slope_model.ts so Node callers keep their
15
- * existing import path.
34
+ * Parameters come from MARKET_ADAPTER.DYNAMIC_WEIGHT_AMA_HUBER (aliased as
35
+ * AMA_SLOPE_HUBER; injected into generated charts). `hub` is overridable only so
36
+ * tests can prove the values are threaded through — production never passes it.
37
+ *
38
+ * @param amaValues Full AMA series (index-addressable).
39
+ * @param index Bar to measure at (evaluated at the window edge).
40
+ * @param lookbackBars Window length in bars (fixed at 20 for every estimator).
41
+ * @param hub Parameter block; defaults to the centralized constant.
42
+ * @returns %/bar, or null when the window is unusable.
16
43
  */
17
- declare function computeAverageAmaSlopePct(current: any, past: any, lookbackBars: any): number | null;
44
+ declare function computeHuberWindowSlopePct(amaValues: any, index: number, lookbackBars: any, hub?: any): number | null;
18
45
  declare function echoLatchSeries(appliedSeries: any[], preGainSeries: any[], confirmBars: any): {
19
46
  echoedAppliedSeries: any[];
20
47
  echoedPreGainSeries: any[];
@@ -74,5 +101,5 @@ declare function computeAmaSlopeClipThreshold(amaValues: any, erPeriod: number,
74
101
  declare function createAmaSlopeClipTracker(erPeriod: number, lookbackBars: number, clipPercentile: number): {
75
102
  push(value: number): number;
76
103
  };
77
- export { computeDynamicWeightSeries, computeAverageAmaSlopePct, echoLatchSeries, roundToN, computeAmaSlopeClipThreshold, createAmaSlopeClipTracker, percentileFromSorted, };
104
+ export { computeDynamicWeightSeries, computeAverageAmaSlopePct, computeHuberWindowSlopePct, echoLatchSeries, roundToN, computeAmaSlopeClipThreshold, createAmaSlopeClipTracker, percentileFromSorted, };
78
105
  //# sourceMappingURL=dynamic_weight_series.d.ts.map