dexbot 1.6.8 → 1.6.10
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +42 -0
- package/analysis/README.md +1 -1
- package/analysis/tradingview/README.md +14 -9
- package/claw/modules/chain_queries.ts +9 -4
- package/claw/modules/claw_bridge.ts +9 -9
- 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/ama_fitting/optimizer_high_resolution.js +2 -1
- package/dist/analysis/bot_fitting/backtest_ama_sweep.js +2 -2
- package/dist/analysis/bot_fitting/backtest_bot_fitting.js +4 -4
- package/dist/analysis/bot_key_utils.js +14 -4
- package/dist/analysis/tradingview/analyze_tradingview.d.ts +0 -3
- package/dist/analysis/tradingview/analyze_tradingview.js +3 -14
- package/dist/analysis/tradingview/grid_reset_sim.d.ts +11 -1
- package/dist/analysis/tradingview/grid_reset_sim.js +22 -9
- package/dist/analysis/tradingview/tradingview_uplot_chart_generator.js +178 -32
- package/dist/analysis/trend_detection/dynamic_weight_chart_generator.js +8 -3
- package/dist/dexbot.js +57 -29
- package/dist/market_adapter/core/market_adapter_service.d.ts +81 -1
- package/dist/market_adapter/core/market_adapter_service.js +225 -18
- package/dist/market_adapter/core/signals/hurst_analyzer.d.ts +10 -1
- package/dist/market_adapter/core/signals/hurst_analyzer.js +40 -18
- package/dist/market_adapter/core/signals/permutation_entropy_analyzer.d.ts +26 -2
- package/dist/market_adapter/core/signals/permutation_entropy_analyzer.js +132 -29
- package/dist/market_adapter/core/strategies/ama_slope_model.d.ts +2 -2
- package/dist/market_adapter/core/strategies/ama_slope_model.js +12 -10
- package/dist/market_adapter/core/strategies/dynamic_weight_series.d.ts +41 -14
- package/dist/market_adapter/core/strategies/dynamic_weight_series.js +138 -30
- package/dist/market_adapter/core/strategies/regime_gate.d.ts +61 -3
- package/dist/market_adapter/core/strategies/regime_gate.js +207 -7
- package/dist/market_adapter/interval_utils.d.ts +18 -1
- package/dist/market_adapter/interval_utils.js +31 -1
- package/dist/market_adapter/lp_chart_strategy_loader.js +2 -1
- package/dist/market_adapter/market_adapter.d.ts +151 -2
- package/dist/market_adapter/market_adapter.js +378 -62
- package/dist/market_adapter/test_helpers.d.ts +2 -2
- package/dist/market_adapter/test_helpers.js +2 -2
- package/dist/market_adapter/utils/chain.d.ts +1 -1
- package/dist/market_adapter/utils/chain.js +8 -6
- package/dist/market_adapter/utils/file_json_cache.d.ts +29 -0
- package/dist/market_adapter/utils/file_json_cache.js +106 -0
- package/dist/modules/account_bots.js +5 -4
- package/dist/modules/bitshares-native/resolvers.js +5 -0
- package/dist/modules/bot_settings.js +13 -1
- package/dist/modules/chain_orders.js +2 -1
- package/dist/modules/config.d.ts +6 -0
- package/dist/modules/config.js +1 -0
- package/dist/modules/constants.d.ts +11 -1
- package/dist/modules/constants.js +64 -15
- package/dist/modules/credential_policy.js +4 -1
- package/dist/modules/credit_runtime.js +5 -1
- package/dist/modules/order/grid.js +95 -25
- package/dist/modules/order/utils/system.js +11 -1
- package/dist/modules/utils/asset_symbols.d.ts +59 -0
- package/dist/modules/utils/asset_symbols.js +128 -0
- package/dist/modules/version_notice.d.ts +166 -20
- package/dist/modules/version_notice.js +401 -56
- package/dist/pm2.js +9 -2
- package/dist/scripts/analyze-credit.js +10 -7
- package/dist/scripts/chart_command.js +12 -4
- package/dist/scripts/verify-browser-bundle.js +8 -0
- package/dist/unlock.js +7 -7
- package/docs/DEXBOT_COMPARISON.md +3 -3
- package/docs/EVOLUTION.md +14 -12
- package/docs/FUND_MOVEMENT_AND_ACCOUNTING.md +1 -1
- package/docs/GRID_RECALCULATION.md +28 -5
- package/docs/README.md +2 -2
- package/market_adapter/README.md +30 -2
- package/package.json +1 -1
|
@@ -17,20 +17,73 @@ import { roundTo } from '../../../modules/order/utils/math.js';
|
|
|
17
17
|
* Thresholds are defined in MARKET_ADAPTER.PE_NODES in constants.ts.
|
|
18
18
|
*
|
|
19
19
|
* Default: m=5 (5!=120 patterns), window=100 bars.
|
|
20
|
+
*
|
|
21
|
+
* PERFORMANCE (2026-09): the analyzer is re-created and re-fed the whole candle
|
|
22
|
+
* history for every bot on every hourly cycle, and the rolling window only ever
|
|
23
|
+
* depends on the last `bufSize` prices. The first implementation re-counted all
|
|
24
|
+
* `window` patterns on every `update()` and encoded each pattern as a *string*,
|
|
25
|
+
* so one cycle cost ~42k patterns x (5 heap objects + comparator sort + string
|
|
26
|
+
* concat) per bot. The count map is now maintained incrementally (only the
|
|
27
|
+
* entering and the leaving pattern change per update) and patterns are encoded as
|
|
28
|
+
* factorial-number-system integers, so `update()` allocates nothing and does O(1)
|
|
29
|
+
* work plus one O(distinct patterns) entropy pass. Measured on an 782-bar series:
|
|
30
|
+
* ~10 ms -> ~0.2 ms per bot per cycle, with the same entropy values (the sum is
|
|
31
|
+
* taken over the same multiset of counts, so results agree to float noise; see
|
|
32
|
+
* tests/test_market_adapter_entropy_equivalence.ts).
|
|
20
33
|
*/
|
|
34
|
+
// Pattern-key scratch buffers. The analyzer is synchronous and single-threaded,
|
|
35
|
+
// so one module-level scratch pair is enough and keeps `update()` allocation-free.
|
|
36
|
+
// Sized for the largest supported embedding dimension (PE_ANALYZER_LIMITS.M_MAX).
|
|
37
|
+
const SCRATCH_VALUES = new Float64Array(MARKET_ADAPTER.PE_ANALYZER_LIMITS.M_MAX);
|
|
38
|
+
const SCRATCH_INDICES = new Int32Array(MARKET_ADAPTER.PE_ANALYZER_LIMITS.M_MAX);
|
|
39
|
+
// (m-1)! table for the Lehmer/rank encoding, indexed by m.
|
|
40
|
+
const FACTORIAL = (() => {
|
|
41
|
+
const table = [1, 1];
|
|
42
|
+
for (let i = 2; i <= MARKET_ADAPTER.PE_ANALYZER_LIMITS.M_MAX; i++)
|
|
43
|
+
table.push(table[i - 1] * i);
|
|
44
|
+
return table;
|
|
45
|
+
})();
|
|
21
46
|
/**
|
|
22
|
-
*
|
|
23
|
-
*
|
|
24
|
-
*
|
|
47
|
+
* Ordinal pattern key for the m values starting at `prices[start]`, stepping by
|
|
48
|
+
* `delay`. Returns the permutation of source indices (sorted by value, ties
|
|
49
|
+
* broken by source index) encoded as a factorial-number-system integer, so the
|
|
50
|
+
* key is a small int (m! - 1 <= 5039 for m = 7) instead of a string.
|
|
51
|
+
*
|
|
52
|
+
* Sorting uses a preallocated scratch pair and insertion sort (m <= 7), so the
|
|
53
|
+
* hot path allocates nothing.
|
|
25
54
|
*/
|
|
26
|
-
function
|
|
27
|
-
|
|
28
|
-
|
|
29
|
-
|
|
30
|
-
|
|
31
|
-
|
|
32
|
-
|
|
33
|
-
|
|
55
|
+
function ordinalPatternKey(prices, start, m, delay) {
|
|
56
|
+
for (let j = 0; j < m; j++) {
|
|
57
|
+
SCRATCH_VALUES[j] = prices[start + j * delay];
|
|
58
|
+
SCRATCH_INDICES[j] = j;
|
|
59
|
+
}
|
|
60
|
+
// Insertion sort by (value, source index) — same ordering as the previous
|
|
61
|
+
// `Array.sort((a, b) => a.v !== b.v ? a.v - b.v : a.j - b.j)` comparator.
|
|
62
|
+
for (let j = 1; j < m; j++) {
|
|
63
|
+
const value = SCRATCH_VALUES[j];
|
|
64
|
+
const index = SCRATCH_INDICES[j];
|
|
65
|
+
let i = j - 1;
|
|
66
|
+
while (i >= 0 && (SCRATCH_VALUES[i] > value || (SCRATCH_VALUES[i] === value && SCRATCH_INDICES[i] > index))) {
|
|
67
|
+
SCRATCH_VALUES[i + 1] = SCRATCH_VALUES[i];
|
|
68
|
+
SCRATCH_INDICES[i + 1] = SCRATCH_INDICES[i];
|
|
69
|
+
i--;
|
|
70
|
+
}
|
|
71
|
+
SCRATCH_VALUES[i + 1] = value;
|
|
72
|
+
SCRATCH_INDICES[i + 1] = index;
|
|
73
|
+
}
|
|
74
|
+
// Lehmer code of the resulting permutation: digit j counts how many of the
|
|
75
|
+
// indices still to the right are smaller than SCRATCH_INDICES[j]. Digits are
|
|
76
|
+
// bounded by (m-1-j), so the encoding is collision free.
|
|
77
|
+
let key = 0;
|
|
78
|
+
for (let j = 0; j < m - 1; j++) {
|
|
79
|
+
const current = SCRATCH_INDICES[j];
|
|
80
|
+
let smaller = 0;
|
|
81
|
+
for (let k = j + 1; k < m; k++) {
|
|
82
|
+
if (SCRATCH_INDICES[k] < current)
|
|
83
|
+
smaller++;
|
|
84
|
+
}
|
|
85
|
+
key += smaller * FACTORIAL[m - 1 - j];
|
|
86
|
+
}
|
|
34
87
|
return key;
|
|
35
88
|
}
|
|
36
89
|
class PermutationEntropyAnalyzer {
|
|
@@ -38,8 +91,11 @@ class PermutationEntropyAnalyzer {
|
|
|
38
91
|
delay;
|
|
39
92
|
window;
|
|
40
93
|
_bufSize;
|
|
94
|
+
bufferBars;
|
|
41
95
|
_maxEntropy;
|
|
42
96
|
_prices;
|
|
97
|
+
_priceCount;
|
|
98
|
+
_counts;
|
|
43
99
|
_updateCount;
|
|
44
100
|
entropy;
|
|
45
101
|
normalizedEntropy;
|
|
@@ -73,16 +129,55 @@ class PermutationEntropyAnalyzer {
|
|
|
73
129
|
this.window = window;
|
|
74
130
|
// Buffer must hold `window` patterns; each pattern spans (m-1)*delay+1 prices.
|
|
75
131
|
this._bufSize = this.window + (this.m - 1) * this.delay;
|
|
132
|
+
// Exposed so the regime gate can ask how much history this analyzer's
|
|
133
|
+
// state actually depends on, instead of mirroring these defaults (which
|
|
134
|
+
// drift the moment a default changes).
|
|
135
|
+
this.bufferBars = this._bufSize;
|
|
76
136
|
let f = 1;
|
|
77
137
|
for (let i = 2; i <= this.m; i++)
|
|
78
138
|
f *= i;
|
|
79
139
|
this._maxEntropy = Math.log(f); // log(m!)
|
|
80
|
-
this._prices =
|
|
140
|
+
this._prices = new Float64Array(this._bufSize);
|
|
141
|
+
this._priceCount = 0;
|
|
142
|
+
this._counts = new Map();
|
|
81
143
|
this._updateCount = 0;
|
|
82
144
|
this.entropy = 0;
|
|
83
145
|
this.normalizedEntropy = 0;
|
|
84
146
|
this.isReady = false;
|
|
85
147
|
}
|
|
148
|
+
/** Number of ordinal patterns currently inside a full buffer. */
|
|
149
|
+
get _numPatterns() {
|
|
150
|
+
return this._priceCount - (this.m - 1) * this.delay;
|
|
151
|
+
}
|
|
152
|
+
_addPattern(key) {
|
|
153
|
+
this._counts.set(key, (this._counts.get(key) ?? 0) + 1);
|
|
154
|
+
}
|
|
155
|
+
_removePattern(key) {
|
|
156
|
+
const current = this._counts.get(key);
|
|
157
|
+
if (current === undefined)
|
|
158
|
+
return;
|
|
159
|
+
if (current <= 1)
|
|
160
|
+
this._counts.delete(key);
|
|
161
|
+
else
|
|
162
|
+
this._counts.set(key, current - 1);
|
|
163
|
+
}
|
|
164
|
+
/**
|
|
165
|
+
* Shannon entropy: H = -Σ p_k * log(p_k) over the live pattern counts.
|
|
166
|
+
* Iterating the (small, <= min(window, m!)) count map is cheaper than
|
|
167
|
+
* maintaining a running sum and keeps the arithmetic identical to counting
|
|
168
|
+
* the window from scratch.
|
|
169
|
+
*/
|
|
170
|
+
_entropyFromCounts() {
|
|
171
|
+
const numPatterns = this._numPatterns;
|
|
172
|
+
if (numPatterns <= 0)
|
|
173
|
+
return 0;
|
|
174
|
+
let entropy = 0;
|
|
175
|
+
for (const count of this._counts.values()) {
|
|
176
|
+
const p = count / numPatterns;
|
|
177
|
+
entropy -= p * Math.log(p);
|
|
178
|
+
}
|
|
179
|
+
return entropy;
|
|
180
|
+
}
|
|
86
181
|
/**
|
|
87
182
|
* Feed a new price and return analysis.
|
|
88
183
|
* @param {number} price
|
|
@@ -92,28 +187,36 @@ class PermutationEntropyAnalyzer {
|
|
|
92
187
|
if (!Number.isFinite(price) || price <= 0) {
|
|
93
188
|
throw new Error('price must be a positive finite number');
|
|
94
189
|
}
|
|
95
|
-
this.
|
|
96
|
-
|
|
97
|
-
|
|
190
|
+
const m = this.m;
|
|
191
|
+
const delay = this.delay;
|
|
192
|
+
const wasFull = this._priceCount === this._bufSize;
|
|
193
|
+
if (wasFull) {
|
|
194
|
+
// The pattern that starts at index 0 is the one leaving the window;
|
|
195
|
+
// drop it before the buffer shifts left.
|
|
196
|
+
this._removePattern(ordinalPatternKey(this._prices, 0, m, delay));
|
|
197
|
+
this._prices.copyWithin(0, 1);
|
|
198
|
+
this._priceCount--;
|
|
199
|
+
}
|
|
200
|
+
this._prices[this._priceCount++] = price;
|
|
98
201
|
this._updateCount++;
|
|
99
|
-
if (this.
|
|
202
|
+
if (this._priceCount < this._bufSize) {
|
|
100
203
|
this.isReady = false;
|
|
101
204
|
return this.getAnalysis();
|
|
102
205
|
}
|
|
103
|
-
|
|
104
|
-
|
|
105
|
-
|
|
106
|
-
|
|
107
|
-
for (let i = 0; i < numPatterns; i++) {
|
|
108
|
-
const key = ordinalPattern(this._prices, i, this.m, this.delay);
|
|
109
|
-
counts.set(key, (counts.get(key) ?? 0) + 1);
|
|
206
|
+
if (wasFull) {
|
|
207
|
+
// Steady state: only the newly completed pattern needs counting,
|
|
208
|
+
// because the leaving one was just decremented.
|
|
209
|
+
this._addPattern(ordinalPatternKey(this._prices, this._numPatterns - 1, m, delay));
|
|
110
210
|
}
|
|
111
|
-
|
|
112
|
-
|
|
113
|
-
|
|
114
|
-
const
|
|
115
|
-
|
|
211
|
+
else {
|
|
212
|
+
// First time the buffer is full: seed the counts with every pattern
|
|
213
|
+
// the window currently contains.
|
|
214
|
+
const numPatterns = this._numPatterns;
|
|
215
|
+
for (let i = 0; i < numPatterns; i++) {
|
|
216
|
+
this._addPattern(ordinalPatternKey(this._prices, i, m, delay));
|
|
217
|
+
}
|
|
116
218
|
}
|
|
219
|
+
const entropy = this._entropyFromCounts();
|
|
117
220
|
this.entropy = entropy;
|
|
118
221
|
this.normalizedEntropy = this._maxEntropy > 0 ? entropy / this._maxEntropy : 0;
|
|
119
222
|
this.isReady = true;
|
|
@@ -145,5 +248,5 @@ class PermutationEntropyAnalyzer {
|
|
|
145
248
|
};
|
|
146
249
|
}
|
|
147
250
|
}
|
|
148
|
-
export { PermutationEntropyAnalyzer };
|
|
251
|
+
export { PermutationEntropyAnalyzer, ordinalPatternKey };
|
|
149
252
|
//# sourceMappingURL=permutation_entropy_analyzer.js.map
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { computeAverageAmaSlopePct, computeAmaSlopeClipThreshold, createAmaSlopeClipTracker } from './dynamic_weight_series.js';
|
|
1
|
+
import { computeAverageAmaSlopePct, computeHuberWindowSlopePct, computeAmaSlopeClipThreshold, createAmaSlopeClipTracker } from './dynamic_weight_series.js';
|
|
2
2
|
/**
|
|
3
3
|
* Compute AMA slope and volatility offsets from the AMA series.
|
|
4
4
|
*
|
|
@@ -31,5 +31,5 @@ declare function computeAmaSlopeWeights(amaValues: any, weightVariance: any, opt
|
|
|
31
31
|
trend: string;
|
|
32
32
|
isReady: boolean;
|
|
33
33
|
};
|
|
34
|
-
export { computeAmaSlopeWeights, computeAverageAmaSlopePct, computeAmaSlopeClipThreshold, createAmaSlopeClipTracker, };
|
|
34
|
+
export { computeAmaSlopeWeights, computeAverageAmaSlopePct, computeHuberWindowSlopePct, computeAmaSlopeClipThreshold, createAmaSlopeClipTracker, };
|
|
35
35
|
//# sourceMappingURL=ama_slope_model.d.ts.map
|
|
@@ -6,7 +6,7 @@ import { normalizeMaxVolatilityOffset, normalizeVolatilityThreshold, } from '../
|
|
|
6
6
|
import { computeVolatilityShift } from './volatility_shift.js';
|
|
7
7
|
// Canonical AMA slope % lives in dynamic_weight_series.ts (self-contained so the
|
|
8
8
|
// chart generators can embed its exact source); re-exported here for compat.
|
|
9
|
-
import { computeAverageAmaSlopePct, computeAmaSlopeClipThreshold, createAmaSlopeClipTracker, } from './dynamic_weight_series.js';
|
|
9
|
+
import { computeAverageAmaSlopePct, computeHuberWindowSlopePct, computeAmaSlopeClipThreshold, createAmaSlopeClipTracker, } from './dynamic_weight_series.js';
|
|
10
10
|
const _DEFAULT_AMA_KEY = MARKET_ADAPTER.DEFAULT_AMA_KEY;
|
|
11
11
|
const DEFAULT_ER_PERIOD = MARKET_ADAPTER.AMAS[_DEFAULT_AMA_KEY].erPeriod;
|
|
12
12
|
/**
|
|
@@ -74,14 +74,16 @@ function computeAmaSlopeWeights(amaValues, weightVariance, opts = {}) {
|
|
|
74
74
|
return notReady;
|
|
75
75
|
}
|
|
76
76
|
const N = amaValues.length;
|
|
77
|
-
|
|
78
|
-
|
|
79
|
-
|
|
80
|
-
|
|
81
|
-
|
|
82
|
-
//
|
|
83
|
-
// lookback
|
|
84
|
-
|
|
77
|
+
// 2. Slope percent per bar over the lookback window, as a Huber-robust
|
|
78
|
+
// linear regression of ln(AMA) (canonical: computeHuberWindowSlopePct). The
|
|
79
|
+
// two-point endpoint difference is kept in dynamic_weight_series as the
|
|
80
|
+
// reference definition, but it gives the window-edge bar full weight: a
|
|
81
|
+
// single-bar impulse moves it 7x-70x the reset gate while the robust fit
|
|
82
|
+
// bounds that influence without the lag of a rank-based estimator.
|
|
83
|
+
// lookback stays a smoothing/lag knob rather than adding gain in sustained
|
|
84
|
+
// trends. The estimator validates every bar in the window (both ends
|
|
85
|
+
// strictly positive), so it subsumes the old two-endpoint guard here.
|
|
86
|
+
const slopePct = computeHuberWindowSlopePct(amaValues, N - 1, lookbackBars);
|
|
85
87
|
if (!Number.isFinite(slopePct)) {
|
|
86
88
|
return notReady;
|
|
87
89
|
}
|
|
@@ -130,5 +132,5 @@ function computeAmaSlopeWeights(amaValues, weightVariance, opts = {}) {
|
|
|
130
132
|
// computeAmaSlopeClipThreshold and createAmaSlopeClipTracker live in
|
|
131
133
|
// dynamic_weight_series.ts (self-contained so the chart generators can embed
|
|
132
134
|
// their exact source); re-exported here so Node callers keep this import path.
|
|
133
|
-
export { computeAmaSlopeWeights, computeAverageAmaSlopePct, computeAmaSlopeClipThreshold, createAmaSlopeClipTracker, };
|
|
135
|
+
export { computeAmaSlopeWeights, computeAverageAmaSlopePct, computeHuberWindowSlopePct, computeAmaSlopeClipThreshold, createAmaSlopeClipTracker, };
|
|
134
136
|
//# sourceMappingURL=ama_slope_model.js.map
|
|
@@ -1,20 +1,47 @@
|
|
|
1
|
+
declare function computeAverageAmaSlopePct(current: any, past: any, lookbackBars: any): number | null;
|
|
1
2
|
/**
|
|
2
|
-
*
|
|
3
|
-
*
|
|
4
|
-
*
|
|
3
|
+
* Per-bar AMA trend in %/bar over `lookbackBars`, fitted as a Huber-robust
|
|
4
|
+
* linear regression of ln(AMA) against bar index (uniform weights, no kernel).
|
|
5
|
+
*
|
|
6
|
+
* This is the canonical slope used by the live adapter (dynamic weight series,
|
|
7
|
+
* AMA slope model, both clip paths), the grid-reset replay and the research
|
|
8
|
+
* charts, which embed this exact source via `embedFunctionSources`. One
|
|
9
|
+
* definition, one set of numbers — do not re-implement it per caller. Selected
|
|
10
|
+
* experimentally on a real 1h pool: it is the smoothest robust option measured
|
|
11
|
+
* (second-difference energy ~25x lower than the median's, max |dSlope|
|
|
12
|
+
* comparable to the two-point endpoint), because its influence function is
|
|
13
|
+
* continuous and bounded rather than an order statistic.
|
|
14
|
+
*
|
|
15
|
+
* The fit is local linear over `lookbackBars` intervals (bars+1 points, the same
|
|
16
|
+
* 20h span the endpoint uses), so a window-wide regime change tilts the line
|
|
17
|
+
* continuously instead of waiting for a majority, and a lone off-trend spike is
|
|
18
|
+
* bounded rather than given full endpoint weight. Output is the log-return per
|
|
19
|
+
* bar x 100. That differs from the arithmetic per-bar return by ~beta^2/2,
|
|
20
|
+
* which is negligible at the sub-0.1 %/bar magnitudes the defaults use (order
|
|
21
|
+
* 1e-9 at 0.1 %/bar) but grows quadratically with the reading — ln(1.06)*100 =
|
|
22
|
+
* 5.83, ~3% below a 6%/bar arithmetic rate. A pre-existing user override of
|
|
23
|
+
* maxSlopePct / neutralZonePct was tuned against the arithmetic reading, so a
|
|
24
|
+
* saturated override now clamps a hair tighter than before.
|
|
5
25
|
*
|
|
6
|
-
*
|
|
7
|
-
*
|
|
8
|
-
*
|
|
9
|
-
*
|
|
26
|
+
* Persistence note: `slopePct` is a different quantity from any pre-Huber
|
|
27
|
+
* reading (log-return regression vs the old median/endpoint). The first cycle
|
|
28
|
+
* after deploying compares a Huber reading against the still-persisted old
|
|
29
|
+
* baseline (botState.gridRangeScalingAmaSlope); the two magnitudes agree
|
|
30
|
+
* closely, so that delta sits below the reset gate on ~98% of bars (p50
|
|
31
|
+
* 0.00043, p90 0.00277 %/bar) — roughly one whitelisted bot in fifty costs one
|
|
32
|
+
* extra recenter, once. No version marker is persisted to suppress it.
|
|
10
33
|
*
|
|
11
|
-
*
|
|
12
|
-
*
|
|
13
|
-
*
|
|
14
|
-
*
|
|
15
|
-
*
|
|
34
|
+
* Parameters come from MARKET_ADAPTER.DYNAMIC_WEIGHT_AMA_HUBER (aliased as
|
|
35
|
+
* AMA_SLOPE_HUBER; injected into generated charts). `hub` is overridable only so
|
|
36
|
+
* tests can prove the values are threaded through — production never passes it.
|
|
37
|
+
*
|
|
38
|
+
* @param amaValues Full AMA series (index-addressable).
|
|
39
|
+
* @param index Bar to measure at (evaluated at the window edge).
|
|
40
|
+
* @param lookbackBars Window length in bars (fixed at 20 for every estimator).
|
|
41
|
+
* @param hub Parameter block; defaults to the centralized constant.
|
|
42
|
+
* @returns %/bar, or null when the window is unusable.
|
|
16
43
|
*/
|
|
17
|
-
declare function
|
|
44
|
+
declare function computeHuberWindowSlopePct(amaValues: any, index: number, lookbackBars: any, hub?: any): number | null;
|
|
18
45
|
declare function echoLatchSeries(appliedSeries: any[], preGainSeries: any[], confirmBars: any): {
|
|
19
46
|
echoedAppliedSeries: any[];
|
|
20
47
|
echoedPreGainSeries: any[];
|
|
@@ -74,5 +101,5 @@ declare function computeAmaSlopeClipThreshold(amaValues: any, erPeriod: number,
|
|
|
74
101
|
declare function createAmaSlopeClipTracker(erPeriod: number, lookbackBars: number, clipPercentile: number): {
|
|
75
102
|
push(value: number): number;
|
|
76
103
|
};
|
|
77
|
-
export { computeDynamicWeightSeries, computeAverageAmaSlopePct, echoLatchSeries, roundToN, computeAmaSlopeClipThreshold, createAmaSlopeClipTracker, percentileFromSorted, };
|
|
104
|
+
export { computeDynamicWeightSeries, computeAverageAmaSlopePct, computeHuberWindowSlopePct, echoLatchSeries, roundToN, computeAmaSlopeClipThreshold, createAmaSlopeClipTracker, percentileFromSorted, };
|
|
78
105
|
//# sourceMappingURL=dynamic_weight_series.d.ts.map
|
|
@@ -1,4 +1,5 @@
|
|
|
1
1
|
'use strict';
|
|
2
|
+
import { MARKET_ADAPTER } from '../../../modules/constants.js';
|
|
2
3
|
/**
|
|
3
4
|
* Dynamic weight per-bar series — canonical implementation shared by the live
|
|
4
5
|
* market adapter service, the research test harness, and the browser-embedded
|
|
@@ -9,12 +10,14 @@
|
|
|
9
10
|
* confirmation latch — the exact shape both the live `_computeDynamicWeights`
|
|
10
11
|
* and the interactive research chart render.
|
|
11
12
|
*
|
|
12
|
-
*
|
|
13
|
-
*
|
|
14
|
-
*
|
|
15
|
-
*
|
|
16
|
-
*
|
|
13
|
+
* The pure functions below stay self-contained so the chart generators can embed
|
|
14
|
+
* their exact source via fn.toString(). The one shared config they read — the
|
|
15
|
+
* canonical Huber-slope parameters — is centralised in
|
|
16
|
+
* MARKET_ADAPTER.DYNAMIC_WEIGHT_AMA_HUBER and aliased here as AMA_SLOPE_HUBER;
|
|
17
|
+
* generated HTML declares the same const from the same constant. Node callers
|
|
18
|
+
* keep their existing import path through strategies/ama_slope_model.ts.
|
|
17
19
|
*/
|
|
20
|
+
const AMA_SLOPE_HUBER = MARKET_ADAPTER.DYNAMIC_WEIGHT_AMA_HUBER;
|
|
18
21
|
function computeAverageAmaSlopePct(current, past, lookbackBars) {
|
|
19
22
|
const safeLookbackBars = Number.isFinite(lookbackBars) && lookbackBars > 0
|
|
20
23
|
? Math.ceil(lookbackBars)
|
|
@@ -24,6 +27,121 @@ function computeAverageAmaSlopePct(current, past, lookbackBars) {
|
|
|
24
27
|
}
|
|
25
28
|
return ((current - past) / past * 100) / safeLookbackBars;
|
|
26
29
|
}
|
|
30
|
+
/**
|
|
31
|
+
* Per-bar AMA trend in %/bar over `lookbackBars`, fitted as a Huber-robust
|
|
32
|
+
* linear regression of ln(AMA) against bar index (uniform weights, no kernel).
|
|
33
|
+
*
|
|
34
|
+
* This is the canonical slope used by the live adapter (dynamic weight series,
|
|
35
|
+
* AMA slope model, both clip paths), the grid-reset replay and the research
|
|
36
|
+
* charts, which embed this exact source via `embedFunctionSources`. One
|
|
37
|
+
* definition, one set of numbers — do not re-implement it per caller. Selected
|
|
38
|
+
* experimentally on a real 1h pool: it is the smoothest robust option measured
|
|
39
|
+
* (second-difference energy ~25x lower than the median's, max |dSlope|
|
|
40
|
+
* comparable to the two-point endpoint), because its influence function is
|
|
41
|
+
* continuous and bounded rather than an order statistic.
|
|
42
|
+
*
|
|
43
|
+
* The fit is local linear over `lookbackBars` intervals (bars+1 points, the same
|
|
44
|
+
* 20h span the endpoint uses), so a window-wide regime change tilts the line
|
|
45
|
+
* continuously instead of waiting for a majority, and a lone off-trend spike is
|
|
46
|
+
* bounded rather than given full endpoint weight. Output is the log-return per
|
|
47
|
+
* bar x 100. That differs from the arithmetic per-bar return by ~beta^2/2,
|
|
48
|
+
* which is negligible at the sub-0.1 %/bar magnitudes the defaults use (order
|
|
49
|
+
* 1e-9 at 0.1 %/bar) but grows quadratically with the reading — ln(1.06)*100 =
|
|
50
|
+
* 5.83, ~3% below a 6%/bar arithmetic rate. A pre-existing user override of
|
|
51
|
+
* maxSlopePct / neutralZonePct was tuned against the arithmetic reading, so a
|
|
52
|
+
* saturated override now clamps a hair tighter than before.
|
|
53
|
+
*
|
|
54
|
+
* Persistence note: `slopePct` is a different quantity from any pre-Huber
|
|
55
|
+
* reading (log-return regression vs the old median/endpoint). The first cycle
|
|
56
|
+
* after deploying compares a Huber reading against the still-persisted old
|
|
57
|
+
* baseline (botState.gridRangeScalingAmaSlope); the two magnitudes agree
|
|
58
|
+
* closely, so that delta sits below the reset gate on ~98% of bars (p50
|
|
59
|
+
* 0.00043, p90 0.00277 %/bar) — roughly one whitelisted bot in fifty costs one
|
|
60
|
+
* extra recenter, once. No version marker is persisted to suppress it.
|
|
61
|
+
*
|
|
62
|
+
* Parameters come from MARKET_ADAPTER.DYNAMIC_WEIGHT_AMA_HUBER (aliased as
|
|
63
|
+
* AMA_SLOPE_HUBER; injected into generated charts). `hub` is overridable only so
|
|
64
|
+
* tests can prove the values are threaded through — production never passes it.
|
|
65
|
+
*
|
|
66
|
+
* @param amaValues Full AMA series (index-addressable).
|
|
67
|
+
* @param index Bar to measure at (evaluated at the window edge).
|
|
68
|
+
* @param lookbackBars Window length in bars (fixed at 20 for every estimator).
|
|
69
|
+
* @param hub Parameter block; defaults to the centralized constant.
|
|
70
|
+
* @returns %/bar, or null when the window is unusable.
|
|
71
|
+
*/
|
|
72
|
+
function computeHuberWindowSlopePct(amaValues, index, lookbackBars, hub = AMA_SLOPE_HUBER) {
|
|
73
|
+
const bars = Number.isFinite(lookbackBars) && Number(lookbackBars) > 0
|
|
74
|
+
? Math.ceil(Number(lookbackBars))
|
|
75
|
+
: 0;
|
|
76
|
+
if (!Array.isArray(amaValues) || bars < 1)
|
|
77
|
+
return null;
|
|
78
|
+
if (!Number.isFinite(index) || index < bars || index >= amaValues.length)
|
|
79
|
+
return null;
|
|
80
|
+
// Local linear fit needs the full window at both ends; reject non-positive
|
|
81
|
+
// values anywhere in the window (Number(null) is 0) before fitting.
|
|
82
|
+
const y = [];
|
|
83
|
+
for (let k = index - bars; k <= index; k++) {
|
|
84
|
+
const v = Number(amaValues[k]);
|
|
85
|
+
if (!Number.isFinite(v) || v <= 0)
|
|
86
|
+
return null;
|
|
87
|
+
y.push(Math.log(v));
|
|
88
|
+
}
|
|
89
|
+
const n = y.length;
|
|
90
|
+
// Fill any missing field from the canonical constant. Production never passes
|
|
91
|
+
// `hub` (the default is the constant), so this only guards a partial override
|
|
92
|
+
// from silently skipping the IRLS loop or injecting NaN weights.
|
|
93
|
+
const hubC = Number.isFinite(hub?.C) ? hub.C : AMA_SLOPE_HUBER.C;
|
|
94
|
+
const hubIterations = Number.isFinite(hub?.ITERATIONS) ? hub.ITERATIONS : AMA_SLOPE_HUBER.ITERATIONS;
|
|
95
|
+
const hubScaleFloor = Number.isFinite(hub?.SCALE_FLOOR) ? hub.SCALE_FLOOR : AMA_SLOPE_HUBER.SCALE_FLOOR;
|
|
96
|
+
const hubZeroEpsilon = Number.isFinite(hub?.ZERO_EPSILON) ? hub.ZERO_EPSILON : AMA_SLOPE_HUBER.ZERO_EPSILON;
|
|
97
|
+
// Weighted least squares of y on the CENTERED index x_i = i - (n-1)/2. The
|
|
98
|
+
// x-centering keeps the normal equations well-conditioned, but the FULL
|
|
99
|
+
// two-variable solution is required: with non-uniform Huber weights the
|
|
100
|
+
// cross term Sx != 0, so b = Sxy/Sxx alone is not the minimiser (it would
|
|
101
|
+
// not decrease the objective). Kept inline (and therefore self-contained
|
|
102
|
+
// for chart embedding): { a, b } with b the log-slope.
|
|
103
|
+
const xMean = (n - 1) / 2;
|
|
104
|
+
const wls = (w) => {
|
|
105
|
+
let sw = 0, swx = 0, swy = 0, swxx = 0, swxy = 0;
|
|
106
|
+
for (let i = 0; i < n; i++) {
|
|
107
|
+
const xi = i - xMean;
|
|
108
|
+
sw += w[i];
|
|
109
|
+
swx += w[i] * xi;
|
|
110
|
+
swy += w[i] * y[i];
|
|
111
|
+
swxx += w[i] * xi * xi;
|
|
112
|
+
swxy += w[i] * xi * y[i];
|
|
113
|
+
}
|
|
114
|
+
const den = sw * swxx - swx * swx;
|
|
115
|
+
const b = den === 0 ? 0 : (sw * swxy - swx * swy) / den;
|
|
116
|
+
const a = sw === 0 ? 0 : (swy - b * swx) / sw;
|
|
117
|
+
return { a, b };
|
|
118
|
+
};
|
|
119
|
+
let fit = wls(new Array(n).fill(1)); // OLS initialisation
|
|
120
|
+
for (let iter = 0; iter < hubIterations; iter++) {
|
|
121
|
+
const resid = y.map((v, i) => v - (fit.a + fit.b * (i - xMean)));
|
|
122
|
+
const abs = resid.map(Math.abs).sort((p, q) => p - q);
|
|
123
|
+
const mid = abs.length >> 1;
|
|
124
|
+
const mad = abs.length % 2 === 1 ? abs[mid] : (abs[mid - 1] + abs[mid]) / 2;
|
|
125
|
+
// Floor the robust scale. On piecewise-perfect data (a pure ramp, a
|
|
126
|
+
// constant series) the MAD can collapse to ~0, which makes the Huber
|
|
127
|
+
// weights degenerate and the weighted fit unstable; the floor is far
|
|
128
|
+
// below any real per-bar signal (the reset gate is ~7e-5 here).
|
|
129
|
+
const s = Math.max(1.4826 * mad, hubScaleFloor);
|
|
130
|
+
const w = resid.map((r) => Math.min(1, (hubC * s) / Math.max(Math.abs(r), 1e-12)));
|
|
131
|
+
const next = wls(w);
|
|
132
|
+
const moved = Math.abs(next.b - fit.b);
|
|
133
|
+
fit = next;
|
|
134
|
+
if (moved < 1e-12)
|
|
135
|
+
break;
|
|
136
|
+
}
|
|
137
|
+
const slope = fit.b * 100;
|
|
138
|
+
// A constant window has zero true slope, but centred WLS leaves ~1e-14 of
|
|
139
|
+
// rounding, which would flip a zero neutral zone to a trend (UP/DOWN).
|
|
140
|
+
// Snap anything below ZERO_EPSILON (far under the reset gate).
|
|
141
|
+
if (Number.isFinite(slope) && Math.abs(slope) < hubZeroEpsilon)
|
|
142
|
+
return 0;
|
|
143
|
+
return Number.isFinite(slope) ? slope : null;
|
|
144
|
+
}
|
|
27
145
|
function echoLatchSeries(appliedSeries, preGainSeries, confirmBars) {
|
|
28
146
|
const n = Array.isArray(appliedSeries) ? appliedSeries.length : 0;
|
|
29
147
|
const echoedAppliedSeries = new Array(n).fill(0);
|
|
@@ -86,9 +204,7 @@ function computeDynamicWeightSeries(inputs) {
|
|
|
86
204
|
for (let i = 0; i < n; i++) {
|
|
87
205
|
if (i < amaReadyBar)
|
|
88
206
|
continue;
|
|
89
|
-
const
|
|
90
|
-
const past = amaValues[i - lookbackBars];
|
|
91
|
-
const sp = computeAverageAmaSlopePct(last, past, lookbackBars);
|
|
207
|
+
const sp = computeHuberWindowSlopePct(amaValues, i, lookbackBars);
|
|
92
208
|
if (sp == null)
|
|
93
209
|
continue;
|
|
94
210
|
const csp = Math.max(-amaClipThreshold, Math.min(amaClipThreshold, sp));
|
|
@@ -182,11 +298,7 @@ function computeAmaSlopeClipThreshold(amaValues, erPeriod, lookbackBars, clipPer
|
|
|
182
298
|
return Infinity;
|
|
183
299
|
const slopes = [];
|
|
184
300
|
for (let i = readyBars; i < amaValues.length; i++) {
|
|
185
|
-
const
|
|
186
|
-
const past = amaValues[i - lookbackBars];
|
|
187
|
-
if (!Number.isFinite(last) || !Number.isFinite(past))
|
|
188
|
-
continue;
|
|
189
|
-
const s = computeAverageAmaSlopePct(last, past, lookbackBars);
|
|
301
|
+
const s = computeHuberWindowSlopePct(amaValues, i, lookbackBars);
|
|
190
302
|
if (Number.isFinite(s))
|
|
191
303
|
slopes.push(Math.abs(s));
|
|
192
304
|
}
|
|
@@ -223,30 +335,26 @@ function createAmaSlopeClipTracker(erPeriod, lookbackBars, clipPercentile) {
|
|
|
223
335
|
return Infinity;
|
|
224
336
|
const i = buffer.length - 1;
|
|
225
337
|
if (i >= readyBars) {
|
|
226
|
-
const
|
|
227
|
-
|
|
228
|
-
|
|
229
|
-
|
|
230
|
-
|
|
231
|
-
|
|
232
|
-
|
|
233
|
-
|
|
234
|
-
|
|
235
|
-
|
|
236
|
-
|
|
237
|
-
lo = mid + 1;
|
|
238
|
-
else
|
|
239
|
-
hi = mid;
|
|
240
|
-
}
|
|
241
|
-
sorted.splice(lo, 0, v);
|
|
338
|
+
const s = computeHuberWindowSlopePct(buffer, i, lookbackBars);
|
|
339
|
+
if (Number.isFinite(s)) {
|
|
340
|
+
const v = Math.abs(s);
|
|
341
|
+
let lo = 0;
|
|
342
|
+
let hi = sorted.length;
|
|
343
|
+
while (lo < hi) {
|
|
344
|
+
const mid = (lo + hi) >> 1;
|
|
345
|
+
if (sorted[mid] < v)
|
|
346
|
+
lo = mid + 1;
|
|
347
|
+
else
|
|
348
|
+
hi = mid;
|
|
242
349
|
}
|
|
350
|
+
sorted.splice(lo, 0, v);
|
|
243
351
|
}
|
|
244
352
|
}
|
|
245
353
|
return percentileFromSorted(sorted, clipPercentile);
|
|
246
354
|
},
|
|
247
355
|
};
|
|
248
356
|
}
|
|
249
|
-
export { computeDynamicWeightSeries, computeAverageAmaSlopePct, echoLatchSeries, roundToN, computeAmaSlopeClipThreshold, createAmaSlopeClipTracker,
|
|
357
|
+
export { computeDynamicWeightSeries, computeAverageAmaSlopePct, computeHuberWindowSlopePct, echoLatchSeries, roundToN, computeAmaSlopeClipThreshold, createAmaSlopeClipTracker,
|
|
250
358
|
// Exported so chart generators can embed the clip tracker's exact
|
|
251
359
|
// dependency set via fn.toString() (see embedFunctionSources): the tracker
|
|
252
360
|
// itself calls this, and embedding one without the other breaks the page.
|
|
@@ -1,3 +1,56 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* How many bars of history the analyzers' rolling state can depend on.
|
|
3
|
+
*
|
|
4
|
+
* Taken from the analyzer INSTANCES (each exposes `bufferBars`), never from a
|
|
5
|
+
* second copy of their constructor defaults: a mirrored formula silently
|
|
6
|
+
* under-estimates whenever a default or a buffer formula changes. Being too
|
|
7
|
+
* large only costs a missed resume; being too small would let the resume carry
|
|
8
|
+
* `cached.series` entries that were computed from bars the incoming window no
|
|
9
|
+
* longer contains (the analyzers' final state is unaffected either way — see
|
|
10
|
+
* _locateResume). An analyzer that does not report a usable size fails closed
|
|
11
|
+
* (MAX_SAFE_INTEGER), which disables resuming for that cache entry.
|
|
12
|
+
*/
|
|
13
|
+
declare function _analyzerBufferSize(hurst: any, pe: any): number;
|
|
14
|
+
/**
|
|
15
|
+
* Locate how `closes` advances the cached window, or null when they are not
|
|
16
|
+
* related that way.
|
|
17
|
+
*
|
|
18
|
+
* Returns `{ k, shared }` where `closes[0..shared)` is exactly
|
|
19
|
+
* `cached[k..cached.length)` — i.e. the incoming window dropped k leading bars
|
|
20
|
+
* and appended `closes.length - shared` new ones. `k = 0, shared =
|
|
21
|
+
* cached.length` is the plain "one or more bars were added" case.
|
|
22
|
+
*
|
|
23
|
+
* The shift is pinned by matching the cached window's newest bar inside the
|
|
24
|
+
* incoming window, then the ENTIRE shared region is verified, so a coincidental
|
|
25
|
+
* price match cannot pass. NaN-aware, like the pre-cache implementation.
|
|
26
|
+
*
|
|
27
|
+
* When the cached newest bar occurs at more than one position and more than one
|
|
28
|
+
* candidate alignment verifies, the window is ambiguous and the function
|
|
29
|
+
* declines to resume. This is hygiene, not a safety requirement: any verified
|
|
30
|
+
* alignment with `shared >= minShared` is exact by construction, because that
|
|
31
|
+
* requirement guarantees the resumed stream's last `bufferBars` values are the
|
|
32
|
+
* same values the incoming stream ends with — the analyzers are rolling, so
|
|
33
|
+
* their final state (and every series entry from that point on) is identical
|
|
34
|
+
* whichever alignment is chosen. Declining only avoids anchoring the
|
|
35
|
+
* `cached.series` carry-over — whose early entries rest on bars the window may
|
|
36
|
+
* no longer contain — to a pattern match we did not intend. It can only arise
|
|
37
|
+
* on degenerate periodic windows, and a cold recompute there is cheap and
|
|
38
|
+
* honest.
|
|
39
|
+
*/
|
|
40
|
+
declare function _locateResume(cached: number[], closes: number[], minShared: number): {
|
|
41
|
+
k: number;
|
|
42
|
+
shared: number;
|
|
43
|
+
} | null;
|
|
44
|
+
/**
|
|
45
|
+
* Drop all memoized analyzer state.
|
|
46
|
+
*
|
|
47
|
+
* A test seam today, not a runtime path: the cycle resolves its parameters once
|
|
48
|
+
* per run, so there is no in-process config reload to invalidate state for, and
|
|
49
|
+
* a parameter change is already detected by `regimeParamsKey` (it forces a full
|
|
50
|
+
* recompute). Production never calls this — it exists so a test can assert a
|
|
51
|
+
* cold run against a warm cache without leaking entries between cases.
|
|
52
|
+
*/
|
|
53
|
+
declare function _resetRegimeCache(): void;
|
|
1
54
|
/**
|
|
2
55
|
* Compute the Hurst+PE regime multiplier from a price series.
|
|
3
56
|
*
|
|
@@ -5,9 +58,13 @@
|
|
|
5
58
|
* canonical pure implementation in strategies/regime_interp.ts (shared with the
|
|
6
59
|
* browser-embedded chart scripts).
|
|
7
60
|
*
|
|
8
|
-
* Feeds
|
|
61
|
+
* Feeds prices through HurstAnalyzer and PermutationEntropyAnalyzer,
|
|
9
62
|
* then bilinear-interpolates the regime table to produce a multiplier that
|
|
10
|
-
* gates the AMA slope offset in production weight computation.
|
|
63
|
+
* gates the AMA slope offset in production weight computation. When
|
|
64
|
+
* `opts.cacheKey` is set, a window that ADVANCES the memoized one (k leading
|
|
65
|
+
* bars dropped, m appended) resumes from the cached analyzer state and feeds
|
|
66
|
+
* only the appended bars; anything else recomputes from scratch. See the cache
|
|
67
|
+
* notes above.
|
|
11
68
|
*
|
|
12
69
|
* @param {number[]} closes - Full close price series (same array used for AMA)
|
|
13
70
|
* @param {Object} [opts]
|
|
@@ -15,6 +72,7 @@
|
|
|
15
72
|
* @param {Array} [opts.regimeTable] - Custom 3x3 regime multiplier table
|
|
16
73
|
* @param {number} [opts.hurstZoneBand] - Override Hurst neutral-zone width
|
|
17
74
|
* @param {Array} [opts.peNodes] - Override entropy thresholds
|
|
75
|
+
* @param {string} [opts.cacheKey] - Stable per-market key enabling cross-cycle reuse
|
|
18
76
|
* @param {Object} [opts.hurstConfig] - Override for HurstAnalyzer config
|
|
19
77
|
* @param {Object} [opts.peConfig] - Override for PermutationEntropyAnalyzer config
|
|
20
78
|
* @returns {{ multiplier: number, hurst: number|null, pe: number|null,
|
|
@@ -38,5 +96,5 @@ declare function computeRegimeMultiplier(closes: any, opts?: any): {
|
|
|
38
96
|
isReady: boolean;
|
|
39
97
|
series: number[];
|
|
40
98
|
};
|
|
41
|
-
export { computeRegimeMultiplier };
|
|
99
|
+
export { computeRegimeMultiplier, _resetRegimeCache, _locateResume, _analyzerBufferSize };
|
|
42
100
|
//# sourceMappingURL=regime_gate.d.ts.map
|