dexbot 1.6.9 → 1.6.11

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 (96) hide show
  1. package/CHANGELOG.md +34 -0
  2. package/README.md +1 -0
  3. package/analysis/README.md +50 -12
  4. package/analysis/bot_fitting/README.md +12 -0
  5. package/analysis/tradingview/README.md +15 -10
  6. package/analysis/trend_detection/DYNAMIC_WEIGHT_RESEARCH.md +10 -36
  7. package/analysis/trend_detection/README.md +31 -0
  8. package/claw/modules/chain_queries.ts +9 -4
  9. package/claw/modules/claw_bridge.ts +9 -9
  10. package/claw/package.json +1 -1
  11. package/claw/runtimes/openclaw-plugin/openclaw.plugin.json +1 -1
  12. package/claw/runtimes/openclaw-plugin/package.json +1 -1
  13. package/dist/analysis/account_resolver.js +13 -1
  14. package/dist/analysis/ama_fitting/optimizer_high_resolution.js +2 -1
  15. package/dist/analysis/analyze_dynamic_weight.js +0 -3
  16. package/dist/analysis/bot_fitting/backtest_ama_sweep.js +52 -8
  17. package/dist/analysis/bot_fitting/backtest_bot_fitting.js +68 -10
  18. package/dist/analysis/bot_fitting/backtest_lookback_drawdown.d.ts +21 -0
  19. package/dist/analysis/bot_fitting/backtest_lookback_drawdown.js +315 -0
  20. package/dist/analysis/bot_key_utils.js +17 -17
  21. package/dist/analysis/fills_cache.d.ts +64 -0
  22. package/dist/analysis/fills_cache.js +254 -0
  23. package/dist/analysis/fills_source.js +5 -2
  24. package/dist/analysis/pnl_report.d.ts +39 -0
  25. package/dist/analysis/pnl_report.js +325 -0
  26. package/dist/analysis/resolve_source.d.ts +0 -1
  27. package/dist/analysis/trade_profitability.d.ts +11 -2
  28. package/dist/analysis/trade_profitability.js +187 -61
  29. package/dist/analysis/tradingview/analyze_tradingview.d.ts +0 -3
  30. package/dist/analysis/tradingview/analyze_tradingview.js +6 -19
  31. package/dist/analysis/tradingview/grid_reset_config.d.ts +2 -0
  32. package/dist/analysis/tradingview/grid_reset_config.js +18 -1
  33. package/dist/analysis/tradingview/grid_reset_sim.d.ts +12 -1
  34. package/dist/analysis/tradingview/grid_reset_sim.js +60 -11
  35. package/dist/analysis/tradingview/tradingview_uplot_chart_generator.js +180 -33
  36. package/dist/analysis/trend_detection/backtest_ama_slope_huber.d.ts +102 -0
  37. package/dist/analysis/trend_detection/backtest_ama_slope_huber.js +725 -0
  38. package/dist/analysis/trend_detection/dynamic_weight_chart_generator.js +29 -110
  39. package/dist/analysis/trend_detection/huber_scale_variants.d.ts +34 -0
  40. package/dist/analysis/trend_detection/huber_scale_variants.js +176 -0
  41. package/dist/dexbot.js +19 -11
  42. package/dist/market_adapter/core/market_adapter_service.d.ts +15 -0
  43. package/dist/market_adapter/core/market_adapter_service.js +64 -5
  44. package/dist/market_adapter/core/strategies/ama.d.ts +1 -1
  45. package/dist/market_adapter/core/strategies/ama.js +5 -28
  46. package/dist/market_adapter/core/strategies/ama_slope_model.d.ts +2 -2
  47. package/dist/market_adapter/core/strategies/ama_slope_model.js +12 -10
  48. package/dist/market_adapter/core/strategies/dynamic_weight_series.d.ts +41 -14
  49. package/dist/market_adapter/core/strategies/dynamic_weight_series.js +138 -30
  50. package/dist/market_adapter/inputs/fetch_cex_synthetic_data.js +1 -2
  51. package/dist/market_adapter/log_format.js +1 -2
  52. package/dist/market_adapter/lp_chart_strategy_loader.js +2 -1
  53. package/dist/market_adapter/market_adapter.d.ts +0 -1
  54. package/dist/market_adapter/market_adapter.js +2 -27
  55. package/dist/market_adapter/utils/chain.d.ts +1 -1
  56. package/dist/market_adapter/utils/chain.js +8 -6
  57. package/dist/modules/account_bots.js +5 -4
  58. package/dist/modules/bitshares-native/resolvers.js +5 -0
  59. package/dist/modules/bot_settings.js +13 -1
  60. package/dist/modules/chain_orders.js +2 -1
  61. package/dist/modules/constants.d.ts +9 -1
  62. package/dist/modules/constants.js +55 -9
  63. package/dist/modules/credential_policy.js +4 -1
  64. package/dist/modules/credit_runtime.js +5 -1
  65. package/dist/modules/dexbot_maintenance_runtime.js +12 -0
  66. package/dist/modules/order/accounting.js +25 -0
  67. package/dist/modules/order/format.d.ts +35 -15
  68. package/dist/modules/order/format.js +62 -16
  69. package/dist/modules/order/manager.d.ts +1 -0
  70. package/dist/modules/order/manager.js +22 -1
  71. package/dist/modules/order/sync_engine.js +15 -1
  72. package/dist/modules/order/utils/order.d.ts +21 -1
  73. package/dist/modules/order/utils/order.js +80 -2
  74. package/dist/modules/order/utils/system.js +11 -1
  75. package/dist/modules/paths.d.ts +2 -0
  76. package/dist/modules/paths.js +2 -0
  77. package/dist/modules/utils/asset_symbols.d.ts +59 -0
  78. package/dist/modules/utils/asset_symbols.js +128 -0
  79. package/dist/modules/utils/time_range.d.ts +15 -0
  80. package/dist/modules/utils/time_range.js +18 -0
  81. package/dist/scripts/analyze-credit.js +10 -7
  82. package/dist/scripts/analyze-orders.js +1 -44
  83. package/dist/scripts/chart_command.js +15 -8
  84. package/dist/scripts/pnl.d.ts +3 -0
  85. package/dist/scripts/pnl.js +40 -0
  86. package/dist/scripts/verify-browser-bundle.js +8 -0
  87. package/dist/unlock.js +34 -0
  88. package/docs/DEXBOT_COMPARISON.md +3 -3
  89. package/docs/EVOLUTION.md +12 -10
  90. package/docs/FUND_MOVEMENT_AND_ACCOUNTING.md +1 -1
  91. package/docs/GRID_RECALCULATION.md +33 -17
  92. package/docs/README.md +2 -2
  93. package/docs/WORKFLOW.md +1 -0
  94. package/market_adapter/README.md +6 -28
  95. package/package.json +1 -1
  96. package/scripts/README.md +14 -0
