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
|
@@ -0,0 +1,725 @@
|
|
|
1
|
+
'use strict';
|
|
2
|
+
/**
|
|
3
|
+
* AMA-SLOPE-HUBER LOOKBACK BACKTEST
|
|
4
|
+
*
|
|
5
|
+
* Sweeps the Huber slope lookback window (MARKET_ADAPTER.DYNAMIC_WEIGHT_AMA_LOOKBACK_BARS,
|
|
6
|
+
* exposed as `lb` in the dynamic-weight research chart) from a low bound to a
|
|
7
|
+
* high bound and reports the metrics that actually differ between windows:
|
|
8
|
+
*
|
|
9
|
+
* LAG — how late the causal slope signal confirms a regime change,
|
|
10
|
+
* measured two ways:
|
|
11
|
+
* priceLag cross-correlation peak vs a centred slope of close
|
|
12
|
+
* (total pipeline lag: AMA smoothing + slope window)
|
|
13
|
+
* amaLag cross-correlation peak vs a centred slope of AMA
|
|
14
|
+
* (slope-window group delay only)
|
|
15
|
+
* revLag median bars from a sign flip in the centred AMA
|
|
16
|
+
* slope until the causal slope confirms the new sign
|
|
17
|
+
* RESETS — the market adapter's two grid-recentering triggers (drift ratchet
|
|
18
|
+
* + slope-delta, whitelist-gated), replayed bar-by-bar through the
|
|
19
|
+
* canonical `simulateGridResetSeries`: count, reason split, rate,
|
|
20
|
+
* gap distribution and whipsaw (back-to-back) resets
|
|
21
|
+
* NOISE — slope standard deviation, bar-to-bar wobble (mean |Δslope|),
|
|
22
|
+
* second-difference energy, zero-crossing rate, saturation and
|
|
23
|
+
* neutral-zone occupancy, average absolute range tilt
|
|
24
|
+
*
|
|
25
|
+
* The reset replay uses the UNCLIPPED slope (clip only feeds the range tilt, it
|
|
26
|
+
* never moves reset timing — see grid_reset_sim.ts), so `clipPercentile` is
|
|
27
|
+
* passed as 0 for speed and the tilt metric is derived from the batch clip
|
|
28
|
+
* threshold instead. Everything else is the production decision path.
|
|
29
|
+
*
|
|
30
|
+
* Data may be a single LP candle JSON or a directory of month shards
|
|
31
|
+
* (market_adapter/data/lp/<pair>/) — shards are concatenated and de-duplicated
|
|
32
|
+
* by timestamp, so overlapping chunk files are harmless.
|
|
33
|
+
*
|
|
34
|
+
* Usage:
|
|
35
|
+
* node dist/analysis/trend_detection/backtest_ama_slope_huber.js \
|
|
36
|
+
* --data market_adapter/data/lp/<market-pair> [--lookback 8:28:2]
|
|
37
|
+
*/
|
|
38
|
+
import fs from 'node:fs';
|
|
39
|
+
import path from 'node:path';
|
|
40
|
+
import { pathToFileURL } from 'node:url';
|
|
41
|
+
import { calculateAMA, getAmaWarmupBars } from '../../market_adapter/core/strategies/ama.js';
|
|
42
|
+
import { computeAmaSlopeClipThreshold } from '../../market_adapter/core/strategies/dynamic_weight_series.js';
|
|
43
|
+
import { createHuberEstimator } from './huber_scale_variants.js';
|
|
44
|
+
import { simulateGridResetSeries, GRID_RESET_BOOTSTRAP } from '../tradingview/grid_reset_sim.js';
|
|
45
|
+
import { normalizeCandle, range } from '../math_utils.js';
|
|
46
|
+
import { parseListOrRange } from '../bot_fitting/shared_utils.js';
|
|
47
|
+
import { getStorage } from '../../modules/storage/index.js';
|
|
48
|
+
import { PATHS } from '../../modules/paths.js';
|
|
49
|
+
import { MARKET_ADAPTER } from '../../modules/constants.js';
|
|
50
|
+
const { readJSON, writeJSON } = getStorage();
|
|
51
|
+
const MA = MARKET_ADAPTER;
|
|
52
|
+
// ─── CLI ─────────────────────────────────────────────────────────────────────
|
|
53
|
+
/**
|
|
54
|
+
* Parse a lookback spec. Accepts the shared `a:b:s` / comma syntax but also
|
|
55
|
+
* tolerates a DESCENDING range like `28:8:2` (which parseListOrRange rejects),
|
|
56
|
+
* so both "8h..28h" and "28h..8h" phrasings work.
|
|
57
|
+
*/
|
|
58
|
+
function parseLookbacks(spec, fallback) {
|
|
59
|
+
const m = spec.match(/^(\d+):(\d+):([\d.]+)$/);
|
|
60
|
+
if (m) {
|
|
61
|
+
const a = Number(m[1]);
|
|
62
|
+
const b = Number(m[2]);
|
|
63
|
+
const step = Number(m[3]);
|
|
64
|
+
if (Number.isFinite(a) && Number.isFinite(b) && Number.isFinite(step) && step > 0 && a > b) {
|
|
65
|
+
spec = `${b}:${a}:${step}`;
|
|
66
|
+
}
|
|
67
|
+
}
|
|
68
|
+
return parseListOrRange(spec, fallback).map((v) => Math.round(v));
|
|
69
|
+
}
|
|
70
|
+
function parseArgs() {
|
|
71
|
+
const args = process.argv.slice(2);
|
|
72
|
+
const out = {
|
|
73
|
+
dataPath: '',
|
|
74
|
+
amaName: MA.DEFAULT_AMA_KEY,
|
|
75
|
+
er: null,
|
|
76
|
+
fast: null,
|
|
77
|
+
slow: null,
|
|
78
|
+
lookbacks: [...range(8, 28, 2, 0)].map((v) => Math.round(v)).reverse(),
|
|
79
|
+
priceThresholdPct: MA.AMA_DELTA_THRESHOLD_PERCENT,
|
|
80
|
+
slopeThresholdFactor: MA.AMA_SLOPE_DELTA_THRESHOLD_PERCENT,
|
|
81
|
+
slopeEnabled: true,
|
|
82
|
+
slopePersistBars: MA.AMA_SLOPE_PERSIST_BARS,
|
|
83
|
+
confirmFraction: 0.25,
|
|
84
|
+
whipsawBars: 3,
|
|
85
|
+
scaleMode: 'none',
|
|
86
|
+
truthWindowBars: null,
|
|
87
|
+
forwardWindowBars: null,
|
|
88
|
+
outPath: null,
|
|
89
|
+
};
|
|
90
|
+
for (let i = 0; i < args.length; i++) {
|
|
91
|
+
const arg = args[i];
|
|
92
|
+
if (arg === '--help' || arg === '-h') {
|
|
93
|
+
printHelp();
|
|
94
|
+
process.exit(0);
|
|
95
|
+
}
|
|
96
|
+
if (arg === '--no-slope') {
|
|
97
|
+
out.slopeEnabled = false;
|
|
98
|
+
continue;
|
|
99
|
+
}
|
|
100
|
+
const val = args[i + 1];
|
|
101
|
+
if (!val)
|
|
102
|
+
continue;
|
|
103
|
+
switch (arg) {
|
|
104
|
+
case '--data':
|
|
105
|
+
out.dataPath = val;
|
|
106
|
+
i++;
|
|
107
|
+
break;
|
|
108
|
+
case '--ama':
|
|
109
|
+
out.amaName = val;
|
|
110
|
+
i++;
|
|
111
|
+
break;
|
|
112
|
+
case '--er':
|
|
113
|
+
out.er = Number(val);
|
|
114
|
+
i++;
|
|
115
|
+
break;
|
|
116
|
+
case '--fast':
|
|
117
|
+
out.fast = Number(val);
|
|
118
|
+
i++;
|
|
119
|
+
break;
|
|
120
|
+
case '--slow':
|
|
121
|
+
out.slow = Number(val);
|
|
122
|
+
i++;
|
|
123
|
+
break;
|
|
124
|
+
case '--lookback':
|
|
125
|
+
out.lookbacks = parseLookbacks(val, out.lookbacks);
|
|
126
|
+
i++;
|
|
127
|
+
break;
|
|
128
|
+
case '--price-threshold':
|
|
129
|
+
out.priceThresholdPct = Number(val);
|
|
130
|
+
i++;
|
|
131
|
+
break;
|
|
132
|
+
case '--slope-threshold-factor':
|
|
133
|
+
out.slopeThresholdFactor = Number(val);
|
|
134
|
+
i++;
|
|
135
|
+
break;
|
|
136
|
+
case '--slope-persist':
|
|
137
|
+
out.slopePersistBars = Math.max(1, Math.round(Number(val)));
|
|
138
|
+
i++;
|
|
139
|
+
break;
|
|
140
|
+
case '--confirm':
|
|
141
|
+
out.confirmFraction = Number(val);
|
|
142
|
+
i++;
|
|
143
|
+
break;
|
|
144
|
+
case '--scale-mode':
|
|
145
|
+
if (val !== 'none' && val !== 'df' && val !== 'mscale')
|
|
146
|
+
throw new Error(`--scale-mode must be none|df|mscale (got '${val}')`);
|
|
147
|
+
out.scaleMode = val;
|
|
148
|
+
i++;
|
|
149
|
+
break;
|
|
150
|
+
case '--whipsaw':
|
|
151
|
+
out.whipsawBars = Number(val);
|
|
152
|
+
i++;
|
|
153
|
+
break;
|
|
154
|
+
case '--truth-window':
|
|
155
|
+
out.truthWindowBars = Number(val);
|
|
156
|
+
i++;
|
|
157
|
+
break;
|
|
158
|
+
case '--forward-window':
|
|
159
|
+
out.forwardWindowBars = Number(val);
|
|
160
|
+
i++;
|
|
161
|
+
break;
|
|
162
|
+
case '--out':
|
|
163
|
+
out.outPath = path.resolve(val);
|
|
164
|
+
i++;
|
|
165
|
+
break;
|
|
166
|
+
}
|
|
167
|
+
}
|
|
168
|
+
if (!out.dataPath)
|
|
169
|
+
throw new Error('--data <path-to-lp-candles.json|dir> is required');
|
|
170
|
+
if (!Array.isArray(out.lookbacks) || out.lookbacks.length === 0 || out.lookbacks.some((v) => !Number.isFinite(v) || v < 2)) {
|
|
171
|
+
throw new Error('--lookback must resolve to a non-empty list of bars >= 2');
|
|
172
|
+
}
|
|
173
|
+
// De-duplicate and present high -> low so the table reads 28h..8h.
|
|
174
|
+
out.lookbacks = [...new Set(out.lookbacks)].sort((a, b) => b - a);
|
|
175
|
+
return out;
|
|
176
|
+
}
|
|
177
|
+
function printHelp() {
|
|
178
|
+
console.log('AMA-Slope-Huber lookback backtest');
|
|
179
|
+
console.log('');
|
|
180
|
+
console.log('Usage: node dist/analysis/trend_detection/backtest_ama_slope_huber.js [options]');
|
|
181
|
+
console.log('');
|
|
182
|
+
console.log('Options:');
|
|
183
|
+
console.log(' --data <path> LP candle file or shard directory (required)');
|
|
184
|
+
console.log(` --ama <AMA1..AMA4> Built-in AMA preset (default: ${MA.DEFAULT_AMA_KEY})`);
|
|
185
|
+
console.log(' --er/--fast/--slow <n> Override AMA periods (override --ama)');
|
|
186
|
+
console.log(' --lookback <spec> Lookback sweep in bars (default: 28h,26h,...,8h; also accepts 28:8:2 or 8:28:2)');
|
|
187
|
+
console.log(` --price-threshold <pct> Drift reset threshold (default: ${MA.AMA_DELTA_THRESHOLD_PERCENT})`);
|
|
188
|
+
console.log(` --slope-threshold-factor <n> % of max slope for the slope reset (default: ${MA.AMA_SLOPE_DELTA_THRESHOLD_PERCENT})`);
|
|
189
|
+
console.log(` --slope-persist <bars> Bars the slope delta must persist before resetting (default: ${MA.AMA_SLOPE_PERSIST_BARS})`);
|
|
190
|
+
console.log(' --no-slope Disable the slope-delta reset (drift only)');
|
|
191
|
+
console.log(' --confirm <frac> Slope confirmation size as a fraction of max slope (default: 0.25)');
|
|
192
|
+
console.log(' --scale-mode <mode> Huber scale estimate: none (production) | df | mscale (default: none)');
|
|
193
|
+
console.log(' --whipsaw <bars> Back-to-back reset gap counted as a whipsaw (default: 3)');
|
|
194
|
+
console.log(' --truth-window <bars> Centred reference half-window (default: max lookback)');
|
|
195
|
+
console.log(' --forward-window <bars> Realized forward horizon for range tilt direction (default: lookback)');
|
|
196
|
+
console.log(' --out <path> JSON output path');
|
|
197
|
+
}
|
|
198
|
+
function resolveAma(cfg) {
|
|
199
|
+
if (cfg.er != null || cfg.fast != null || cfg.slow != null) {
|
|
200
|
+
const er = cfg.er ?? 781;
|
|
201
|
+
const fast = cfg.fast ?? 5.2;
|
|
202
|
+
const slow = cfg.slow ?? 83.6;
|
|
203
|
+
return { name: `custom(er=${er},f=${fast},s=${slow})`, er, fast, slow };
|
|
204
|
+
}
|
|
205
|
+
const presets = MA.AMAS;
|
|
206
|
+
const preset = presets[cfg.amaName];
|
|
207
|
+
if (!preset)
|
|
208
|
+
throw new Error(`Unknown AMA preset '${cfg.amaName}' (expected ${Object.keys(presets).join(', ')})`);
|
|
209
|
+
return { name: cfg.amaName, er: preset.erPeriod, fast: preset.fastPeriod, slow: preset.slowPeriod };
|
|
210
|
+
}
|
|
211
|
+
// ─── Data loading ────────────────────────────────────────────────────────────
|
|
212
|
+
function loadCandles(input) {
|
|
213
|
+
const resolved = path.resolve(input);
|
|
214
|
+
if (!fs.existsSync(resolved))
|
|
215
|
+
throw new Error(`Data path not found: ${resolved}`);
|
|
216
|
+
const stat = fs.statSync(resolved);
|
|
217
|
+
const files = stat.isDirectory()
|
|
218
|
+
? fs.readdirSync(resolved)
|
|
219
|
+
.filter((name) => /\.json$/i.test(name) && !/manifest/i.test(name))
|
|
220
|
+
.map((name) => path.join(resolved, name))
|
|
221
|
+
.sort()
|
|
222
|
+
: [resolved];
|
|
223
|
+
const byTime = new Map();
|
|
224
|
+
let meta = null;
|
|
225
|
+
for (const file of files) {
|
|
226
|
+
let raw;
|
|
227
|
+
try {
|
|
228
|
+
raw = readJSON(file);
|
|
229
|
+
}
|
|
230
|
+
catch {
|
|
231
|
+
continue;
|
|
232
|
+
}
|
|
233
|
+
const arr = Array.isArray(raw?.candles) ? raw.candles : (Array.isArray(raw) ? raw : null);
|
|
234
|
+
if (!arr || arr.length === 0)
|
|
235
|
+
continue;
|
|
236
|
+
if (!meta && raw?.meta)
|
|
237
|
+
meta = raw.meta;
|
|
238
|
+
for (const c of arr) {
|
|
239
|
+
const n = normalizeCandle(c);
|
|
240
|
+
if (n)
|
|
241
|
+
byTime.set(n.time, { time: n.time, open: n.open, high: n.high, low: n.low, close: n.close, volume: n.volume });
|
|
242
|
+
}
|
|
243
|
+
}
|
|
244
|
+
const candles = [...byTime.values()].sort((a, b) => a.time - b.time);
|
|
245
|
+
if (candles.length === 0)
|
|
246
|
+
throw new Error(`No candles found under ${resolved}`);
|
|
247
|
+
return { candles, meta, files: files.length };
|
|
248
|
+
}
|
|
249
|
+
// ─── Small stats helpers ─────────────────────────────────────────────────────
|
|
250
|
+
function median(values) {
|
|
251
|
+
if (values.length === 0)
|
|
252
|
+
return null;
|
|
253
|
+
const s = values.slice().sort((a, b) => a - b);
|
|
254
|
+
const mid = s.length >> 1;
|
|
255
|
+
return s.length % 2 ? s[mid] : (s[mid - 1] + s[mid]) / 2;
|
|
256
|
+
}
|
|
257
|
+
function percentile(values, pct) {
|
|
258
|
+
if (values.length === 0)
|
|
259
|
+
return null;
|
|
260
|
+
const s = values.slice().sort((a, b) => a - b);
|
|
261
|
+
const idx = Math.min(s.length - 1, Math.max(0, Math.round((pct / 100) * (s.length - 1))));
|
|
262
|
+
return s[idx];
|
|
263
|
+
}
|
|
264
|
+
function fmt(x, d = 2) {
|
|
265
|
+
return Number.isFinite(Number(x)) ? Number(x).toFixed(d) : 'n/a';
|
|
266
|
+
}
|
|
267
|
+
// ─── Lag estimators ──────────────────────────────────────────────────────────
|
|
268
|
+
/**
|
|
269
|
+
* Cross-correlation peak lag between the causal signal and a reference.
|
|
270
|
+
* Returns the smallest non-negative k maximising corr(sig[t], ref[t-k]).
|
|
271
|
+
* A positive lag means `sig` trails `ref` by k bars (the smoother's group delay).
|
|
272
|
+
*/
|
|
273
|
+
function crossCorrelationLag(sig, ref, maxLag) {
|
|
274
|
+
let bestLag = 0;
|
|
275
|
+
let bestCorr = -Infinity;
|
|
276
|
+
for (let k = 0; k <= maxLag; k++) {
|
|
277
|
+
let n = 0, sx = 0, sy = 0, sxy = 0, sxx = 0, syy = 0;
|
|
278
|
+
for (let t = k; t < sig.length; t++) {
|
|
279
|
+
const x = sig[t];
|
|
280
|
+
const y = ref[t - k];
|
|
281
|
+
if (x == null || y == null || !Number.isFinite(x) || !Number.isFinite(y))
|
|
282
|
+
continue;
|
|
283
|
+
n++;
|
|
284
|
+
sx += x;
|
|
285
|
+
sy += y;
|
|
286
|
+
sxy += x * y;
|
|
287
|
+
sxx += x * x;
|
|
288
|
+
syy += y * y;
|
|
289
|
+
}
|
|
290
|
+
if (n < 100)
|
|
291
|
+
continue;
|
|
292
|
+
const mx = sx / n, my = sy / n;
|
|
293
|
+
const vx = sxx / n - mx * mx;
|
|
294
|
+
const vy = syy / n - my * my;
|
|
295
|
+
const cov = sxy / n - mx * my;
|
|
296
|
+
const corr = vx > 0 && vy > 0 ? cov / Math.sqrt(vx * vy) : -Infinity;
|
|
297
|
+
if (corr > bestCorr) {
|
|
298
|
+
bestCorr = corr;
|
|
299
|
+
bestLag = k;
|
|
300
|
+
}
|
|
301
|
+
}
|
|
302
|
+
return { lagBars: bestLag, corr: Number.isFinite(bestCorr) ? bestCorr : null };
|
|
303
|
+
}
|
|
304
|
+
/**
|
|
305
|
+
* Median bars between a sign flip in the centred reference slope and the first
|
|
306
|
+
* bar the causal slope confirms the new direction at or above `confirmPct`.
|
|
307
|
+
* `misses` counts flips the causal slope never confirmed inside the window.
|
|
308
|
+
*/
|
|
309
|
+
function reversalLag(sig, ref, maxLag, confirmPct) {
|
|
310
|
+
const lags = [];
|
|
311
|
+
let flips = 0;
|
|
312
|
+
let misses = 0;
|
|
313
|
+
let prevSign = 0;
|
|
314
|
+
for (let t = 1; t < ref.length; t++) {
|
|
315
|
+
const v = ref[t];
|
|
316
|
+
if (v == null || !Number.isFinite(v))
|
|
317
|
+
continue;
|
|
318
|
+
const s = Math.sign(v);
|
|
319
|
+
if (s !== 0 && prevSign !== 0 && s !== prevSign) {
|
|
320
|
+
flips++;
|
|
321
|
+
const end = Math.min(t + maxLag, sig.length - 1);
|
|
322
|
+
let found = -1;
|
|
323
|
+
for (let u = t + 1; u <= end; u++) {
|
|
324
|
+
const x = sig[u];
|
|
325
|
+
if (x != null && Number.isFinite(x) && Math.sign(x) === s && Math.abs(x) >= confirmPct) {
|
|
326
|
+
found = u - t;
|
|
327
|
+
break;
|
|
328
|
+
}
|
|
329
|
+
}
|
|
330
|
+
if (found >= 0)
|
|
331
|
+
lags.push(found);
|
|
332
|
+
else
|
|
333
|
+
misses++;
|
|
334
|
+
}
|
|
335
|
+
prevSign = s;
|
|
336
|
+
}
|
|
337
|
+
return { lagBars: median(lags), flips, misses, samples: lags.length };
|
|
338
|
+
}
|
|
339
|
+
// ─── Per-lookback computation ────────────────────────────────────────────────
|
|
340
|
+
function analyzeLookback(closes, amaValues, lookbackBars, amaDef, cfg, truthArr, priceTruthArr, truthHalf, estimator = createHuberEstimator('none')) {
|
|
341
|
+
const n = closes.length;
|
|
342
|
+
const warmupBars = getAmaWarmupBars(amaDef.er, amaDef.slow, 0, amaDef.fast);
|
|
343
|
+
const maxSlopePct = MA.DYNAMIC_WEIGHT_AMA_MAX_SLOPE_PCT;
|
|
344
|
+
const neutralZonePct = MA.DYNAMIC_WEIGHT_AMA_NEUTRAL_ZONE_PCT;
|
|
345
|
+
const maxSlopeOffset = MA.DYNAMIC_WEIGHT_ASYMMETRIC_OFFSET_CLAMP;
|
|
346
|
+
const slopeDeltaThresholdPct = (cfg.slopeThresholdFactor / 100) * maxSlopePct;
|
|
347
|
+
// Canonical production reset decision (clip-independent for timing).
|
|
348
|
+
const sim = simulateGridResetSeries(amaValues, {
|
|
349
|
+
priceDeltaThresholdPercent: cfg.priceThresholdPct,
|
|
350
|
+
slopeDeltaThresholdPercent: slopeDeltaThresholdPct,
|
|
351
|
+
slopeEnabled: cfg.slopeEnabled,
|
|
352
|
+
erPeriod: amaDef.er,
|
|
353
|
+
lookbackBars,
|
|
354
|
+
warmupBars,
|
|
355
|
+
maxSlopePct,
|
|
356
|
+
neutralZonePct,
|
|
357
|
+
maxSlopeOffset,
|
|
358
|
+
clipPercentile: 0,
|
|
359
|
+
slopePersistBars: cfg.slopePersistBars,
|
|
360
|
+
slopeEstimator: estimator,
|
|
361
|
+
});
|
|
362
|
+
const slopeSeries = sim.slopePct;
|
|
363
|
+
const estStats = estimator.stats;
|
|
364
|
+
const meanOutlierFraction = estStats.calls > 0 ? estStats.outlierFractionSum / estStats.calls : null;
|
|
365
|
+
const meanHuberScale = estStats.calls > 0 ? estStats.scaleSum / estStats.calls : null;
|
|
366
|
+
const liveBars = Math.max(1, n - warmupBars);
|
|
367
|
+
// ── Noise / signal-quality metrics ──────────────────────────────────────
|
|
368
|
+
let finite = 0, sumSigned = 0, sumAbs = 0, sumSq = 0;
|
|
369
|
+
let prev = null;
|
|
370
|
+
let deltaCount = 0, sumAbsDelta = 0;
|
|
371
|
+
let prevDelta = null;
|
|
372
|
+
let secondCount = 0, secondSq = 0;
|
|
373
|
+
let zeroCross = 0, lastSign = 0;
|
|
374
|
+
let saturated = 0, neutral = 0;
|
|
375
|
+
for (let i = 0; i < n; i++) {
|
|
376
|
+
const s = slopeSeries[i];
|
|
377
|
+
if (s == null || !Number.isFinite(s)) {
|
|
378
|
+
prev = null;
|
|
379
|
+
prevDelta = null;
|
|
380
|
+
continue;
|
|
381
|
+
}
|
|
382
|
+
finite++;
|
|
383
|
+
sumSigned += s;
|
|
384
|
+
sumAbs += Math.abs(s);
|
|
385
|
+
sumSq += s * s;
|
|
386
|
+
if (Math.abs(s) >= maxSlopePct)
|
|
387
|
+
saturated++;
|
|
388
|
+
if (Math.abs(s) <= neutralZonePct)
|
|
389
|
+
neutral++;
|
|
390
|
+
const sign = Math.sign(s);
|
|
391
|
+
if (sign !== 0) {
|
|
392
|
+
if (lastSign !== 0 && sign !== lastSign)
|
|
393
|
+
zeroCross++;
|
|
394
|
+
lastSign = sign;
|
|
395
|
+
}
|
|
396
|
+
if (prev != null) {
|
|
397
|
+
const d = s - prev;
|
|
398
|
+
sumAbsDelta += Math.abs(d);
|
|
399
|
+
deltaCount++;
|
|
400
|
+
if (prevDelta != null) {
|
|
401
|
+
secondSq += (d - prevDelta) ** 2;
|
|
402
|
+
secondCount++;
|
|
403
|
+
}
|
|
404
|
+
prevDelta = d;
|
|
405
|
+
}
|
|
406
|
+
else {
|
|
407
|
+
prevDelta = null;
|
|
408
|
+
}
|
|
409
|
+
prev = s;
|
|
410
|
+
}
|
|
411
|
+
const meanAbsSlope = finite > 0 ? sumAbs / finite : 0;
|
|
412
|
+
const meanSlope = finite > 0 ? sumSigned / finite : 0;
|
|
413
|
+
const variance = finite > 0 ? Math.max(0, sumSq / finite - meanSlope * meanSlope) : 0;
|
|
414
|
+
// ── Range tilt (batch clip threshold; only affects offset, not timing) ──
|
|
415
|
+
const clipThreshold = computeAmaSlopeClipThreshold(amaValues, amaDef.er, lookbackBars, MA.DYNAMIC_WEIGHT_CLIP_PERCENTILE);
|
|
416
|
+
let offsetCount = 0, offsetAbsSum = 0;
|
|
417
|
+
for (let i = 0; i < n; i++) {
|
|
418
|
+
const s = slopeSeries[i];
|
|
419
|
+
if (s == null || !Number.isFinite(s))
|
|
420
|
+
continue;
|
|
421
|
+
const clipped = Math.max(-clipThreshold, Math.min(clipThreshold, s));
|
|
422
|
+
if (Math.abs(clipped) <= neutralZonePct)
|
|
423
|
+
continue;
|
|
424
|
+
offsetAbsSum += Math.abs(clipped / maxSlopePct) * maxSlopeOffset;
|
|
425
|
+
offsetCount++;
|
|
426
|
+
}
|
|
427
|
+
// ── Lag metrics ─────────────────────────────────────────────────────────
|
|
428
|
+
const maxLag = Math.max(1, lookbackBars * 2);
|
|
429
|
+
const priceLag = crossCorrelationLag(slopeSeries, priceTruthArr, maxLag);
|
|
430
|
+
const amaLag = crossCorrelationLag(slopeSeries, truthArr, maxLag);
|
|
431
|
+
// The reversal search window is wider than the xcorr window: a slow AMA can
|
|
432
|
+
// take well over one slope window to actually cross into a new regime.
|
|
433
|
+
const revMaxLag = Math.max(maxLag, truthHalf * 3);
|
|
434
|
+
const confirmPct = cfg.confirmFraction * meanAbsSlope;
|
|
435
|
+
const rev = reversalLag(slopeSeries, truthArr, revMaxLag, confirmPct);
|
|
436
|
+
// ── Reset metrics ───────────────────────────────────────────────────────
|
|
437
|
+
const resetEvents = sim.events.filter((e) => e.reason !== GRID_RESET_BOOTSTRAP);
|
|
438
|
+
const resetIdx = resetEvents.map((e) => e.index);
|
|
439
|
+
const gaps = [];
|
|
440
|
+
for (let k = 1; k < resetIdx.length; k++)
|
|
441
|
+
gaps.push(resetIdx[k] - resetIdx[k - 1]);
|
|
442
|
+
const whipsaws = gaps.filter((g) => g <= cfg.whipsawBars).length;
|
|
443
|
+
const resetsPerDay = (sim.stats.resets / liveBars) * 24;
|
|
444
|
+
const lastResetIndex = sim.stats.lastResetIndex;
|
|
445
|
+
// ── Range-tilt wrong-way (applied tilt vs realized forward move) ────────
|
|
446
|
+
// The band tilt only refreshes at resets, so the applied direction at bar t
|
|
447
|
+
// is the sign of the slope sampled at the most recent reset. Wrong-way =
|
|
448
|
+
// that applied direction points against the realized forward AMA move over
|
|
449
|
+
// `forwardWindowBars`. Geometry-independent: the tilt sign is sign(slope).
|
|
450
|
+
const forwardWindowCfg = Number(cfg.forwardWindowBars);
|
|
451
|
+
const forwardWindowBars = Number.isFinite(forwardWindowCfg) && forwardWindowCfg > 0
|
|
452
|
+
? Math.round(forwardWindowCfg)
|
|
453
|
+
: Math.max(1, lookbackBars);
|
|
454
|
+
const eventIdx = new Set(sim.events.map((e) => e.index));
|
|
455
|
+
let curAppliedDir = 0;
|
|
456
|
+
let evaluatedBars = 0, tiltActiveBars = 0, wrongWayBars = 0;
|
|
457
|
+
let curWrongStreak = 0;
|
|
458
|
+
const wrongStreaks = [];
|
|
459
|
+
const adverseMoves = [];
|
|
460
|
+
const closeStreak = () => { if (curWrongStreak > 0) {
|
|
461
|
+
wrongStreaks.push(curWrongStreak);
|
|
462
|
+
curWrongStreak = 0;
|
|
463
|
+
} };
|
|
464
|
+
for (let i = 0; i < n; i++) {
|
|
465
|
+
if (eventIdx.has(i)) {
|
|
466
|
+
const s = slopeSeries[i];
|
|
467
|
+
curAppliedDir = (s != null && Number.isFinite(s) && Math.abs(s) > neutralZonePct) ? Math.sign(s) : 0;
|
|
468
|
+
}
|
|
469
|
+
const fwdEnd = i + forwardWindowBars;
|
|
470
|
+
if (i < warmupBars || fwdEnd >= n) {
|
|
471
|
+
closeStreak();
|
|
472
|
+
continue;
|
|
473
|
+
}
|
|
474
|
+
const a0 = amaValues[i], a1 = amaValues[fwdEnd];
|
|
475
|
+
if (!Number.isFinite(a0) || a0 <= 0 || !Number.isFinite(a1)) {
|
|
476
|
+
closeStreak();
|
|
477
|
+
continue;
|
|
478
|
+
}
|
|
479
|
+
const fwdPct = ((a1 - a0) / a0) * 100;
|
|
480
|
+
const fwdDir = Math.sign(fwdPct);
|
|
481
|
+
if (fwdDir === 0) {
|
|
482
|
+
closeStreak();
|
|
483
|
+
continue;
|
|
484
|
+
}
|
|
485
|
+
evaluatedBars++;
|
|
486
|
+
if (curAppliedDir !== 0) {
|
|
487
|
+
tiltActiveBars++;
|
|
488
|
+
if (fwdDir !== curAppliedDir) {
|
|
489
|
+
wrongWayBars++;
|
|
490
|
+
curWrongStreak++;
|
|
491
|
+
adverseMoves.push(Math.abs(fwdPct));
|
|
492
|
+
}
|
|
493
|
+
else
|
|
494
|
+
closeStreak();
|
|
495
|
+
}
|
|
496
|
+
else {
|
|
497
|
+
closeStreak();
|
|
498
|
+
}
|
|
499
|
+
}
|
|
500
|
+
closeStreak();
|
|
501
|
+
return {
|
|
502
|
+
lookbackBars,
|
|
503
|
+
huberScaleMode: cfg.scaleMode,
|
|
504
|
+
meanOutlierFractionPct: meanOutlierFraction == null ? null : meanOutlierFraction * 100,
|
|
505
|
+
meanHuberScale,
|
|
506
|
+
// lag
|
|
507
|
+
priceLagBars: priceLag.lagBars,
|
|
508
|
+
priceLagCorr: priceLag.corr,
|
|
509
|
+
amaLagBars: amaLag.lagBars,
|
|
510
|
+
amaLagCorr: amaLag.corr,
|
|
511
|
+
reversalLagBars: rev.lagBars,
|
|
512
|
+
reversalFlips: rev.flips,
|
|
513
|
+
reversalMisses: rev.misses,
|
|
514
|
+
// resets
|
|
515
|
+
resets: sim.stats.resets,
|
|
516
|
+
resetsTotal: sim.stats.resetsTotal,
|
|
517
|
+
priceResets: sim.stats.priceResets,
|
|
518
|
+
slopeResets: sim.stats.slopeResets,
|
|
519
|
+
resetsPerDay,
|
|
520
|
+
avgBarsBetweenResets: gaps.length > 0 ? gaps.reduce((a, b) => a + b, 0) / gaps.length : null,
|
|
521
|
+
medianBarsBetweenResets: median(gaps),
|
|
522
|
+
p90BarsBetweenResets: percentile(gaps, 90),
|
|
523
|
+
minBarsBetweenResets: gaps.length > 0 ? Math.min(...gaps) : null,
|
|
524
|
+
whipsawResets: whipsaws,
|
|
525
|
+
whipsawPct: gaps.length > 0 ? (whipsaws / gaps.length) * 100 : 0,
|
|
526
|
+
gridAgeSinceLastResetBars: lastResetIndex == null ? null : n - 1 - lastResetIndex,
|
|
527
|
+
// noise / quality
|
|
528
|
+
meanAbsSlopePct: meanAbsSlope,
|
|
529
|
+
slopeStdPct: Math.sqrt(variance),
|
|
530
|
+
slopeWobblePct: deltaCount > 0 ? sumAbsDelta / deltaCount : 0,
|
|
531
|
+
secondDiffEnergy: secondCount > 0 ? secondSq / secondCount : 0,
|
|
532
|
+
zeroCrossPer1k: finite > 0 ? (zeroCross / finite) * 1000 : 0,
|
|
533
|
+
saturationPct: finite > 0 ? (saturated / finite) * 100 : 0,
|
|
534
|
+
neutralPct: finite > 0 ? (neutral / finite) * 100 : 0,
|
|
535
|
+
avgAbsRangeOffset: offsetCount > 0 ? offsetAbsSum / offsetCount : 0,
|
|
536
|
+
offsetActivePct: finite > 0 ? (offsetCount / finite) * 100 : 0,
|
|
537
|
+
// range-tilt wrong-way
|
|
538
|
+
forwardWindowBars,
|
|
539
|
+
rangeWrongWayPct: tiltActiveBars > 0 ? (wrongWayBars / tiltActiveBars) * 100 : null,
|
|
540
|
+
rangeTiltActivePct: evaluatedBars > 0 ? (tiltActiveBars / evaluatedBars) * 100 : null,
|
|
541
|
+
meanWrongStreakBars: wrongStreaks.length > 0 ? wrongStreaks.reduce((a, b) => a + b, 0) / wrongStreaks.length : null,
|
|
542
|
+
medianAdverseMoveWhileWrongPct: median(adverseMoves),
|
|
543
|
+
p90AdverseMoveWhileWrongPct: percentile(adverseMoves, 90),
|
|
544
|
+
// context
|
|
545
|
+
warmupBars,
|
|
546
|
+
finiteSlopeBars: finite,
|
|
547
|
+
};
|
|
548
|
+
}
|
|
549
|
+
// ─── Composite recommendation ────────────────────────────────────────────────
|
|
550
|
+
function normalize(values) {
|
|
551
|
+
const finite = values.filter((v) => Number.isFinite(v));
|
|
552
|
+
const lo = Math.min(...finite);
|
|
553
|
+
const hi = Math.max(...finite);
|
|
554
|
+
return (v) => (hi > lo ? (v - lo) / (hi - lo) : 0);
|
|
555
|
+
}
|
|
556
|
+
function addCompositeScore(results) {
|
|
557
|
+
const lagVals = results.map((r) => (r.reversalLagBars ?? r.amaLagBars));
|
|
558
|
+
const resetVals = results.map((r) => r.resetsPerDay);
|
|
559
|
+
const wobbleVals = results.map((r) => r.slopeWobblePct);
|
|
560
|
+
const nLag = normalize(lagVals);
|
|
561
|
+
const nReset = normalize(resetVals);
|
|
562
|
+
const nWobble = normalize(wobbleVals);
|
|
563
|
+
for (const r of results) {
|
|
564
|
+
const lag = (r.reversalLagBars ?? r.amaLagBars);
|
|
565
|
+
const freshness = 1 - nLag(lag);
|
|
566
|
+
const stability = 1 - nReset(r.resetsPerDay);
|
|
567
|
+
const smoothness = 1 - nWobble(r.slopeWobblePct);
|
|
568
|
+
r.compositeScore = (freshness + stability + smoothness) / 3;
|
|
569
|
+
}
|
|
570
|
+
}
|
|
571
|
+
// ─── Main ────────────────────────────────────────────────────────────────────
|
|
572
|
+
function run() {
|
|
573
|
+
const cfg = parseArgs();
|
|
574
|
+
const amaDef = resolveAma(cfg);
|
|
575
|
+
const { candles, meta, files } = loadCandles(cfg.dataPath);
|
|
576
|
+
const closes = candles.map((c) => c.close);
|
|
577
|
+
const n = closes.length;
|
|
578
|
+
const amaValues = calculateAMA(closes, { erPeriod: amaDef.er, fastPeriod: amaDef.fast, slowPeriod: amaDef.slow });
|
|
579
|
+
const warmupBars = getAmaWarmupBars(amaDef.er, amaDef.slow, 0, amaDef.fast);
|
|
580
|
+
const maxLookback = Math.max(...cfg.lookbacks);
|
|
581
|
+
const truthHalf = cfg.truthWindowBars ?? maxLookback;
|
|
582
|
+
// Centred Huber slope (uses future bars) — the zero-lag reference the causal
|
|
583
|
+
// slope is correlated against. Half-window is shared across lookbacks so
|
|
584
|
+
// lag differences come from the causal window, not the reference.
|
|
585
|
+
const amaTruth = new Array(n).fill(null);
|
|
586
|
+
const priceTruth = new Array(n).fill(null);
|
|
587
|
+
const truthEstimator = createHuberEstimator(cfg.scaleMode);
|
|
588
|
+
for (let t = truthHalf; t <= n - 1 - truthHalf; t++) {
|
|
589
|
+
const a = truthEstimator(amaValues, t + truthHalf, truthHalf * 2);
|
|
590
|
+
if (a != null && Number.isFinite(a))
|
|
591
|
+
amaTruth[t] = a;
|
|
592
|
+
const p = truthEstimator(closes, t + truthHalf, truthHalf * 2);
|
|
593
|
+
if (p != null && Number.isFinite(p))
|
|
594
|
+
priceTruth[t] = p;
|
|
595
|
+
}
|
|
596
|
+
console.log('================================================================================');
|
|
597
|
+
console.log(' AMA-SLOPE-HUBER LOOKBACK BACKTEST');
|
|
598
|
+
console.log('================================================================================');
|
|
599
|
+
console.log(` Data: ${path.resolve(cfg.dataPath)}`);
|
|
600
|
+
console.log(` ${files} file(s), ${n} candles, ${((n * (meta?.intervalSeconds ?? 3600)) / 86400).toFixed(0)} days`);
|
|
601
|
+
console.log(` AMA: ${amaDef.name} (er=${amaDef.er}, fast=${amaDef.fast}, slow=${amaDef.slow}), warmup ${warmupBars} bars`);
|
|
602
|
+
console.log(` Lookbacks: ${cfg.lookbacks.join(', ')} bars (${cfg.lookbacks.length} windows)`);
|
|
603
|
+
console.log(` Resets: drift >= ${cfg.priceThresholdPct}% | slope delta >= ${fmt((cfg.slopeThresholdFactor / 100) * MA.DYNAMIC_WEIGHT_AMA_MAX_SLOPE_PCT, 4)}%/bar` +
|
|
604
|
+
` (${cfg.slopeThresholdFactor}% of max ${MA.DYNAMIC_WEIGHT_AMA_MAX_SLOPE_PCT})${cfg.slopeEnabled ? '' : ' [OFF]'} | persist K=${cfg.slopePersistBars}`);
|
|
605
|
+
console.log(` Reference: centred Huber slope, half-window ${truthHalf} bars`);
|
|
606
|
+
console.log(` Huber: scale mode = ${cfg.scaleMode}`);
|
|
607
|
+
console.log(` Confirm: |slope| >= ${cfg.confirmFraction} x each window's mean |slope| (per-window gate)`);
|
|
608
|
+
console.log('');
|
|
609
|
+
const results = [];
|
|
610
|
+
for (const lb of cfg.lookbacks) {
|
|
611
|
+
const estimator = createHuberEstimator(cfg.scaleMode);
|
|
612
|
+
const r = analyzeLookback(closes, amaValues, lb, amaDef, cfg, amaTruth, priceTruth, truthHalf, estimator);
|
|
613
|
+
results.push(r);
|
|
614
|
+
process.stdout.write(` lb=${String(lb).padStart(2)} resets=${String(r.resets).padStart(4)} ` +
|
|
615
|
+
`lag(ama)=${fmt(r.amaLagBars, 0).padStart(3)} rev=${fmt(r.reversalLagBars, 1).padStart(5)} ` +
|
|
616
|
+
`wobble=${fmt(r.slopeWobblePct, 4)} zc/1k=${fmt(r.zeroCrossPer1k, 1)}\n`);
|
|
617
|
+
}
|
|
618
|
+
addCompositeScore(results);
|
|
619
|
+
// ── Metric table ────────────────────────────────────────────────────────
|
|
620
|
+
console.log('\n================================================================================');
|
|
621
|
+
console.log(' PER-LOOKBACK METRICS');
|
|
622
|
+
console.log('================================================================================');
|
|
623
|
+
console.log(' lb | resets rs/day | price slope | medGap p90 | whip% | lagP lagA | revLag | std wobble zc/1k | sat% | comp');
|
|
624
|
+
console.log('----+--------------+-------------+------------+-------+---------+--------+-----------------------+------+-----');
|
|
625
|
+
for (const r of results) {
|
|
626
|
+
console.log(` ${String(r.lookbackBars).padStart(2)} | ` +
|
|
627
|
+
`${String(r.resets).padStart(6)} ${fmt(r.resetsPerDay, 1).padStart(6)} | ` +
|
|
628
|
+
`${String(r.priceResets).padStart(5)} ${String(r.slopeResets).padStart(5)} | ` +
|
|
629
|
+
`${fmt(r.medianBarsBetweenResets, 0).padStart(6)} ${fmt(r.p90BarsBetweenResets, 0).padStart(4)} | ` +
|
|
630
|
+
`${fmt(r.whipsawPct, 0).padStart(5)} | ` +
|
|
631
|
+
`${fmt(r.priceLagBars, 0).padStart(4)} ${fmt(r.amaLagBars, 0).padStart(4)} | ` +
|
|
632
|
+
`${fmt(r.reversalLagBars, 1).padStart(6)} | ` +
|
|
633
|
+
`${fmt(r.slopeStdPct, 4).padStart(6)} ${fmt(r.slopeWobblePct, 4).padStart(7)} ${fmt(r.zeroCrossPer1k, 1).padStart(6)} | ` +
|
|
634
|
+
`${fmt(r.saturationPct, 0).padStart(4)} | ` +
|
|
635
|
+
`${fmt(r.compositeScore, 3)}`);
|
|
636
|
+
}
|
|
637
|
+
console.log('\n Correlation strength at the peak (higher = more reliable lag estimate):');
|
|
638
|
+
console.log(' lb | priceCorr | amaCorr | reversalFlips | reversalMisses | offsetActive% | avg|offset|');
|
|
639
|
+
console.log(' ---+-----------+---------+---------------+----------------+---------------+------------');
|
|
640
|
+
for (const r of results) {
|
|
641
|
+
console.log(` ${String(r.lookbackBars).padStart(2)} | ` +
|
|
642
|
+
`${fmt(r.priceLagCorr, 3).padStart(9)} | ` +
|
|
643
|
+
`${fmt(r.amaLagCorr, 3).padStart(7)} | ` +
|
|
644
|
+
`${String(r.reversalFlips).padStart(13)} | ` +
|
|
645
|
+
`${String(r.reversalMisses).padStart(14)} | ` +
|
|
646
|
+
`${fmt(r.offsetActivePct, 1).padStart(13)} | ` +
|
|
647
|
+
`${fmt(r.avgAbsRangeOffset, 4).padStart(12)}`);
|
|
648
|
+
}
|
|
649
|
+
console.log(`\n Huber scale mode: ${cfg.scaleMode} (outlier = |residual| > C x scale)`);
|
|
650
|
+
console.log(' lb | mean outlier% | mean scale (log units)');
|
|
651
|
+
console.log(' ---+---------------+----------------------');
|
|
652
|
+
for (const r of results) {
|
|
653
|
+
console.log(` ${String(r.lookbackBars).padStart(2)} | ` +
|
|
654
|
+
`${fmt(r.meanOutlierFractionPct, 2).padStart(13)} | ` +
|
|
655
|
+
`${fmt(r.meanHuberScale, 5).padStart(20)}`);
|
|
656
|
+
}
|
|
657
|
+
console.log('\n Range-tilt wrong-way (applied tilt vs realized forward AMA move):');
|
|
658
|
+
console.log(' var | tiltActive% | wrongWay% | meanWrongRun | medAdverse | p90Adverse');
|
|
659
|
+
console.log(' -------+-------------+-----------+--------------+------------+-----------');
|
|
660
|
+
for (const r of results) {
|
|
661
|
+
console.log(` ${String(r.lookbackBars).padStart(5)} | ` +
|
|
662
|
+
`${fmt(r.rangeTiltActivePct, 1).padStart(11)} | ` +
|
|
663
|
+
`${fmt(r.rangeWrongWayPct, 1).padStart(9)} | ` +
|
|
664
|
+
`${fmt(r.meanWrongStreakBars, 1).padStart(12)} | ` +
|
|
665
|
+
`${fmt(r.medianAdverseMoveWhileWrongPct, 2).padStart(10)} | ` +
|
|
666
|
+
`${fmt(r.p90AdverseMoveWhileWrongPct, 2).padStart(10)}`);
|
|
667
|
+
}
|
|
668
|
+
// ── Sweet spot (heuristic) ──────────────────────────────────────────────
|
|
669
|
+
const ranked = results.slice().sort((a, b) => b.compositeScore - a.compositeScore);
|
|
670
|
+
const winner = ranked[0];
|
|
671
|
+
console.log('\n================================================================================');
|
|
672
|
+
console.log(' HEURISTIC SWEET SPOT');
|
|
673
|
+
console.log('================================================================================');
|
|
674
|
+
console.log(' Composite = equal-weight mean of (low reversal lag, low reset rate, low wobble),');
|
|
675
|
+
console.log(' each min-max normalised across the swept lookbacks. Not a P&L objective —');
|
|
676
|
+
console.log(' use the per-metric table to trade lag against reset churn for your own fill model.');
|
|
677
|
+
console.log(`\n lb=${winner.lookbackBars}: lagA=${fmt(winner.amaLagBars, 0)} revLag=${fmt(winner.reversalLagBars, 1)} ` +
|
|
678
|
+
`resets/day=${fmt(winner.resetsPerDay, 1)} wobble=${fmt(winner.slopeWobblePct, 4)} score=${fmt(winner.compositeScore, 3)}`);
|
|
679
|
+
// ── Persist ─────────────────────────────────────────────────────────────
|
|
680
|
+
const base = path.basename(path.resolve(cfg.dataPath)).replace(/\.json$/i, '');
|
|
681
|
+
const outPath = cfg.outPath ?? path.join(PATHS.ANALYSIS.RESULTS_DIR, `ama_slope_huber_lookback_${base}.json`);
|
|
682
|
+
fs.mkdirSync(path.dirname(outPath), { recursive: true });
|
|
683
|
+
writeJSON(outPath, {
|
|
684
|
+
meta: {
|
|
685
|
+
generatedAt: new Date().toISOString(),
|
|
686
|
+
dataPath: path.relative(process.cwd(), path.resolve(cfg.dataPath)),
|
|
687
|
+
files,
|
|
688
|
+
candles: n,
|
|
689
|
+
ama: amaDef,
|
|
690
|
+
warmupBars,
|
|
691
|
+
lookbacks: cfg.lookbacks,
|
|
692
|
+
slopePersistBars: cfg.slopePersistBars,
|
|
693
|
+
huberScaleMode: cfg.scaleMode,
|
|
694
|
+
resetConfig: {
|
|
695
|
+
priceDeltaThresholdPercent: cfg.priceThresholdPct,
|
|
696
|
+
slopeDeltaThresholdPercent: (cfg.slopeThresholdFactor / 100) * MA.DYNAMIC_WEIGHT_AMA_MAX_SLOPE_PCT,
|
|
697
|
+
slopeThresholdFactor: cfg.slopeThresholdFactor,
|
|
698
|
+
slopeEnabled: cfg.slopeEnabled,
|
|
699
|
+
maxSlopePct: MA.DYNAMIC_WEIGHT_AMA_MAX_SLOPE_PCT,
|
|
700
|
+
neutralZonePct: MA.DYNAMIC_WEIGHT_AMA_NEUTRAL_ZONE_PCT,
|
|
701
|
+
clipPercentile: MA.DYNAMIC_WEIGHT_CLIP_PERCENTILE,
|
|
702
|
+
},
|
|
703
|
+
lagConfig: {
|
|
704
|
+
reference: `centred Huber slope, half-window ${truthHalf} bars`,
|
|
705
|
+
confirmPct: `${cfg.confirmFraction} x each window's mean |slope|`,
|
|
706
|
+
},
|
|
707
|
+
whipsawBars: cfg.whipsawBars,
|
|
708
|
+
notes: 'Reset replay uses the canonical simulateGridResetSeries decision path (unclipped slope — clip only affects range tilt). Lag is a cross-correlation group-delay estimate; reversalLag is the median bars from a sign flip in the centred AMA slope to causal confirmation.',
|
|
709
|
+
},
|
|
710
|
+
results,
|
|
711
|
+
sweetSpot: winner,
|
|
712
|
+
});
|
|
713
|
+
console.log(`\nSaved: ${path.relative(process.cwd(), outPath)}`);
|
|
714
|
+
}
|
|
715
|
+
if (process.argv[1] && import.meta.url === pathToFileURL(process.argv[1]).href) {
|
|
716
|
+
try {
|
|
717
|
+
run();
|
|
718
|
+
}
|
|
719
|
+
catch (err) {
|
|
720
|
+
console.error(err);
|
|
721
|
+
process.exit(1);
|
|
722
|
+
}
|
|
723
|
+
}
|
|
724
|
+
export { loadCandles, crossCorrelationLag, reversalLag, analyzeLookback };
|
|
725
|
+
//# sourceMappingURL=backtest_ama_slope_huber.js.map
|