dexbot 1.6.10 → 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.
- package/CHANGELOG.md +16 -0
- package/README.md +1 -0
- package/analysis/README.md +49 -11
- package/analysis/bot_fitting/README.md +12 -0
- package/analysis/tradingview/README.md +2 -2
- package/analysis/trend_detection/DYNAMIC_WEIGHT_RESEARCH.md +10 -36
- package/analysis/trend_detection/README.md +31 -0
- package/claw/package.json +1 -1
- package/claw/runtimes/openclaw-plugin/openclaw.plugin.json +1 -1
- package/claw/runtimes/openclaw-plugin/package.json +1 -1
- package/dist/analysis/account_resolver.js +13 -1
- package/dist/analysis/analyze_dynamic_weight.js +0 -3
- package/dist/analysis/bot_fitting/backtest_ama_sweep.js +51 -7
- package/dist/analysis/bot_fitting/backtest_bot_fitting.js +65 -7
- package/dist/analysis/bot_fitting/backtest_lookback_drawdown.d.ts +21 -0
- package/dist/analysis/bot_fitting/backtest_lookback_drawdown.js +315 -0
- package/dist/analysis/bot_key_utils.js +3 -13
- package/dist/analysis/fills_cache.d.ts +64 -0
- package/dist/analysis/fills_cache.js +254 -0
- package/dist/analysis/fills_source.js +5 -2
- package/dist/analysis/pnl_report.d.ts +39 -0
- package/dist/analysis/pnl_report.js +325 -0
- package/dist/analysis/resolve_source.d.ts +0 -1
- package/dist/analysis/trade_profitability.d.ts +11 -2
- package/dist/analysis/trade_profitability.js +187 -61
- package/dist/analysis/tradingview/analyze_tradingview.js +3 -5
- package/dist/analysis/tradingview/grid_reset_config.d.ts +2 -0
- package/dist/analysis/tradingview/grid_reset_config.js +18 -1
- package/dist/analysis/tradingview/grid_reset_sim.d.ts +1 -0
- package/dist/analysis/tradingview/grid_reset_sim.js +38 -2
- package/dist/analysis/tradingview/tradingview_uplot_chart_generator.js +2 -1
- package/dist/analysis/trend_detection/backtest_ama_slope_huber.d.ts +102 -0
- package/dist/analysis/trend_detection/backtest_ama_slope_huber.js +725 -0
- package/dist/analysis/trend_detection/dynamic_weight_chart_generator.js +22 -108
- package/dist/analysis/trend_detection/huber_scale_variants.d.ts +34 -0
- package/dist/analysis/trend_detection/huber_scale_variants.js +176 -0
- package/dist/dexbot.js +6 -3
- package/dist/market_adapter/core/market_adapter_service.d.ts +15 -0
- package/dist/market_adapter/core/market_adapter_service.js +64 -5
- package/dist/market_adapter/core/strategies/ama.d.ts +1 -1
- package/dist/market_adapter/core/strategies/ama.js +5 -28
- package/dist/market_adapter/core/strategies/dynamic_weight_series.d.ts +2 -2
- package/dist/market_adapter/core/strategies/dynamic_weight_series.js +2 -2
- package/dist/market_adapter/inputs/fetch_cex_synthetic_data.js +1 -2
- package/dist/market_adapter/log_format.js +1 -2
- package/dist/market_adapter/market_adapter.d.ts +0 -1
- package/dist/market_adapter/market_adapter.js +2 -27
- package/dist/modules/constants.d.ts +3 -1
- package/dist/modules/constants.js +39 -15
- package/dist/modules/dexbot_maintenance_runtime.js +12 -0
- package/dist/modules/order/accounting.js +25 -0
- package/dist/modules/order/format.d.ts +35 -15
- package/dist/modules/order/format.js +62 -16
- package/dist/modules/order/manager.d.ts +1 -0
- package/dist/modules/order/manager.js +22 -1
- package/dist/modules/order/sync_engine.js +15 -1
- package/dist/modules/order/utils/order.d.ts +21 -1
- package/dist/modules/order/utils/order.js +80 -2
- package/dist/modules/paths.d.ts +2 -0
- package/dist/modules/paths.js +2 -0
- package/dist/modules/utils/time_range.d.ts +15 -0
- package/dist/modules/utils/time_range.js +18 -0
- package/dist/scripts/analyze-orders.js +1 -44
- package/dist/scripts/chart_command.js +3 -4
- package/dist/scripts/pnl.d.ts +3 -0
- package/dist/scripts/pnl.js +40 -0
- package/dist/unlock.js +34 -0
- package/docs/DEXBOT_COMPARISON.md +3 -3
- package/docs/EVOLUTION.md +10 -9
- package/docs/FUND_MOVEMENT_AND_ACCOUNTING.md +1 -1
- package/docs/GRID_RECALCULATION.md +12 -15
- package/docs/README.md +2 -2
- package/docs/WORKFLOW.md +1 -0
- package/market_adapter/README.md +4 -26
- package/package.json +1 -1
- 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,
|
|
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,6 @@ 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,
|
|
14
13
|
computeHuberWindowSlopePct,
|
|
15
14
|
computeAmaSlopeClipThreshold,
|
|
16
15
|
bilinearInterpolate,
|
|
@@ -33,7 +32,6 @@ function generateHTML(data, title = 'Dynamic Weight Research') {
|
|
|
33
32
|
const AMA_MS_MIN = 0.06, AMA_MS_MAX = 0.12;
|
|
34
33
|
const KAL_MS_MIN = 0.5, KAL_MS_MAX = 1.5;
|
|
35
34
|
const CLIP_PCT_MAX = 20;
|
|
36
|
-
const EMA_MIN = 0, EMA_MAX = 32;
|
|
37
35
|
const TH_MIN = 0, TH_MAX = 0.5;
|
|
38
36
|
const KF_MIN = 0, KF_MAX = 200;
|
|
39
37
|
const KFD_MIN = 1.0, KFD_MAX = 3.0;
|
|
@@ -47,7 +45,6 @@ function generateHTML(data, title = 'Dynamic Weight Research') {
|
|
|
47
45
|
dispWeight: [0, 1],
|
|
48
46
|
neutralZonePct: [0, 1],
|
|
49
47
|
lookbackBars: [LB_MIN, LB_MAX],
|
|
50
|
-
amaEmaSpan: [EMA_MIN, EMA_MAX],
|
|
51
48
|
amaMaxSlopePct: [AMA_MS_MIN, AMA_MS_MAX],
|
|
52
49
|
kalmanMaxSlopePct: [KAL_MS_MIN, KAL_MS_MAX],
|
|
53
50
|
clipPct: [0, CLIP_PCT_MAX],
|
|
@@ -107,10 +104,6 @@ function generateHTML(data, title = 'Dynamic Weight Research') {
|
|
|
107
104
|
const defaultKalmanDispThresholdMult = data.kalmanDispThresholdMult ?? MARKET_ADAPTER.DYNAMIC_WEIGHT_KALMAN_DISP_THRESHOLD_MULT_DEFAULT;
|
|
108
105
|
const defaultKalmanSmoothSpanPct = data.kalmanSmoothSpanPct ?? MARKET_ADAPTER.DYNAMIC_WEIGHT_KALMAN_SMOOTH_SPAN_PCT_DEFAULT;
|
|
109
106
|
const defaultSignalConfirmBars = data.signalConfirmBars ?? MARKET_ADAPTER.DYNAMIC_WEIGHT_SIGNAL_CONFIRM_BARS_DEFAULT;
|
|
110
|
-
// Research-only `ema` knob: EMA span in bars over the AMA input before the
|
|
111
|
-
// slope is taken. 0 (default) = off, keeps the raw AMA input.
|
|
112
|
-
const defaultAmaEmaSpanRaw = data.amaEmaSpan ?? ma.amaEmaSpan ?? 0;
|
|
113
|
-
const defaultAmaEmaSpan = Math.round(Math.min(EMA_MAX, Math.max(EMA_MIN, Number.isFinite(defaultAmaEmaSpanRaw) ? defaultAmaEmaSpanRaw : EMA_MIN)));
|
|
114
107
|
const regimeInitSlider = Math.round(defaultRegimeSensitivity * 100);
|
|
115
108
|
const interval = results.length > 1 ?
|
|
116
109
|
(new Date(results[1].timestamp).getTime() - new Date(results[0].timestamp).getTime()) / 1000 : 3600;
|
|
@@ -137,8 +130,7 @@ function generateHTML(data, title = 'Dynamic Weight Research') {
|
|
|
137
130
|
const amaErPeriod = data.amaConfig?.erPeriod ?? MARKET_ADAPTER.AMAS[defaultAmaKey].erPeriod;
|
|
138
131
|
const amaSlowPeriod = data.amaConfig?.slowPeriod ?? MARKET_ADAPTER.AMAS[defaultAmaKey].slowPeriod;
|
|
139
132
|
const amaFastPeriod = data.amaConfig?.fastPeriod ?? MARKET_ADAPTER.AMAS[defaultAmaKey].fastPeriod;
|
|
140
|
-
const
|
|
141
|
-
const amaWarmupBars = getAmaWarmupBars(amaErPeriod, amaSlowPeriod, lookbackBars, amaFastPeriod, amaErSmoothPeriod);
|
|
133
|
+
const amaWarmupBars = getAmaWarmupBars(amaErPeriod, amaSlowPeriod, lookbackBars, amaFastPeriod);
|
|
142
134
|
const amaSlopeReadyBars = Math.ceil(amaErPeriod) + lookbackBars;
|
|
143
135
|
const amaSeedSmaLine = new Array(results.length).fill(null);
|
|
144
136
|
const amaSeedWindowEnd = Math.min(results.length - 1, Math.ceil(amaErPeriod));
|
|
@@ -176,16 +168,6 @@ function generateHTML(data, title = 'Dynamic Weight Research') {
|
|
|
176
168
|
amaSeedSmaLine.push(null);
|
|
177
169
|
}
|
|
178
170
|
const realBarCount = results.length;
|
|
179
|
-
function maxAbsPct(arr) {
|
|
180
|
-
let m = 0;
|
|
181
|
-
for (let i = 0; i < realBarCount; i++) {
|
|
182
|
-
if (arr[i] != null && Math.abs(arr[i]) > m)
|
|
183
|
-
m = Math.abs(arr[i]);
|
|
184
|
-
}
|
|
185
|
-
return m || 4;
|
|
186
|
-
}
|
|
187
|
-
const amaPctMax = Math.ceil(maxAbsPct(amaSlopePct) * 1.15) || 5;
|
|
188
|
-
const kalPctMax = Math.ceil(Math.max(maxAbsPct(kalmanVelocityPct), maxAbsPct(kalmanDisplacementPct)) * 1.15) || 5;
|
|
189
171
|
function buildPercentiles(arr, startIndex = 0) {
|
|
190
172
|
const safeStartIndex = Math.max(0, Math.min(realBarCount, Math.ceil(startIndex)));
|
|
191
173
|
const sorted = [];
|
|
@@ -208,7 +190,6 @@ function generateHTML(data, title = 'Dynamic Weight Research') {
|
|
|
208
190
|
}
|
|
209
191
|
const amaPercentiles = buildPercentiles(amaSlopePct, amaSlopeReadyBars);
|
|
210
192
|
const kalPercentiles = buildPercentiles(kalmanVelocityPct);
|
|
211
|
-
const maxDispPct = Math.ceil(maxAbsPct(kalmanDisplacementPct) * 1.15) || 5;
|
|
212
193
|
return `<!DOCTYPE html>
|
|
213
194
|
<html lang="en">
|
|
214
195
|
<head>
|
|
@@ -225,7 +206,7 @@ function generateHTML(data, title = 'Dynamic Weight Research') {
|
|
|
225
206
|
.legend-item { gap: 3px; }
|
|
226
207
|
.legend-val { font-family: monospace; display: inline-block; text-align: right; min-width: 45px; }
|
|
227
208
|
#l-price, #l-ama3 { min-width: 62px; }
|
|
228
|
-
#l-ama-slope, #l-
|
|
209
|
+
#l-ama-slope, #l-kal-vel, #l-kal-disp { min-width: 54px; }
|
|
229
210
|
#l-signal, #l-signal-latched { min-width: 70px; text-align: left; }
|
|
230
211
|
#l-combined-raw, #l-combined-echo { min-width: 42px; }
|
|
231
212
|
#l-mult { min-width: 38px; }
|
|
@@ -270,9 +251,6 @@ function generateHTML(data, title = 'Dynamic Weight Research') {
|
|
|
270
251
|
.ctrl.lb label { min-width: 20px; }
|
|
271
252
|
.ctrl.lb input[type="range"] { accent-color: #39d0d8; width: 80px; }
|
|
272
253
|
.ctrl.lb .val { color: #39d0d8; }
|
|
273
|
-
.ctrl.ema label { min-width: 20px; }
|
|
274
|
-
.ctrl.ema input[type="range"] { accent-color: #f0a000; width: 80px; }
|
|
275
|
-
.ctrl.ema .val { color: #f0a000; }
|
|
276
254
|
.ctrl.off input[type="range"] { accent-color: #3fb950; }
|
|
277
255
|
.ctrl.off .val { color: #3fb950; }
|
|
278
256
|
.ctrl.nz input[type="range"] { accent-color: #8b949e; }
|
|
@@ -318,7 +296,6 @@ function generateHTML(data, title = 'Dynamic Weight Research') {
|
|
|
318
296
|
<div class="section-label">AMA SLOPE INPUT</div>
|
|
319
297
|
<div class="legend">
|
|
320
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>
|
|
321
|
-
<div class="legend-item"><div class="dot" style="background:#8b949e;"></div>Raw‰: <span id="l-ama-slope-raw" class="legend-val">-</span></div>
|
|
322
299
|
</div>
|
|
323
300
|
<div id="ama-chart"></div>
|
|
324
301
|
</div>
|
|
@@ -349,7 +326,6 @@ function generateHTML(data, title = 'Dynamic Weight Research') {
|
|
|
349
326
|
<div class="group-sep"></div>
|
|
350
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>
|
|
351
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>
|
|
352
|
-
<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>
|
|
353
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>
|
|
354
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>
|
|
355
331
|
|
|
@@ -383,7 +359,7 @@ function generateHTML(data, title = 'Dynamic Weight Research') {
|
|
|
383
359
|
</div>
|
|
384
360
|
</div>
|
|
385
361
|
|
|
386
|
-
<script id="payload" type="application/json">${serializeJsonForScript({ dates, prices, hurstArr, peArr, hurstSegments, peSegments, ama3Prices, amaSeedSmaLine,
|
|
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>
|
|
387
363
|
|
|
388
364
|
<script>
|
|
389
365
|
const data = JSON.parse(document.getElementById('payload').textContent);
|
|
@@ -429,8 +405,7 @@ function generateHTML(data, title = 'Dynamic Weight Research') {
|
|
|
429
405
|
const kalMsSliderToVal = (pos) => Math.exp(KAL_MS_LOG_MIN + (pos / 1000) * (KAL_MS_LOG_MAX - KAL_MS_LOG_MIN));
|
|
430
406
|
|
|
431
407
|
let currentLookbackBars = data.lookbackBars ?? ${JSON.stringify(lookbackBars)};
|
|
432
|
-
|
|
433
|
-
let currentAmaSource = data.ama3Prices;
|
|
408
|
+
const currentAmaSource = data.ama3Prices;
|
|
434
409
|
const LB_LOG_MIN = data.lbLogMin;
|
|
435
410
|
const LB_LOG_MAX = data.lbLogMax;
|
|
436
411
|
const lbSliderToVal = (pos) => Math.round(Math.exp(LB_LOG_MIN + (pos / 1000) * (LB_LOG_MAX - LB_LOG_MIN)));
|
|
@@ -442,11 +417,10 @@ function generateHTML(data, title = 'Dynamic Weight Research') {
|
|
|
442
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);
|
|
443
418
|
|
|
444
419
|
let currentClipPct = data.clipPct ?? ${JSON.stringify(defaultClipPct)};
|
|
445
|
-
//
|
|
446
|
-
//
|
|
447
|
-
//
|
|
448
|
-
|
|
449
|
-
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.
|
|
450
424
|
let currentKalClipThreshold = currentClipPct === 0 ? Infinity : data.kalPercentiles[100 - currentClipPct];
|
|
451
425
|
|
|
452
426
|
// Regime table and axis nodes from payload — sourced from MARKET_ADAPTER in constants.ts
|
|
@@ -460,7 +434,10 @@ function generateHTML(data, title = 'Dynamic Weight Research') {
|
|
|
460
434
|
*/
|
|
461
435
|
function getRegimeMultiplier(H, PE) {
|
|
462
436
|
if (H == null || PE == null) return 1.0;
|
|
463
|
-
|
|
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 });
|
|
464
441
|
}
|
|
465
442
|
|
|
466
443
|
let currentRegimeSensitivity = data.regimeSensitivity ?? ma.regimeSensitivity;
|
|
@@ -469,7 +446,6 @@ function generateHTML(data, title = 'Dynamic Weight Research') {
|
|
|
469
446
|
const currentLatchedSignals = new Array(data.dates.length).fill(null);
|
|
470
447
|
const dynamicAmaOff = new Array(data.dates.length).fill(null);
|
|
471
448
|
const dynamicAmaSlopePct = new Array(data.dates.length).fill(null);
|
|
472
|
-
const dynamicAmaSlopePctRaw = new Array(data.dates.length).fill(null);
|
|
473
449
|
const dynamicKalOff = new Array(data.dates.length).fill(null);
|
|
474
450
|
const combinedOff = new Array(data.dates.length).fill(null);
|
|
475
451
|
const combinedSell = new Array(data.dates.length).fill(null);
|
|
@@ -584,37 +560,6 @@ function generateHTML(data, title = 'Dynamic Weight Research') {
|
|
|
584
560
|
}
|
|
585
561
|
}
|
|
586
562
|
|
|
587
|
-
/**
|
|
588
|
-
* Research-only ema knob — EMA low-pass over the AMA input before the
|
|
589
|
-
* slope is taken (EMA-then-difference == difference-then-EMA, both are
|
|
590
|
-
* linear filters). span bars, alpha = 2/(span+1): noise std shrinks ~
|
|
591
|
-
* 1/sqrt(span), lag grows ~ (span-1)/2 bars. Seeded with an SMA over the
|
|
592
|
-
* first 'span' finite values (mirrors the AMA seed SMA) so the transient
|
|
593
|
-
* is gone before any slope bar can go ready. Nulls (warmup / trailing
|
|
594
|
-
* padding) stay null so no fabricated values reach the clip-percentile
|
|
595
|
-
* pool or the offset pipeline. span <= 0 returns the input untouched.
|
|
596
|
-
*/
|
|
597
|
-
function buildEmaSeries(values, span) {
|
|
598
|
-
if (!(span > 0) || !Array.isArray(values)) return values;
|
|
599
|
-
const n = values.length;
|
|
600
|
-
const out = new Array(n);
|
|
601
|
-
const alpha = 2 / (span + 1);
|
|
602
|
-
let seedSum = 0, seedCount = 0;
|
|
603
|
-
for (let i = 0; i < n && seedCount < span; i++) {
|
|
604
|
-
const v = values[i];
|
|
605
|
-
if (v == null || !Number.isFinite(v)) continue;
|
|
606
|
-
seedSum += v; seedCount++;
|
|
607
|
-
}
|
|
608
|
-
let prev = seedCount > 0 ? seedSum / seedCount : null;
|
|
609
|
-
for (let i = 0; i < n; i++) {
|
|
610
|
-
const v = values[i];
|
|
611
|
-
if (v == null || !Number.isFinite(v)) { out[i] = null; continue; }
|
|
612
|
-
prev = prev == null ? v : alpha * v + (1 - alpha) * prev;
|
|
613
|
-
out[i] = prev;
|
|
614
|
-
}
|
|
615
|
-
return out;
|
|
616
|
-
}
|
|
617
|
-
|
|
618
563
|
function computeSlopeAtIndex(idx, lb, values) {
|
|
619
564
|
// Canonical AMA slope % (computeHuberWindowSlopePct injected above).
|
|
620
565
|
const sp = computeHuberWindowSlopePct(values, idx, lb);
|
|
@@ -625,7 +570,6 @@ function generateHTML(data, title = 'Dynamic Weight Research') {
|
|
|
625
570
|
recalcKalmanVelocity();
|
|
626
571
|
recalcKalmanClipThreshold();
|
|
627
572
|
recalcLatchedSignals();
|
|
628
|
-
currentAmaSource = buildEmaSeries(data.ama3Prices, currentAmaEmaSpan);
|
|
629
573
|
const lb = currentLookbackBars;
|
|
630
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)});
|
|
631
575
|
const amaReadyBar = Math.max(lb, amaErWarmup + lb);
|
|
@@ -634,20 +578,13 @@ function generateHTML(data, title = 'Dynamic Weight Research') {
|
|
|
634
578
|
// implementation (computeAmaSlopeClipThreshold injected above),
|
|
635
579
|
// shared with the live market adapter service. Trailing padded
|
|
636
580
|
// nulls beyond realBarCount are skipped by its finiteness guards.
|
|
637
|
-
// Clip pool follows the (possibly EMA-filtered) AMA input so the
|
|
638
|
-
// percentile threshold matches the series the offsets derive from.
|
|
639
581
|
dynamicClipThreshold = computeAmaSlopeClipThreshold(currentAmaSource, amaErWarmup, lb, currentClipPct);
|
|
640
582
|
|
|
641
583
|
for (let i = 0; i < data.realBarCount; i++) {
|
|
642
|
-
|
|
643
|
-
// recalcWeights): the raw reference line from the unfiltered AMA
|
|
644
|
-
// input, the plotted series from the EMA-filtered input.
|
|
645
|
-
dynamicAmaSlopePctRaw[i] = i < amaReadyBar ? null : computeSlopeAtIndex(i, lb, data.ama3Prices);
|
|
646
|
-
dynamicAmaSlopePct[i] = i < amaReadyBar ? null : computeSlopeAtIndex(i, lb, currentAmaSource);
|
|
584
|
+
dynamicAmaSlopePct[i] = i < amaReadyBar ? null : computeSlopeAtIndex(i, lb, currentAmaSource);
|
|
647
585
|
}
|
|
648
586
|
for (let i = data.realBarCount; i < data.dates.length; i++) {
|
|
649
587
|
dynamicAmaSlopePct[i] = null;
|
|
650
|
-
dynamicAmaSlopePctRaw[i] = null;
|
|
651
588
|
}
|
|
652
589
|
}
|
|
653
590
|
|
|
@@ -655,7 +592,6 @@ function generateHTML(data, title = 'Dynamic Weight Research') {
|
|
|
655
592
|
// Normalize each channel by the configured clamp so alpha remains a pure ratio knob.
|
|
656
593
|
// Gain then scales the blended output linearly after the dead-band decision.
|
|
657
594
|
currentOutputAxisMax = Math.max(0.5, OUTPUT_CLAMP);
|
|
658
|
-
const channelNorm = Math.max(Math.abs(OUTPUT_CLAMP), 1e-9);
|
|
659
595
|
const outputThreshold = currentMinOutputThreshold;
|
|
660
596
|
const n = data.realBarCount;
|
|
661
597
|
|
|
@@ -663,11 +599,11 @@ function generateHTML(data, title = 'Dynamic Weight Research') {
|
|
|
663
599
|
for (let i = 0; i < data.dates.length; i++) {
|
|
664
600
|
if (i >= n) { currentMults[i] = null; continue; }
|
|
665
601
|
const baseMult = getRegimeMultiplier(data.hurstArr[i], data.peArr[i]);
|
|
666
|
-
//
|
|
667
|
-
|
|
668
|
-
//
|
|
669
|
-
|
|
670
|
-
currentMults[i] = Math.abs(rawMult - 1.0) >= ABSOLUTE_THRESHOLD ?
|
|
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;
|
|
671
607
|
}
|
|
672
608
|
|
|
673
609
|
// Per-bar offset pipeline — canonical implementation (computeDynamicWeightSeries
|
|
@@ -680,7 +616,7 @@ function generateHTML(data, title = 'Dynamic Weight Research') {
|
|
|
680
616
|
regimeMultipliers: currentMults,
|
|
681
617
|
lookbackBars: currentLookbackBars,
|
|
682
618
|
amaErPeriod: data.amaErPeriod,
|
|
683
|
-
amaClipThreshold:
|
|
619
|
+
amaClipThreshold: dynamicClipThreshold,
|
|
684
620
|
kalClipThreshold: currentKalClipThreshold,
|
|
685
621
|
neutralZonePct: currentNz,
|
|
686
622
|
amaMaxSlopePct: currentAmaMaxSlopePct,
|
|
@@ -757,7 +693,7 @@ function generateHTML(data, title = 'Dynamic Weight Research') {
|
|
|
757
693
|
max: Number.isFinite(xs.max) ? xs.max : xMax,
|
|
758
694
|
} : null;
|
|
759
695
|
|
|
760
|
-
amaChart.setData([data.dates,
|
|
696
|
+
amaChart.setData([data.dates, dynamicAmaSlopePct], false);
|
|
761
697
|
kalmanChart.setData([data.dates, currentKalmanVelocityPct, data.kalmanDisplacementPct], false);
|
|
762
698
|
outputChart.setData([data.dates, combinedOff, echoCombinedOff], false);
|
|
763
699
|
|
|
@@ -792,11 +728,6 @@ function generateHTML(data, title = 'Dynamic Weight Research') {
|
|
|
792
728
|
if (sp == null) { spEl.textContent = '-'; spEl.style.color = '#8b949e'; }
|
|
793
729
|
else { spEl.textContent = (sp >= 0 ? '+' : '') + (sp * 10).toFixed(3) + '‰'; spEl.style.color = sp > 0.01 ? '#2ea043' : sp < -0.01 ? '#f85149' : '#8b949e'; }
|
|
794
730
|
|
|
795
|
-
const spRaw = dynamicAmaSlopePctRaw[idx];
|
|
796
|
-
const spRawEl = document.getElementById('l-ama-slope-raw');
|
|
797
|
-
if (spRaw == null) { spRawEl.textContent = '-'; spRawEl.style.color = '#8b949e'; }
|
|
798
|
-
else { spRawEl.textContent = (spRaw >= 0 ? '+' : '') + (spRaw * 10).toFixed(3) + '‰'; spRawEl.style.color = '#8b949e'; }
|
|
799
|
-
|
|
800
731
|
const vp = currentKalmanVelocityPct[idx];
|
|
801
732
|
const vpEl = document.getElementById('l-kal-vel');
|
|
802
733
|
if (vp == null) { vpEl.textContent = '-'; vpEl.style.color = '#8b949e'; }
|
|
@@ -1020,7 +951,6 @@ function generateHTML(data, title = 'Dynamic Weight Research') {
|
|
|
1020
951
|
document.getElementById('clip-slider').value = currentClipPct;
|
|
1021
952
|
document.getElementById('nz-slider').value = Math.round(currentNz * 100);
|
|
1022
953
|
document.getElementById('lb-slider').value = lbValToSlider(currentLookbackBars);
|
|
1023
|
-
document.getElementById('ema-slider').value = currentAmaEmaSpan;
|
|
1024
954
|
|
|
1025
955
|
const priceEl = document.getElementById('price-panel');
|
|
1026
956
|
const amaEl = document.getElementById('ama-panel');
|
|
@@ -1056,7 +986,6 @@ function generateHTML(data, title = 'Dynamic Weight Research') {
|
|
|
1056
986
|
scales: { x: { time: true }, p: { auto: true } },
|
|
1057
987
|
series: [
|
|
1058
988
|
{ label: 'Time' },
|
|
1059
|
-
{ label: 'Raw‰', stroke: '#8b949e', width: 1, dash: [3, 3], scale: 'p', points: { show: false } },
|
|
1060
989
|
{ label: 'Slope‰', stroke: '#f0a000', width: 2, scale: 'p', points: { show: false } },
|
|
1061
990
|
],
|
|
1062
991
|
axes: [
|
|
@@ -1066,7 +995,7 @@ function generateHTML(data, title = 'Dynamic Weight Research') {
|
|
|
1066
995
|
],
|
|
1067
996
|
cursor: cursorCfg,
|
|
1068
997
|
hooks: { draw: [makePctFillHook(dynamicAmaSlopePct, 'p', 'rgba(46,160,67,0.20)', 'rgba(248,81,73,0.20)'), makeSignalBgHook('p')] }
|
|
1069
|
-
}, [data.dates,
|
|
998
|
+
}, [data.dates, dynamicAmaSlopePct], document.getElementById('ama-chart'));
|
|
1070
999
|
|
|
1071
1000
|
kalmanChart = new uPlot({
|
|
1072
1001
|
width: kalmanEl.offsetWidth, height: kalmanEl.offsetHeight,
|
|
@@ -1203,7 +1132,6 @@ function generateHTML(data, title = 'Dynamic Weight Research') {
|
|
|
1203
1132
|
document.getElementById('clip-slider').addEventListener('input', (e) => {
|
|
1204
1133
|
currentClipPct = parseInt(e.target.value, 10);
|
|
1205
1134
|
if (currentClipPct === 0) {
|
|
1206
|
-
currentAmaClipThreshold = data.amaPercentiles[data.amaPercentiles.length - 1];
|
|
1207
1135
|
currentKalClipThreshold = Infinity;
|
|
1208
1136
|
} else {
|
|
1209
1137
|
// AMA clip threshold for clipPct>0 comes from the canonical
|
|
@@ -1228,12 +1156,6 @@ function generateHTML(data, title = 'Dynamic Weight Research') {
|
|
|
1228
1156
|
onSliderChange();
|
|
1229
1157
|
});
|
|
1230
1158
|
|
|
1231
|
-
document.getElementById('ema-slider').addEventListener('input', (e) => {
|
|
1232
|
-
currentAmaEmaSpan = parseInt(e.target.value, 10);
|
|
1233
|
-
document.getElementById('ema-value').textContent = currentAmaEmaSpan;
|
|
1234
|
-
onSliderChange();
|
|
1235
|
-
});
|
|
1236
|
-
|
|
1237
1159
|
document.getElementById('regime-slider').addEventListener('input', (e) => {
|
|
1238
1160
|
currentRegimeSensitivity = parseInt(e.target.value, 10) / 100;
|
|
1239
1161
|
document.getElementById('regime-value').textContent = currentRegimeSensitivity.toFixed(2);
|
|
@@ -1308,7 +1230,6 @@ function applyParams(p, btn) {
|
|
|
1308
1230
|
document.getElementById('clip-slider').value = currentClipPct;
|
|
1309
1231
|
document.getElementById('clip-value').textContent = currentClipPct + '%';
|
|
1310
1232
|
if (currentClipPct === 0) {
|
|
1311
|
-
currentAmaClipThreshold = data.amaPercentiles[data.amaPercentiles.length - 1];
|
|
1312
1233
|
currentKalClipThreshold = Infinity;
|
|
1313
1234
|
} else {
|
|
1314
1235
|
recalcKalmanClipThreshold();
|
|
@@ -1329,11 +1250,6 @@ function applyParams(p, btn) {
|
|
|
1329
1250
|
document.getElementById('lb-slider').value = lbValToSlider(currentLookbackBars);
|
|
1330
1251
|
document.getElementById('lb-value').textContent = currentLookbackBars;
|
|
1331
1252
|
}
|
|
1332
|
-
if (p.amaEmaSpan != null) {
|
|
1333
|
-
currentAmaEmaSpan = Math.max(SR.amaEmaSpan[0], Math.min(SR.amaEmaSpan[1], Math.round(p.amaEmaSpan)));
|
|
1334
|
-
document.getElementById('ema-slider').value = currentAmaEmaSpan;
|
|
1335
|
-
document.getElementById('ema-value').textContent = currentAmaEmaSpan;
|
|
1336
|
-
}
|
|
1337
1253
|
recalcInputs();
|
|
1338
1254
|
recalcWeights();
|
|
1339
1255
|
refreshChartsPreservingZoom();
|
|
@@ -1360,7 +1276,6 @@ function applyParams(p, btn) {
|
|
|
1360
1276
|
regimeSensitivity: 'regime',
|
|
1361
1277
|
dispWeight: 'dw',
|
|
1362
1278
|
lookbackBars: 'lb',
|
|
1363
|
-
amaEmaSpan: 'ema',
|
|
1364
1279
|
};
|
|
1365
1280
|
document.getElementById('paste-confirm-vals').innerHTML = Object.entries(labels)
|
|
1366
1281
|
.filter(([k]) => p[k] != null)
|
|
@@ -1414,7 +1329,6 @@ function applyParams(p, btn) {
|
|
|
1414
1329
|
regimeSensitivity: +currentRegimeSensitivity.toFixed(2),
|
|
1415
1330
|
dispWeight: +currentDw.toFixed(2),
|
|
1416
1331
|
lookbackBars: currentLookbackBars,
|
|
1417
|
-
amaEmaSpan: currentAmaEmaSpan,
|
|
1418
1332
|
};
|
|
1419
1333
|
const json = JSON.stringify(params, null, 2);
|
|
1420
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
|
package/dist/dexbot.js
CHANGED
|
@@ -143,7 +143,7 @@ if (typeof credentialPolicy.checkPolicyFileSecurity === 'function')
|
|
|
143
143
|
// Primary CLI driver that manages tracked bots and helper utilities such as key/bot editors.
|
|
144
144
|
const PROFILES_BOTS_FILE = PATHS.PROFILES.BOTS_JSON;
|
|
145
145
|
const PROFILES_DIR = PATHS.PROFILES_DIR;
|
|
146
|
-
const CLI_COMMANDS = ['start', 'test', 'reset', 'default', 'disable', 'enable', 'drystart', 'key', 'bot', 'pm2', 'update', 'export', 'order', 'credit', 'tv', 'dw', 'clear', 'clear-orders', 'clear-market-adapter', 'clear-all', 'status', 'unlock', 'delete', 'stop', 'restart', 'reload', 'help'];
|
|
146
|
+
const CLI_COMMANDS = ['start', 'test', 'reset', 'default', 'disable', 'enable', 'drystart', 'key', 'bot', 'pm2', 'update', 'export', 'order', 'credit', 'tv', 'dw', 'pnl', 'clear', 'clear-orders', 'clear-market-adapter', 'clear-all', 'status', 'unlock', 'delete', 'stop', 'restart', 'reload', 'help'];
|
|
147
147
|
const COMMAND_ALIASES = { orders: 'order', keys: 'key', bots: 'bot', stat: 'status', stats: 'status', start: 'unlock', defaults: 'default', stp: 'stop', stopall: 'stop', restartall: 'restart', reloadall: 'reload' };
|
|
148
148
|
const CLI_HELP_FLAGS = ['-h', '--help'];
|
|
149
149
|
const CLI_EXAMPLES_FLAG = '--cli-examples';
|
|
@@ -162,6 +162,7 @@ const CLI_EXAMPLES = [
|
|
|
162
162
|
{ title: 'Analyze persisted order grids', command: 'dexbot order', notes: 'Runs the order analyzer across the orders directory (<profiles>/orders) and prints spread/increment/funds/distribution metrics. Add a bot key to render only that bot, and --export for an HTML report.' },
|
|
163
163
|
{ title: 'Show live credit/MPA positions', command: 'dexbot credit', notes: 'Queries get_margin_positions + get_credit_deals_by_borrower per preferredAccount and prints debt/collateral sums plus one Curr. CR line per whitelisted pair (active CR, else borrow-now CR vs funds avail. on the offer) and one Avar. CR line per bot. CR covers only pairs whitelisted in bots.json and listed on the current credit offer. Add a bot key to render only that bot.' },
|
|
164
164
|
{ title: 'TradingView chart for a bot, pool, or pair', command: 'dexbot tv <bot|pool-id|AssetA/AssetB> --month 3', notes: 'Fetches 1h candles for N months (default 3, pool-first with orderbook fallback; --feed charts MPA price-feed history) and writes an auto-named HTML chart.' },
|
|
165
|
+
{ title: 'PnL report for a bot or blockchain account', command: 'dexbot pnl <bot|account|1.2.x> --month 3 [--pair BASE/QUOTE]', notes: 'Resolves a local bot profile first, then the chain account, analyzes its fills for the requested window and writes a self-contained HTML PnL report.' },
|
|
165
166
|
{ title: 'Clear all bot log files', command: 'dexbot clear', notes: 'Runs scripts/clear-logs.sh to remove *.log, rotated *.log.N and *.jsonl* from the logs directory (<profiles>/logs), including the credential audit trail daemon-audit.jsonl and its rotated siblings (named in the preview). Offline only: the scripts warn when a live runtime is detected, but a running bot keeps writing to unlinked files and the space is not freed until it restarts; dexbot clear-orders / clear-market-adapter / clear-all are undone within seconds (grid state is re-persisted, the adapter rewrites its state file and lock). Stop first with dexbot stop / dexbot pm2 stop all.' },
|
|
166
167
|
{ title: 'Reset settings to defaults', command: 'dexbot default', notes: 'Runs scripts/reset-settings.sh to delete general.settings.json, market_profiles.json, and market_adapter_settings.json.' }
|
|
167
168
|
];
|
|
@@ -220,6 +221,7 @@ function printCLIUsage() {
|
|
|
220
221
|
['credit [<bot>]', 'Live summed MPA + borrowed-credit positions per asset per bot.'],
|
|
221
222
|
['tv <target>', 'TradingView chart: 1h candles for <bot|pool-id|AssetA/AssetB> over --month N (default 3).'],
|
|
222
223
|
['dw <target>', 'Dynamic-weight research chart: same targets/flags as tv (see analysis/).'],
|
|
224
|
+
['pnl <account>', 'PnL HTML report for a bot/account over --month N, optional --pair BASE/QUOTE filter.'],
|
|
223
225
|
]],
|
|
224
226
|
['Files', [
|
|
225
227
|
['clear', 'Delete <profiles>/logs/*.log, *.log.N and *.jsonl* (audit trail included). Stop the runtime first.'],
|
|
@@ -259,7 +261,7 @@ if (cliArgs.some(arg => CLI_HELP_FLAGS.includes(arg))) {
|
|
|
259
261
|
// so the script prints its usage. Only scripts with offline help handling
|
|
260
262
|
// belong here — forwarding to a script without it could misinterpret the
|
|
261
263
|
// flag as input (e.g. a bot-name filter triggering live work).
|
|
262
|
-
const HELP_OWNING_COMMANDS = new Set(['credit', 'tv', 'dw']);
|
|
264
|
+
const HELP_OWNING_COMMANDS = new Set(['credit', 'tv', 'dw', 'pnl']);
|
|
263
265
|
const requestedCommand = COMMAND_ALIASES[cliArgs[0]] ?? cliArgs[0];
|
|
264
266
|
if (!HELP_OWNING_COMMANDS.has(requestedCommand)) {
|
|
265
267
|
printCLIUsage();
|
|
@@ -1008,7 +1010,8 @@ async function handleCLICommands() {
|
|
|
1008
1010
|
return true;
|
|
1009
1011
|
}
|
|
1010
1012
|
case 'tv':
|
|
1011
|
-
case 'dw':
|
|
1013
|
+
case 'dw':
|
|
1014
|
+
case 'pnl': {
|
|
1012
1015
|
const { spawnSync } = require('child_process');
|
|
1013
1016
|
const scriptArgs = buildRuntimeScriptArgs({
|
|
1014
1017
|
codeRoot: __dirname,
|