@@ -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, 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';
@@ -10,7 +10,7 @@ import { Y_AXIS_SIZE, makeCursorConfig, bindHoverStateFn, wireChartEvents, zoomR
10
10
  // Browser-embedded shared functions — the interactive chart runs the exact same
11
11
  // pure logic as the live market adapter service instead of a hand-copied copy.
12
12
  const EMBEDDED_SHARED_FUNCS = embedFunctionSources([
13
- computeAverageAmaSlopePct,
13
+ computeHuberWindowSlopePct,
14
14
  computeAmaSlopeClipThreshold,
15
15
  bilinearInterpolate,
16
16
  echoLatchSeries,
@@ -32,7 +32,6 @@ function generateHTML(data, title = 'Dynamic Weight Research') {
32
32
  const AMA_MS_MIN = 0.06, AMA_MS_MAX = 0.12;
33
33
  const KAL_MS_MIN = 0.5, KAL_MS_MAX = 1.5;
34
34
  const CLIP_PCT_MAX = 20;
35
- const EMA_MIN = 0, EMA_MAX = 32;
36
35
  const TH_MIN = 0, TH_MAX = 0.5;
37
36
  const KF_MIN = 0, KF_MAX = 200;
38
37
  const KFD_MIN = 1.0, KFD_MAX = 3.0;
@@ -46,7 +45,6 @@ function generateHTML(data, title = 'Dynamic Weight Research') {
46
45
  dispWeight: [0, 1],
47
46
  neutralZonePct: [0, 1],
48
47
  lookbackBars: [LB_MIN, LB_MAX],
49
- amaEmaSpan: [EMA_MIN, EMA_MAX],
50
48
  amaMaxSlopePct: [AMA_MS_MIN, AMA_MS_MAX],
51
49
  kalmanMaxSlopePct: [KAL_MS_MIN, KAL_MS_MAX],
52
50
  clipPct: [0, CLIP_PCT_MAX],
@@ -106,10 +104,6 @@ function generateHTML(data, title = 'Dynamic Weight Research') {
106
104
  const defaultKalmanDispThresholdMult = data.kalmanDispThresholdMult ?? MARKET_ADAPTER.DYNAMIC_WEIGHT_KALMAN_DISP_THRESHOLD_MULT_DEFAULT;
107
105
  const defaultKalmanSmoothSpanPct = data.kalmanSmoothSpanPct ?? MARKET_ADAPTER.DYNAMIC_WEIGHT_KALMAN_SMOOTH_SPAN_PCT_DEFAULT;
108
106
  const defaultSignalConfirmBars = data.signalConfirmBars ?? MARKET_ADAPTER.DYNAMIC_WEIGHT_SIGNAL_CONFIRM_BARS_DEFAULT;
109
- // Research-only `ema` knob: EMA span in bars over the AMA input before the
110
- // slope is taken. 0 (default) = off, keeps the raw AMA input.
111
- const defaultAmaEmaSpanRaw = data.amaEmaSpan ?? ma.amaEmaSpan ?? 0;
112
- const defaultAmaEmaSpan = Math.round(Math.min(EMA_MAX, Math.max(EMA_MIN, Number.isFinite(defaultAmaEmaSpanRaw) ? defaultAmaEmaSpanRaw : EMA_MIN)));
113
107
  const regimeInitSlider = Math.round(defaultRegimeSensitivity * 100);
114
108
  const interval = results.length > 1 ?
115
109
  (new Date(results[1].timestamp).getTime() - new Date(results[0].timestamp).getTime()) / 1000 : 3600;
@@ -136,8 +130,7 @@ function generateHTML(data, title = 'Dynamic Weight Research') {
136
130
  const amaErPeriod = data.amaConfig?.erPeriod ?? MARKET_ADAPTER.AMAS[defaultAmaKey].erPeriod;
137
131
  const amaSlowPeriod = data.amaConfig?.slowPeriod ?? MARKET_ADAPTER.AMAS[defaultAmaKey].slowPeriod;
138
132
  const amaFastPeriod = data.amaConfig?.fastPeriod ?? MARKET_ADAPTER.AMAS[defaultAmaKey].fastPeriod;
139
- const amaErSmoothPeriod = data.amaConfig?.erSmoothPeriod ?? 0;
140
- const amaWarmupBars = getAmaWarmupBars(amaErPeriod, amaSlowPeriod, lookbackBars, amaFastPeriod, amaErSmoothPeriod);
133
+ const amaWarmupBars = getAmaWarmupBars(amaErPeriod, amaSlowPeriod, lookbackBars, amaFastPeriod);
141
134
  const amaSlopeReadyBars = Math.ceil(amaErPeriod) + lookbackBars;
142
135
  const amaSeedSmaLine = new Array(results.length).fill(null);
143
136
  const amaSeedWindowEnd = Math.min(results.length - 1, Math.ceil(amaErPeriod));
@@ -175,16 +168,6 @@ function generateHTML(data, title = 'Dynamic Weight Research') {
175
168
  amaSeedSmaLine.push(null);
176
169
  }
177
170
  const realBarCount = results.length;
178
- function maxAbsPct(arr) {
179
- let m = 0;
180
- for (let i = 0; i < realBarCount; i++) {
181
- if (arr[i] != null && Math.abs(arr[i]) > m)
182
- m = Math.abs(arr[i]);
183
- }
184
- return m || 4;
185
- }
186
- const amaPctMax = Math.ceil(maxAbsPct(amaSlopePct) * 1.15) || 5;
187
- const kalPctMax = Math.ceil(Math.max(maxAbsPct(kalmanVelocityPct), maxAbsPct(kalmanDisplacementPct)) * 1.15) || 5;
188
171
  function buildPercentiles(arr, startIndex = 0) {
189
172
  const safeStartIndex = Math.max(0, Math.min(realBarCount, Math.ceil(startIndex)));
190
173
  const sorted = [];
@@ -207,7 +190,6 @@ function generateHTML(data, title = 'Dynamic Weight Research') {
207
190
  }
208
191
  const amaPercentiles = buildPercentiles(amaSlopePct, amaSlopeReadyBars);
209
192
  const kalPercentiles = buildPercentiles(kalmanVelocityPct);
210
- const maxDispPct = Math.ceil(maxAbsPct(kalmanDisplacementPct) * 1.15) || 5;
211
193
  return `<!DOCTYPE html>
212
194
  <html lang="en">
213
195
  <head>
@@ -224,7 +206,7 @@ function generateHTML(data, title = 'Dynamic Weight Research') {
224
206
  .legend-item { gap: 3px; }
225
207
  .legend-val { font-family: monospace; display: inline-block; text-align: right; min-width: 45px; }
226
208
  #l-price, #l-ama3 { min-width: 62px; }
227
- #l-ama-slope, #l-ama-slope-raw, #l-kal-vel, #l-kal-disp { min-width: 54px; }
209
+ #l-ama-slope, #l-kal-vel, #l-kal-disp { min-width: 54px; }
228
210
  #l-signal, #l-signal-latched { min-width: 70px; text-align: left; }
229
211
  #l-combined-raw, #l-combined-echo { min-width: 42px; }
230
212
  #l-mult { min-width: 38px; }
@@ -269,9 +251,6 @@ function generateHTML(data, title = 'Dynamic Weight Research') {
269
251
  .ctrl.lb label { min-width: 20px; }
270
252
  .ctrl.lb input[type="range"] { accent-color: #39d0d8; width: 80px; }
271
253
  .ctrl.lb .val { color: #39d0d8; }
272
- .ctrl.ema label { min-width: 20px; }
273
- .ctrl.ema input[type="range"] { accent-color: #f0a000; width: 80px; }
274
- .ctrl.ema .val { color: #f0a000; }
275
254
  .ctrl.off input[type="range"] { accent-color: #3fb950; }
276
255
  .ctrl.off .val { color: #3fb950; }
277
256
  .ctrl.nz input[type="range"] { accent-color: #8b949e; }
@@ -317,7 +296,6 @@ function generateHTML(data, title = 'Dynamic Weight Research') {
317
296
  <div class="section-label">AMA SLOPE INPUT</div>
318
297
  <div class="legend">
319
298
  <div class="legend-item"><div class="dot" style="background:#f0a000;"></div>Slope‰: <span id="l-ama-slope" class="legend-val" style="font-weight:bold;">-</span></div>
320
- <div class="legend-item"><div class="dot" style="background:#8b949e;"></div>Raw‰: <span id="l-ama-slope-raw" class="legend-val">-</span></div>
321
299
  </div>
322
300
  <div id="ama-chart"></div>
323
301
  </div>
@@ -348,7 +326,6 @@ function generateHTML(data, title = 'Dynamic Weight Research') {
348
326
  <div class="group-sep"></div>
349
327
  <div class="ctrl nz"><label for="nz-slider">nz%</label><input type="range" id="nz-slider" min="0" max="100" value="${Math.round(defaultNeutralZone * 100)}" title="Neutral Zone %"><span class="val" id="nz-value">${defaultNeutralZone.toFixed(2)}</span></div>
350
328
  <div class="ctrl lb"><label for="lb-slider">lb</label><input type="range" id="lb-slider" min="0" max="1000" value="${lbInitSlider}" title="Lookback Bars (${LB_MIN}-${LB_MAX})"><span class="val" id="lb-value">${lookbackBars}</span></div>
351
- <div class="ctrl ema"><label for="ema-slider">ema</label><input type="range" id="ema-slider" min="${EMA_MIN}" max="${EMA_MAX}" value="${defaultAmaEmaSpan}" title="AMA input EMA span in bars (${EMA_MIN} = off; noise std ~ 1/sqrt(span), lag ~ (span-1)/2 bars; span ~ lb is the balance point)"><span class="val" id="ema-value">${defaultAmaEmaSpan}</span></div>
352
329
  <div class="ctrl ms-ama"><label for="ama-ms-slider">amaS%</label><input type="range" id="ama-ms-slider" min="0" max="1000" value="${amaMsInitSlider}" title="AMA Max Slope % per bar (${AMA_MS_MIN}-${AMA_MS_MAX})"><span class="val" id="ama-ms-value">${defaultAmaMaxSlopePct.toFixed(4)}</span></div>
353
330
  <div class="ctrl clip"><label for="clip-slider">clip%</label><input type="range" id="clip-slider" min="0" max="${CLIP_PCT_MAX}" value="${Math.min(defaultClipPct, CLIP_PCT_MAX)}" title="Outlier Clip %"><span class="val" id="clip-value">${Math.min(defaultClipPct, CLIP_PCT_MAX)}%</span></div>
354
331
 
@@ -382,11 +359,15 @@ function generateHTML(data, title = 'Dynamic Weight Research') {
382
359
  </div>
383
360
  </div>
384
361
 
385
- <script id="payload" type="application/json">${serializeJsonForScript({ dates, prices, hurstArr, peArr, hurstSegments, peSegments, ama3Prices, amaSeedSmaLine, amaSlopePct, kalmanVelocityPctRaw, kalmanVelocityPct, kalmanDisplacementPct, kalmanIsReady, signals, alpha: defaultAlpha, gain: defaultGain, kalmanSmoothPct: defaultKalmanSmoothPct, kalmanDispScaleMult: defaultKalmanDispScaleMult, kalmanDispThresholdMult: defaultKalmanDispThresholdMult, kalmanSmoothSpanPct: defaultKalmanSmoothSpanPct, signalConfirmBars: defaultSignalConfirmBars, neutralZonePct: defaultNeutralZone, dispWeight: defaultDispWeight, amaMaxSlopePct: defaultAmaMaxSlopePct, kalmanMaxSlopePct: defaultKalmanMaxSlopePct, maxDispPct, clipPct: defaultClipPct, minOutputThreshold: defaultMinOutputThreshold, outputClamp: defaultOutputClamp, regimeSensitivity: defaultRegimeSensitivity, absoluteThreshold: defaultAbsoluteThreshold, lookbackBars, amaErPeriod, amaSlowPeriod, amaWarmupBars, amaSlopeReadyBars, realBarCount, amaPctMax, kalPctMax, amaPercentiles, kalPercentiles, amaSlopeLogMin: AMA_MS_LOG_MIN_N, amaSlopeLogMax: AMA_MS_LOG_MAX_N, kalSlopeLogMin: KAL_MS_LOG_MIN_N, kalSlopeLogMax: KAL_MS_LOG_MAX_N, lbLogMin: LB_LOG_MIN_N, lbLogMax: LB_LOG_MAX_N, amaEmaSpan: defaultAmaEmaSpan, gainLogMin: GAIN_LOG_MIN_N, gainLogMax: GAIN_LOG_MAX_N, sliderRanges: SLIDER_RANGES, dispScaleMinPct: defaultDispScaleMinPct, weightMin: MARKET_ADAPTER.DYNAMIC_WEIGHT_MIN_WEIGHT, weightMax: MARKET_ADAPTER.DYNAMIC_WEIGHT_MAX_WEIGHT, marketAdapter: ma, amaWeightConfig, hNodes: [0.5 + MARKET_ADAPTER.HURST_ZONE_BAND, 0.5, 0.5 - MARKET_ADAPTER.HURST_ZONE_BAND], pNodes: MARKET_ADAPTER.PE_NODES, regimeTable: MARKET_ADAPTER.REGIME_TABLE })}</script>
362
+ <script id="payload" type="application/json">${serializeJsonForScript({ dates, prices, hurstArr, peArr, hurstSegments, peSegments, ama3Prices, amaSeedSmaLine, kalmanVelocityPctRaw, kalmanVelocityPct, kalmanDisplacementPct, kalmanIsReady, signals, alpha: defaultAlpha, gain: defaultGain, kalmanSmoothPct: defaultKalmanSmoothPct, kalmanDispScaleMult: defaultKalmanDispScaleMult, kalmanDispThresholdMult: defaultKalmanDispThresholdMult, kalmanSmoothSpanPct: defaultKalmanSmoothSpanPct, signalConfirmBars: defaultSignalConfirmBars, neutralZonePct: defaultNeutralZone, dispWeight: defaultDispWeight, amaMaxSlopePct: defaultAmaMaxSlopePct, kalmanMaxSlopePct: defaultKalmanMaxSlopePct, clipPct: defaultClipPct, minOutputThreshold: defaultMinOutputThreshold, outputClamp: defaultOutputClamp, regimeSensitivity: defaultRegimeSensitivity, absoluteThreshold: defaultAbsoluteThreshold, lookbackBars, amaErPeriod, amaSlowPeriod, amaWarmupBars, amaSlopeReadyBars, realBarCount, amaPercentiles, kalPercentiles, amaSlopeLogMin: AMA_MS_LOG_MIN_N, amaSlopeLogMax: AMA_MS_LOG_MAX_N, kalSlopeLogMin: KAL_MS_LOG_MIN_N, kalSlopeLogMax: KAL_MS_LOG_MAX_N, lbLogMin: LB_LOG_MIN_N, lbLogMax: LB_LOG_MAX_N, gainLogMin: GAIN_LOG_MIN_N, gainLogMax: GAIN_LOG_MAX_N, sliderRanges: SLIDER_RANGES, dispScaleMinPct: defaultDispScaleMinPct, weightMin: MARKET_ADAPTER.DYNAMIC_WEIGHT_MIN_WEIGHT, weightMax: MARKET_ADAPTER.DYNAMIC_WEIGHT_MAX_WEIGHT, marketAdapter: ma, amaWeightConfig, hNodes: [0.5 + MARKET_ADAPTER.HURST_ZONE_BAND, 0.5, 0.5 - MARKET_ADAPTER.HURST_ZONE_BAND], pNodes: MARKET_ADAPTER.PE_NODES, regimeTable: MARKET_ADAPTER.REGIME_TABLE })}</script>
386
363
 
387
364
  <script>
388
365
  const data = JSON.parse(document.getElementById('payload').textContent);
389
366
 
367
+ // Canonical Huber-slope parameters, injected from MARKET_ADAPTER so the
368
+ // embedded estimator runs the same values as the live adapter.
369
+ const AMA_SLOPE_HUBER = ${serializeJsonForScript(MARKET_ADAPTER.DYNAMIC_WEIGHT_AMA_HUBER)};
370
+
390
371
  ${EMBEDDED_SHARED_FUNCS}
391
372
 
392
373
  const SYNC_KEY = "dyn-wt-res-v4";
@@ -424,8 +405,7 @@ function generateHTML(data, title = 'Dynamic Weight Research') {
424
405
  const kalMsSliderToVal = (pos) => Math.exp(KAL_MS_LOG_MIN + (pos / 1000) * (KAL_MS_LOG_MAX - KAL_MS_LOG_MIN));
425
406
 
426
407
  let currentLookbackBars = data.lookbackBars ?? ${JSON.stringify(lookbackBars)};
427
- let currentAmaEmaSpan = Math.max(SR.amaEmaSpan[0], Math.min(SR.amaEmaSpan[1], Math.round(data.amaEmaSpan ?? 0)));
428
- let currentAmaSource = data.ama3Prices;
408
+ const currentAmaSource = data.ama3Prices;
429
409
  const LB_LOG_MIN = data.lbLogMin;
430
410
  const LB_LOG_MAX = data.lbLogMax;
431
411
  const lbSliderToVal = (pos) => Math.round(Math.exp(LB_LOG_MIN + (pos / 1000) * (LB_LOG_MAX - LB_LOG_MIN)));
@@ -437,11 +417,10 @@ function generateHTML(data, title = 'Dynamic Weight Research') {
437
417
  const gainValToSlider = (val) => Math.round((Math.log(Math.max(Math.exp(GAIN_LOG_MIN), val)) - GAIN_LOG_MIN) / (GAIN_LOG_MAX - GAIN_LOG_MIN) * 1000);
438
418
 
439
419
  let currentClipPct = data.clipPct ?? ${JSON.stringify(defaultClipPct)};
440
- // Only the clipPct===0 branch value is ever read (recalcWeights reads
441
- // currentAmaClipThreshold solely when clipping is disabled; otherwise
442
- // it uses the canonical dynamicClipThreshold from computeAmaSlopeClipThreshold).
443
- const maxAmaSlope = data.amaPercentiles[data.amaPercentiles.length - 1];
444
- let currentAmaClipThreshold = currentClipPct === 0 ? maxAmaSlope : Infinity;
420
+ // The AMA clip threshold always comes from dynamicClipThreshold, which
421
+ // recalcInputs() recomputes via the canonical
422
+ // computeAmaSlopeClipThreshold (Infinity when clipping is disabled,
423
+ // matching the live adapter). No separate clipPct==0 branch is needed.
445
424
  let currentKalClipThreshold = currentClipPct === 0 ? Infinity : data.kalPercentiles[100 - currentClipPct];
446
425
 
447
426
  // Regime table and axis nodes from payload — sourced from MARKET_ADAPTER in constants.ts
@@ -455,7 +434,10 @@ function generateHTML(data, title = 'Dynamic Weight Research') {
455
434
  */
456
435
  function getRegimeMultiplier(H, PE) {
457
436
  if (H == null || PE == null) return 1.0;
458
- return bilinearInterpolate(H, PE, REGIME_TABLE, { hNodes: H_NODES, pNodes: P_NODES });
437
+ // NOTE: peNodes is the canonical option name read by
438
+ // bilinearInterpolate; a pNodes key silently falls back to the
439
+ // inline defaults.
440
+ return bilinearInterpolate(H, PE, REGIME_TABLE, { hNodes: H_NODES, peNodes: P_NODES });
459
441
  }
460
442
 
461
443
  let currentRegimeSensitivity = data.regimeSensitivity ?? ma.regimeSensitivity;
@@ -464,7 +446,6 @@ function generateHTML(data, title = 'Dynamic Weight Research') {
464
446
  const currentLatchedSignals = new Array(data.dates.length).fill(null);
465
447
  const dynamicAmaOff = new Array(data.dates.length).fill(null);
466
448
  const dynamicAmaSlopePct = new Array(data.dates.length).fill(null);
467
- const dynamicAmaSlopePctRaw = new Array(data.dates.length).fill(null);
468
449
  const dynamicKalOff = new Array(data.dates.length).fill(null);
469
450
  const combinedOff = new Array(data.dates.length).fill(null);
470
451
  const combinedSell = new Array(data.dates.length).fill(null);
@@ -579,40 +560,9 @@ function generateHTML(data, title = 'Dynamic Weight Research') {
579
560
  }
580
561
  }
581
562
 
582
- /**
583
- * Research-only ema knob — EMA low-pass over the AMA input before the
584
- * slope is taken (EMA-then-difference == difference-then-EMA, both are
585
- * linear filters). span bars, alpha = 2/(span+1): noise std shrinks ~
586
- * 1/sqrt(span), lag grows ~ (span-1)/2 bars. Seeded with an SMA over the
587
- * first 'span' finite values (mirrors the AMA seed SMA) so the transient
588
- * is gone before any slope bar can go ready. Nulls (warmup / trailing
589
- * padding) stay null so no fabricated values reach the clip-percentile
590
- * pool or the offset pipeline. span <= 0 returns the input untouched.
591
- */
592
- function buildEmaSeries(values, span) {
593
- if (!(span > 0) || !Array.isArray(values)) return values;
594
- const n = values.length;
595
- const out = new Array(n);
596
- const alpha = 2 / (span + 1);
597
- let seedSum = 0, seedCount = 0;
598
- for (let i = 0; i < n && seedCount < span; i++) {
599
- const v = values[i];
600
- if (v == null || !Number.isFinite(v)) continue;
601
- seedSum += v; seedCount++;
602
- }
603
- let prev = seedCount > 0 ? seedSum / seedCount : null;
604
- for (let i = 0; i < n; i++) {
605
- const v = values[i];
606
- if (v == null || !Number.isFinite(v)) { out[i] = null; continue; }
607
- prev = prev == null ? v : alpha * v + (1 - alpha) * prev;
608
- out[i] = prev;
609
- }
610
- return out;
611
- }
612
-
613
563
  function computeSlopeAtIndex(idx, lb, values) {
614
- // Canonical AMA slope % (computeAverageAmaSlopePct injected above).
615
- const sp = computeAverageAmaSlopePct(values[idx], values[idx - lb], lb);
564
+ // Canonical AMA slope % (computeHuberWindowSlopePct injected above).
565
+ const sp = computeHuberWindowSlopePct(values, idx, lb);
616
566
  return sp == null ? 0 : sp;
617
567
  }
618
568
 
@@ -620,7 +570,6 @@ function generateHTML(data, title = 'Dynamic Weight Research') {
620
570
  recalcKalmanVelocity();
621
571
  recalcKalmanClipThreshold();
622
572
  recalcLatchedSignals();
623
- currentAmaSource = buildEmaSeries(data.ama3Prices, currentAmaEmaSpan);
624
573
  const lb = currentLookbackBars;
625
574
  const amaErWarmup = Math.max(0, Number.isFinite(data.amaErPeriod) ? Math.ceil(data.amaErPeriod) : ${JSON.stringify(MARKET_ADAPTER.AMAS[MARKET_ADAPTER.DEFAULT_AMA_KEY].erPeriod)});
626
575
  const amaReadyBar = Math.max(lb, amaErWarmup + lb);
@@ -629,20 +578,13 @@ function generateHTML(data, title = 'Dynamic Weight Research') {
629
578
  // implementation (computeAmaSlopeClipThreshold injected above),
630
579
  // shared with the live market adapter service. Trailing padded
631
580
  // nulls beyond realBarCount are skipped by its finiteness guards.
632
- // Clip pool follows the (possibly EMA-filtered) AMA input so the
633
- // percentile threshold matches the series the offsets derive from.
634
581
  dynamicClipThreshold = computeAmaSlopeClipThreshold(currentAmaSource, amaErWarmup, lb, currentClipPct);
635
582
 
636
583
  for (let i = 0; i < data.realBarCount; i++) {
637
- // AMA slope % for the display panel (offsets computed in
638
- // recalcWeights): the raw reference line from the unfiltered AMA
639
- // input, the plotted series from the EMA-filtered input.
640
- dynamicAmaSlopePctRaw[i] = i < amaReadyBar ? null : computeSlopeAtIndex(i, lb, data.ama3Prices);
641
- dynamicAmaSlopePct[i] = i < amaReadyBar ? null : computeSlopeAtIndex(i, lb, currentAmaSource);
584
+ dynamicAmaSlopePct[i] = i < amaReadyBar ? null : computeSlopeAtIndex(i, lb, currentAmaSource);
642
585
  }
643
586
  for (let i = data.realBarCount; i < data.dates.length; i++) {
644
587
  dynamicAmaSlopePct[i] = null;
645
- dynamicAmaSlopePctRaw[i] = null;
646
588
  }
647
589
  }
648
590
 
@@ -650,7 +592,6 @@ function generateHTML(data, title = 'Dynamic Weight Research') {
650
592
  // Normalize each channel by the configured clamp so alpha remains a pure ratio knob.
651
593
  // Gain then scales the blended output linearly after the dead-band decision.
652
594
  currentOutputAxisMax = Math.max(0.5, OUTPUT_CLAMP);
653
- const channelNorm = Math.max(Math.abs(OUTPUT_CLAMP), 1e-9);
654
595
  const outputThreshold = currentMinOutputThreshold;
655
596
  const n = data.realBarCount;
656
597
 
@@ -658,11 +599,11 @@ function generateHTML(data, title = 'Dynamic Weight Research') {
658
599
  for (let i = 0; i < data.dates.length; i++) {
659
600
  if (i >= n) { currentMults[i] = null; continue; }
660
601
  const baseMult = getRegimeMultiplier(data.hurstArr[i], data.peArr[i]);
661
- // Use power for sensitivity: pushes away from 1.0 in both directions without flipping sign
662
- const rawMult = Math.pow(baseMult, currentRegimeSensitivity);
663
- // Dead-band: only apply regime multiplier when |mult - 1.0| >= absoluteThreshold
664
- // Clamp to 1.0 max: regime only dampens, never amplifies
665
- currentMults[i] = Math.abs(rawMult - 1.0) >= ABSOLUTE_THRESHOLD ? Math.min(rawMult, 1.0) : 1.0;
602
+ // Match the live regime gate exactly: apply the sensitivity
603
+ // exponent, clamp to 1.0 (dampen-only), round the per-bar series
604
+ // to 3 decimals, then apply the absolute-threshold dead-band.
605
+ const rawMult = roundToN(Math.min(Math.pow(baseMult, currentRegimeSensitivity), 1.0), 1000);
606
+ currentMults[i] = Math.abs(rawMult - 1.0) >= ABSOLUTE_THRESHOLD ? rawMult : 1.0;
666
607
  }
667
608
 
668
609
  // Per-bar offset pipeline — canonical implementation (computeDynamicWeightSeries
@@ -675,7 +616,7 @@ function generateHTML(data, title = 'Dynamic Weight Research') {
675
616
  regimeMultipliers: currentMults,
676
617
  lookbackBars: currentLookbackBars,
677
618
  amaErPeriod: data.amaErPeriod,
678
- amaClipThreshold: currentClipPct > 0 ? dynamicClipThreshold : currentAmaClipThreshold,
619
+ amaClipThreshold: dynamicClipThreshold,
679
620
  kalClipThreshold: currentKalClipThreshold,
680
621
  neutralZonePct: currentNz,
681
622
  amaMaxSlopePct: currentAmaMaxSlopePct,
@@ -752,7 +693,7 @@ function generateHTML(data, title = 'Dynamic Weight Research') {
752
693
  max: Number.isFinite(xs.max) ? xs.max : xMax,
753
694
  } : null;
754
695
 
755
- amaChart.setData([data.dates, dynamicAmaSlopePctRaw, dynamicAmaSlopePct], false);
696
+ amaChart.setData([data.dates, dynamicAmaSlopePct], false);
756
697
  kalmanChart.setData([data.dates, currentKalmanVelocityPct, data.kalmanDisplacementPct], false);
757
698
  outputChart.setData([data.dates, combinedOff, echoCombinedOff], false);
758
699
 
@@ -787,11 +728,6 @@ function generateHTML(data, title = 'Dynamic Weight Research') {
787
728
  if (sp == null) { spEl.textContent = '-'; spEl.style.color = '#8b949e'; }
788
729
  else { spEl.textContent = (sp >= 0 ? '+' : '') + (sp * 10).toFixed(3) + '‰'; spEl.style.color = sp > 0.01 ? '#2ea043' : sp < -0.01 ? '#f85149' : '#8b949e'; }
789
730
 
790
- const spRaw = dynamicAmaSlopePctRaw[idx];
791
- const spRawEl = document.getElementById('l-ama-slope-raw');
792
- if (spRaw == null) { spRawEl.textContent = '-'; spRawEl.style.color = '#8b949e'; }
793
- else { spRawEl.textContent = (spRaw >= 0 ? '+' : '') + (spRaw * 10).toFixed(3) + '‰'; spRawEl.style.color = '#8b949e'; }
794
-
795
731
  const vp = currentKalmanVelocityPct[idx];
796
732
  const vpEl = document.getElementById('l-kal-vel');
797
733
  if (vp == null) { vpEl.textContent = '-'; vpEl.style.color = '#8b949e'; }
@@ -1015,7 +951,6 @@ function generateHTML(data, title = 'Dynamic Weight Research') {
1015
951
  document.getElementById('clip-slider').value = currentClipPct;
1016
952
  document.getElementById('nz-slider').value = Math.round(currentNz * 100);
1017
953
  document.getElementById('lb-slider').value = lbValToSlider(currentLookbackBars);
1018
- document.getElementById('ema-slider').value = currentAmaEmaSpan;
1019
954
 
1020
955
  const priceEl = document.getElementById('price-panel');
1021
956
  const amaEl = document.getElementById('ama-panel');
@@ -1051,7 +986,6 @@ function generateHTML(data, title = 'Dynamic Weight Research') {
1051
986
  scales: { x: { time: true }, p: { auto: true } },
1052
987
  series: [
1053
988
  { label: 'Time' },
1054
- { label: 'Raw‰', stroke: '#8b949e', width: 1, dash: [3, 3], scale: 'p', points: { show: false } },
1055
989
  { label: 'Slope‰', stroke: '#f0a000', width: 2, scale: 'p', points: { show: false } },
1056
990
  ],
1057
991
  axes: [
@@ -1061,7 +995,7 @@ function generateHTML(data, title = 'Dynamic Weight Research') {
1061
995
  ],
1062
996
  cursor: cursorCfg,
1063
997
  hooks: { draw: [makePctFillHook(dynamicAmaSlopePct, 'p', 'rgba(46,160,67,0.20)', 'rgba(248,81,73,0.20)'), makeSignalBgHook('p')] }
1064
- }, [data.dates, dynamicAmaSlopePctRaw, dynamicAmaSlopePct], document.getElementById('ama-chart'));
998
+ }, [data.dates, dynamicAmaSlopePct], document.getElementById('ama-chart'));
1065
999
 
1066
1000
  kalmanChart = new uPlot({
1067
1001
  width: kalmanEl.offsetWidth, height: kalmanEl.offsetHeight,
@@ -1198,7 +1132,6 @@ function generateHTML(data, title = 'Dynamic Weight Research') {
1198
1132
  document.getElementById('clip-slider').addEventListener('input', (e) => {
1199
1133
  currentClipPct = parseInt(e.target.value, 10);
1200
1134
  if (currentClipPct === 0) {
1201
- currentAmaClipThreshold = data.amaPercentiles[data.amaPercentiles.length - 1];
1202
1135
  currentKalClipThreshold = Infinity;
1203
1136
  } else {
1204
1137
  // AMA clip threshold for clipPct>0 comes from the canonical
@@ -1223,12 +1156,6 @@ function generateHTML(data, title = 'Dynamic Weight Research') {
1223
1156
  onSliderChange();
1224
1157
  });
1225
1158
 
1226
- document.getElementById('ema-slider').addEventListener('input', (e) => {
1227
- currentAmaEmaSpan = parseInt(e.target.value, 10);
1228
- document.getElementById('ema-value').textContent = currentAmaEmaSpan;
1229
- onSliderChange();
1230
- });
1231
-
1232
1159
  document.getElementById('regime-slider').addEventListener('input', (e) => {
1233
1160
  currentRegimeSensitivity = parseInt(e.target.value, 10) / 100;
1234
1161
  document.getElementById('regime-value').textContent = currentRegimeSensitivity.toFixed(2);
@@ -1303,7 +1230,6 @@ function applyParams(p, btn) {
1303
1230
  document.getElementById('clip-slider').value = currentClipPct;
1304
1231
  document.getElementById('clip-value').textContent = currentClipPct + '%';
1305
1232
  if (currentClipPct === 0) {
1306
- currentAmaClipThreshold = data.amaPercentiles[data.amaPercentiles.length - 1];
1307
1233
  currentKalClipThreshold = Infinity;
1308
1234
  } else {
1309
1235
  recalcKalmanClipThreshold();
@@ -1324,11 +1250,6 @@ function applyParams(p, btn) {
1324
1250
  document.getElementById('lb-slider').value = lbValToSlider(currentLookbackBars);
1325
1251
  document.getElementById('lb-value').textContent = currentLookbackBars;
1326
1252
  }
1327
- if (p.amaEmaSpan != null) {
1328
- currentAmaEmaSpan = Math.max(SR.amaEmaSpan[0], Math.min(SR.amaEmaSpan[1], Math.round(p.amaEmaSpan)));
1329
- document.getElementById('ema-slider').value = currentAmaEmaSpan;
1330
- document.getElementById('ema-value').textContent = currentAmaEmaSpan;
1331
- }
1332
1253
  recalcInputs();
1333
1254
  recalcWeights();
1334
1255
  refreshChartsPreservingZoom();
@@ -1355,7 +1276,6 @@ function applyParams(p, btn) {
1355
1276
  regimeSensitivity: 'regime',
1356
1277
  dispWeight: 'dw',
1357
1278
  lookbackBars: 'lb',
1358
- amaEmaSpan: 'ema',
1359
1279
  };
1360
1280
  document.getElementById('paste-confirm-vals').innerHTML = Object.entries(labels)
1361
1281
  .filter(([k]) => p[k] != null)
@@ -1409,7 +1329,6 @@ function applyParams(p, btn) {
1409
1329
  regimeSensitivity: +currentRegimeSensitivity.toFixed(2),
1410
1330
  dispWeight: +currentDw.toFixed(2),
1411
1331
  lookbackBars: currentLookbackBars,
1412
- amaEmaSpan: currentAmaEmaSpan,
1413
1332
  };
1414
1333
  const json = JSON.stringify(params, null, 2);
1415
1334
  localStorage.setItem(LS_KEY, json);
@@ -0,0 +1,34 @@
1
+ export type HuberScaleMode = 'none' | 'df' | 'mscale';
2
+ /** One-bar diagnostic snapshot returned alongside the slope. */
3
+ export interface HuberDiagnostics {
4
+ slopePct: number;
5
+ scale: number;
6
+ outlierFraction: number;
7
+ }
8
+ /** Accumulated stats attached to an estimator built by {@link createHuberEstimator}. */
9
+ export interface HuberEstimatorStats {
10
+ calls: number;
11
+ outlierFractionSum: number;
12
+ scaleSum: number;
13
+ }
14
+ /** Estimator function shape accepted by simulateGridResetSeries (cfg.slopeEstimator). */
15
+ export type HuberEstimator = ((amaValues: any, index: number, lookbackBars: any) => number | null) & {
16
+ stats: HuberEstimatorStats;
17
+ };
18
+ /**
19
+ * delta_C = E[rho_C(Z)] for Z ~ N(0,1), the proposal-2 consistency constant:
20
+ * delta_C = 2*Phi(c) - 1 + 2*c*phi(c) - 2*c^2*(1 - Phi(c)).
21
+ */
22
+ export declare function huberConsistencyConstant(c: number): number;
23
+ /**
24
+ * Core fit. Reproduces `computeHuberWindowSlopePct` byte-for-byte for
25
+ * `mode='none'`; the other modes change only the scale estimate fed to the
26
+ * Huber weight `min(1, C*s/|r|)`.
27
+ */
28
+ export declare function huberSlopeCore(amaValues: any, index: number, lookbackBars: any, mode?: HuberScaleMode, hub?: any): HuberDiagnostics | null;
29
+ /**
30
+ * Build the `(series, index, lookbackBars)` estimator the reset replay expects,
31
+ * accumulating the mean outlier fraction and scale across calls in `.stats`.
32
+ */
33
+ export declare function createHuberEstimator(mode?: HuberScaleMode, hub?: any): HuberEstimator;
34
+ //# sourceMappingURL=huber_scale_variants.d.ts.map
@@ -0,0 +1,176 @@
1
+ 'use strict';
2
+ /**
3
+ * RESEARCH-ONLY scale variants for the canonical Huber AMA-slope estimator.
4
+ *
5
+ * `computeHuberWindowSlopePct` (market_adapter/core/strategies/dynamic_weight_series.ts)
6
+ * estimates the robust scale as a PLUG-IN `1.4826 * MAD` of the residuals of the
7
+ * current fit, recomputed each IRLS pass. Those residuals are shrunk relative to
8
+ * the true errors (n - 2 degrees of freedom), so the plug-in scale is biased low
9
+ * — measured ~0.93x sigma at a 16-bar window, ~0.86x at 8 bars — which lowers the
10
+ * effective Huber constant below the nominal 1.345 and makes short windows more
11
+ * conservative than intended.
12
+ *
13
+ * scikit-learn's `HuberRegressor` avoids this by optimizing sigma JOINTLY with the
14
+ * coefficients (sklearn/linear_model/_huber.py); its reference is Huber &
15
+ * Ronchetti, "Concomitant scale estimates", p. 172. This module reproduces the
16
+ * baseline exactly and offers two corrected scale estimates so the effect can be
17
+ * measured without touching production:
18
+ *
19
+ * 'none' — exact production behaviour (plug-in 1.4826 * MAD).
20
+ * 'df' — plug-in MAD inflated by the finite-sample factor sqrt(n / (n - 2)).
21
+ * 'mscale' — Huber proposal-2 M-scale: solve mean(rho_C(r_i / s)) = delta_C,
22
+ * where delta_C = E[rho_C(Z)] under N(0, 1), iterated with the fit.
23
+ *
24
+ * Also returns an outlier fraction (share of |residual| > C * s), the sklearn
25
+ * `outliers_` analogue, for observability.
26
+ *
27
+ * Not imported by production code and not embedded in any chart — a research
28
+ * harness for the scale-bias hypothesis only.
29
+ */
30
+ import { MARKET_ADAPTER } from '../../modules/constants.js';
31
+ // Abramowitz & Stegun 7.1.26 approximation — max abs error ~1.5e-7, ample for a
32
+ // consistency constant that only needs ~1e-6 relative accuracy.
33
+ function erf(x) {
34
+ const sign = x < 0 ? -1 : 1;
35
+ const ax = Math.abs(x);
36
+ const t = 1 / (1 + 0.3275911 * ax);
37
+ const poly = ((((1.061405429 * t - 1.453152027) * t + 1.421413741) * t - 0.284496736) * t + 0.254829592) * t;
38
+ return sign * (1 - poly * Math.exp(-ax * ax));
39
+ }
40
+ function standardNormalCdf(x) {
41
+ return 0.5 * (1 + erf(x / Math.SQRT2));
42
+ }
43
+ function standardNormalPdf(x) {
44
+ return Math.exp(-0.5 * x * x) / Math.sqrt(2 * Math.PI);
45
+ }
46
+ /** Huber rho: z^2 inside the band, linear beyond. */
47
+ function huberRho(z, c) {
48
+ const a = Math.abs(z);
49
+ return a <= c ? z * z : 2 * c * a - c * c;
50
+ }
51
+ /**
52
+ * delta_C = E[rho_C(Z)] for Z ~ N(0,1), the proposal-2 consistency constant:
53
+ * delta_C = 2*Phi(c) - 1 + 2*c*phi(c) - 2*c^2*(1 - Phi(c)).
54
+ */
55
+ export function huberConsistencyConstant(c) {
56
+ const Phi = standardNormalCdf(c);
57
+ const phi = standardNormalPdf(c);
58
+ return 2 * Phi - 1 + 2 * c * phi - 2 * c * c * (1 - Phi);
59
+ }
60
+ /**
61
+ * Proposal-2 M-scale: the s satisfying mean(rho_C(r_i / s)) = delta_C.
62
+ * Fixed-point iteration s <- s * sqrt(mean(rho_C(r / s)) / delta_C), seeded from
63
+ * the plug-in MAD so it starts near the answer.
64
+ */
65
+ function solveMScale(resid, c, seed, floor) {
66
+ const delta = huberConsistencyConstant(c);
67
+ let s = Math.max(seed, floor);
68
+ for (let it = 0; it < 60; it++) {
69
+ let acc = 0;
70
+ for (let i = 0; i < resid.length; i++)
71
+ acc += huberRho(resid[i] / s, c);
72
+ const ratio = acc / (resid.length * delta);
73
+ const next = s * Math.sqrt(Math.max(ratio, 1e-12));
74
+ if (!Number.isFinite(next))
75
+ return s;
76
+ if (Math.abs(next - s) <= 1e-13 * s)
77
+ return next;
78
+ s = next;
79
+ }
80
+ return s;
81
+ }
82
+ /**
83
+ * Core fit. Reproduces `computeHuberWindowSlopePct` byte-for-byte for
84
+ * `mode='none'`; the other modes change only the scale estimate fed to the
85
+ * Huber weight `min(1, C*s/|r|)`.
86
+ */
87
+ export function huberSlopeCore(amaValues, index, lookbackBars, mode = 'none', hub = MARKET_ADAPTER.DYNAMIC_WEIGHT_AMA_HUBER) {
88
+ const bars = Number.isFinite(lookbackBars) && Number(lookbackBars) > 0
89
+ ? Math.ceil(Number(lookbackBars))
90
+ : 0;
91
+ if (!Array.isArray(amaValues) || bars < 1)
92
+ return null;
93
+ if (!Number.isFinite(index) || index < bars || index >= amaValues.length)
94
+ return null;
95
+ const y = [];
96
+ for (let k = index - bars; k <= index; k++) {
97
+ const v = Number(amaValues[k]);
98
+ if (!Number.isFinite(v) || v <= 0)
99
+ return null;
100
+ y.push(Math.log(v));
101
+ }
102
+ const n = y.length;
103
+ const c = Number.isFinite(hub?.C) ? hub.C : 1.345;
104
+ const iterations = Number.isFinite(hub?.ITERATIONS) ? hub.ITERATIONS : 5;
105
+ const scaleFloor = Number.isFinite(hub?.SCALE_FLOOR) ? hub.SCALE_FLOOR : 1e-6;
106
+ const zeroEpsilon = Number.isFinite(hub?.ZERO_EPSILON) ? hub.ZERO_EPSILON : 1e-9;
107
+ const xMean = (n - 1) / 2;
108
+ const wls = (w) => {
109
+ let sw = 0, swx = 0, swy = 0, swxx = 0, swxy = 0;
110
+ for (let i = 0; i < n; i++) {
111
+ const xi = i - xMean;
112
+ sw += w[i];
113
+ swx += w[i] * xi;
114
+ swy += w[i] * y[i];
115
+ swxx += w[i] * xi * xi;
116
+ swxy += w[i] * xi * y[i];
117
+ }
118
+ const den = sw * swxx - swx * swx;
119
+ const b = den === 0 ? 0 : (sw * swxy - swx * swy) / den;
120
+ const a = sw === 0 ? 0 : (swy - b * swx) / sw;
121
+ return { a, b };
122
+ };
123
+ let fit = wls(new Array(n).fill(1));
124
+ let scale = scaleFloor;
125
+ for (let iter = 0; iter < iterations; iter++) {
126
+ const resid = y.map((v, i) => v - (fit.a + fit.b * (i - xMean)));
127
+ const abs = resid.map(Math.abs).sort((p, q) => p - q);
128
+ const mid = abs.length >> 1;
129
+ const mad = abs.length % 2 === 1 ? abs[mid] : (abs[mid - 1] + abs[mid]) / 2;
130
+ let s = 1.4826 * mad;
131
+ if (mode === 'df')
132
+ s = s * Math.sqrt(n / Math.max(1, n - 2));
133
+ else if (mode === 'mscale')
134
+ s = solveMScale(resid, c, s, scaleFloor);
135
+ s = Math.max(s, scaleFloor);
136
+ scale = s;
137
+ const w = resid.map((r) => Math.min(1, (c * s) / Math.max(Math.abs(r), 1e-12)));
138
+ const next = wls(w);
139
+ const moved = Math.abs(next.b - fit.b);
140
+ fit = next;
141
+ if (moved < 1e-12)
142
+ break;
143
+ }
144
+ // Outlier fraction at the final fit (sklearn outliers_ analogue).
145
+ let outliers = 0;
146
+ for (let i = 0; i < n; i++) {
147
+ const r = y[i] - (fit.a + fit.b * (i - xMean));
148
+ if (Math.abs(r) > c * scale)
149
+ outliers++;
150
+ }
151
+ let slope = fit.b * 100;
152
+ if (Number.isFinite(slope) && Math.abs(slope) < zeroEpsilon)
153
+ slope = 0;
154
+ if (!Number.isFinite(slope))
155
+ return null;
156
+ return { slopePct: slope, scale, outlierFraction: outliers / n };
157
+ }
158
+ /**
159
+ * Build the `(series, index, lookbackBars)` estimator the reset replay expects,
160
+ * accumulating the mean outlier fraction and scale across calls in `.stats`.
161
+ */
162
+ export function createHuberEstimator(mode = 'none', hub = MARKET_ADAPTER.DYNAMIC_WEIGHT_AMA_HUBER) {
163
+ const stats = { calls: 0, outlierFractionSum: 0, scaleSum: 0 };
164
+ const fn = ((amaValues, index, lookbackBars) => {
165
+ const d = huberSlopeCore(amaValues, index, lookbackBars, mode, hub);
166
+ if (d == null)
167
+ return null;
168
+ stats.calls++;
169
+ stats.outlierFractionSum += d.outlierFraction;
170
+ stats.scaleSum += d.scale;
171
+ return d.slopePct;
172
+ });
173
+ fn.stats = stats;
174
+ return fn;
175
+ }
176
+ //# sourceMappingURL=huber_scale_variants.js.map