dexbot 1.6.9 → 1.6.10

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (47) hide show
  1. package/CHANGELOG.md +18 -0
  2. package/analysis/README.md +1 -1
  3. package/analysis/tradingview/README.md +14 -9
  4. package/claw/modules/chain_queries.ts +9 -4
  5. package/claw/modules/claw_bridge.ts +9 -9
  6. package/claw/package.json +1 -1
  7. package/claw/runtimes/openclaw-plugin/openclaw.plugin.json +1 -1
  8. package/claw/runtimes/openclaw-plugin/package.json +1 -1
  9. package/dist/analysis/ama_fitting/optimizer_high_resolution.js +2 -1
  10. package/dist/analysis/bot_fitting/backtest_ama_sweep.js +2 -2
  11. package/dist/analysis/bot_fitting/backtest_bot_fitting.js +4 -4
  12. package/dist/analysis/bot_key_utils.js +14 -4
  13. package/dist/analysis/tradingview/analyze_tradingview.d.ts +0 -3
  14. package/dist/analysis/tradingview/analyze_tradingview.js +3 -14
  15. package/dist/analysis/tradingview/grid_reset_sim.d.ts +11 -1
  16. package/dist/analysis/tradingview/grid_reset_sim.js +22 -9
  17. package/dist/analysis/tradingview/tradingview_uplot_chart_generator.js +178 -32
  18. package/dist/analysis/trend_detection/dynamic_weight_chart_generator.js +8 -3
  19. package/dist/dexbot.js +13 -8
  20. package/dist/market_adapter/core/strategies/ama_slope_model.d.ts +2 -2
  21. package/dist/market_adapter/core/strategies/ama_slope_model.js +12 -10
  22. package/dist/market_adapter/core/strategies/dynamic_weight_series.d.ts +41 -14
  23. package/dist/market_adapter/core/strategies/dynamic_weight_series.js +138 -30
  24. package/dist/market_adapter/lp_chart_strategy_loader.js +2 -1
  25. package/dist/market_adapter/utils/chain.d.ts +1 -1
  26. package/dist/market_adapter/utils/chain.js +8 -6
  27. package/dist/modules/account_bots.js +5 -4
  28. package/dist/modules/bitshares-native/resolvers.js +5 -0
  29. package/dist/modules/bot_settings.js +13 -1
  30. package/dist/modules/chain_orders.js +2 -1
  31. package/dist/modules/constants.d.ts +6 -0
  32. package/dist/modules/constants.js +23 -1
  33. package/dist/modules/credential_policy.js +4 -1
  34. package/dist/modules/credit_runtime.js +5 -1
  35. package/dist/modules/order/utils/system.js +11 -1
  36. package/dist/modules/utils/asset_symbols.d.ts +59 -0
  37. package/dist/modules/utils/asset_symbols.js +128 -0
  38. package/dist/scripts/analyze-credit.js +10 -7
  39. package/dist/scripts/chart_command.js +12 -4
  40. package/dist/scripts/verify-browser-bundle.js +8 -0
  41. package/docs/DEXBOT_COMPARISON.md +3 -3
  42. package/docs/EVOLUTION.md +9 -8
  43. package/docs/FUND_MOVEMENT_AND_ACCOUNTING.md +1 -1
  44. package/docs/GRID_RECALCULATION.md +22 -3
  45. package/docs/README.md +1 -1
  46. package/market_adapter/README.md +2 -2
  47. package/package.json +1 -1
@@ -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
- * This module is intentionally fully self-contained (no imports): the chart
13
- * generator embeds its exact source into generated HTML via fn.toString(), so
14
- * every consumer runs one logic path. The pure helper computeAverageAmaSlopePct
15
- * is re-exported by strategies/ama_slope_model.ts so Node callers keep their
16
- * existing import path.
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 last = amaValues[i];
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 last = amaValues[i];
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 last = buffer[i];
227
- const past = buffer[i - lookbackBars];
228
- if (Number.isFinite(last) && Number.isFinite(past)) {
229
- const s = computeAverageAmaSlopePct(last, past, lookbackBars);
230
- if (Number.isFinite(s)) {
231
- const v = Math.abs(s);
232
- let lo = 0;
233
- let hi = sorted.length;
234
- while (lo < hi) {
235
- const mid = (lo + hi) >> 1;
236
- if (sorted[mid] < v)
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,7 +1,8 @@
1
1
  'use strict';
2
2
  import { path } from '../modules/path_api.js';
3
3
  import { getStorage } from '../modules/storage/index.js';
4
- import { normalizeAssetSymbol, isExactPair, isSamePair } from './utils/chain.js';
4
+ import { isExactPair, isSamePair } from './utils/chain.js';
5
+ import { normalizeAssetSymbol } from '../modules/utils/asset_symbols.js';
5
6
  import { toIntervalLabel } from './interval_utils.js';
6
7
  import { PATHS } from '../modules/paths.js';
7
8
  const storage = getStorage();
@@ -1,3 +1,4 @@
1
+ import { normalizeAssetSymbol } from '../../modules/utils/asset_symbols.js';
1
2
  declare function getBitsharesClient(): any;
2
3
  declare function setBitsharesClientForTests(client: any): void;
3
4
  declare function resolveAsset(symbol: any, bitsharesClient?: any): Promise<{
@@ -6,7 +7,6 @@ declare function resolveAsset(symbol: any, bitsharesClient?: any): Promise<{
6
7
  symbol: string;
7
8
  }>;
8
9
  declare function findPoolByAssets(assetAId: any, assetBId: any, options?: any): Promise<any>;
9
- declare function normalizeAssetSymbol(value: any): string;
10
10
  declare function isExactPair(a: any, b: any, targetA: any, targetB: any): boolean;
11
11
  declare function isSamePair(a: any, b: any, targetA: any, targetB: any): boolean;
12
12
  declare function isExactPairIds(aId: any, bId: any, targetAId: any, targetBId: any): boolean;
@@ -2,6 +2,7 @@
2
2
  import { createRequire } from 'node:module';
3
3
  const require = createRequire(import.meta.url);
4
4
  import { API_LIMITS } from '../../modules/constants.js';
5
+ import { normalizeAssetSymbol } from '../../modules/utils/asset_symbols.js';
5
6
  let _bitsharesClient = null;
6
7
  function getBitsharesClient() {
7
8
  // lazy require to avoid circular dependencies at module load time
@@ -17,13 +18,17 @@ async function resolveAsset(symbol, bitsharesClient = null) {
17
18
  if (!symbol || typeof symbol !== 'string') {
18
19
  throw new Error(`Cannot resolve asset: invalid or missing symbol "${symbol}"`);
19
20
  }
21
+ // BitShares symbols are canonical UPPERCASE; nodes answer lowercase lookups
22
+ // silently, so normalize here and hand the canonical symbol downstream
23
+ // (cache keys, Kibana terms, chart labels) instead of the raw input.
24
+ const canonical = normalizeAssetSymbol(symbol);
20
25
  const client = bitsharesClient || getBitsharesClient();
21
- const results = await client.BitShares.db.lookup_asset_symbols([symbol]);
26
+ const results = await client.BitShares.db.lookup_asset_symbols([canonical]);
22
27
  const asset = results?.[0];
23
28
  if (!asset?.id || typeof asset.precision !== 'number') {
24
- throw new Error(`Cannot resolve asset "${symbol}": lookup failed`);
29
+ throw new Error(`Cannot resolve asset "${canonical}": lookup failed`);
25
30
  }
26
- return { id: asset.id, precision: asset.precision, symbol };
31
+ return { id: asset.id, precision: asset.precision, symbol: String(asset.symbol || canonical) };
27
32
  }
28
33
  async function findPoolByAssets(assetAId, assetBId, options = {}) {
29
34
  const client = options.bitsharesClient || getBitsharesClient();
@@ -107,9 +112,6 @@ async function findPoolByAssets(assetAId, assetBId, options = {}) {
107
112
  }
108
113
  throw new Error(`No liquidity pool found for ${assetAId}/${assetBId}`);
109
114
  }
110
- function normalizeAssetSymbol(value) {
111
- return String(value || '').trim().toUpperCase();
112
- }
113
115
  function isExactPair(a, b, targetA, targetB) {
114
116
  const na = normalizeAssetSymbol(a);
115
117
  const nb = normalizeAssetSymbol(b);
@@ -99,6 +99,7 @@ import { getWhitelistFlags, setWhitelistFlags, renameWhitelistEntry, removeWhite
99
99
  import { BOT_LIVE_CONFIG_KEYS } from './runtime_settings.js';
100
100
  import { mergeSettings } from './settings_merge.js';
101
101
  import { getErrorMessage } from './utils/errors.js';
102
+ import { normalizeAssetSymbol } from './utils/asset_symbols.js';
102
103
  import { roundToDecimals, parseRelativeMultiplier } from './order/utils/math.js';
103
104
  import { CLI_COLORS } from './cli_colors.js';
104
105
  import { displayWidth, padDisplay } from './utils/text_width.js';
@@ -360,7 +361,7 @@ async function askLogLevel(promptText, defaultValue) {
360
361
  */
361
362
  async function askAsset(promptText, defaultValue) {
362
363
  while (true) {
363
- const displayDefault = defaultValue ? String(defaultValue).toUpperCase() : undefined;
364
+ const displayDefault = defaultValue ? normalizeAssetSymbol(defaultValue) : undefined;
364
365
  const suffix = displayDefault !== undefined && displayDefault !== null ? ` [${displayDefault}]` : '';
365
366
  const answer = await readInput(`${promptText}${suffix}: `);
366
367
  if (answer === '\x1b')
@@ -371,7 +372,7 @@ async function askAsset(promptText, defaultValue) {
371
372
  console.log('Asset name is required.');
372
373
  continue;
373
374
  }
374
- return answer.toUpperCase().trim();
375
+ return normalizeAssetSymbol(answer);
375
376
  }
376
377
  }
377
378
  /**
@@ -383,7 +384,7 @@ async function askAsset(promptText, defaultValue) {
383
384
  */
384
385
  async function askAssetB(promptText, defaultValue, assetA) {
385
386
  while (true) {
386
- const displayDefault = defaultValue ? String(defaultValue).toUpperCase() : undefined;
387
+ const displayDefault = defaultValue ? normalizeAssetSymbol(defaultValue) : undefined;
387
388
  const suffix = displayDefault !== undefined && displayDefault !== null ? ` [${displayDefault}]` : '';
388
389
  const answer = await readInput(`${promptText}${suffix}: `);
389
390
  if (answer === '\x1b')
@@ -394,7 +395,7 @@ async function askAssetB(promptText, defaultValue, assetA) {
394
395
  console.log('Asset name is required.');
395
396
  continue;
396
397
  }
397
- const assetB = answer.toUpperCase().trim();
398
+ const assetB = normalizeAssetSymbol(answer);
398
399
  // Validate that Asset B is different from Asset A
399
400
  if (assetB === assetA) {
400
401
  console.log(`Invalid: Asset B cannot be the same as Asset A (${assetA})`);
@@ -2,6 +2,7 @@
2
2
  import { NATIVE_CLIENT } from '../constants.js';
3
3
  import { LRUCache } from './lru_cache.js';
4
4
  import { getErrorMessage } from '../utils/errors.js';
5
+ import { normalizeAssetRef } from '../utils/asset_symbols.js';
5
6
  const { RESOLVERS } = NATIVE_CLIENT;
6
7
  const ASSET_TTL_MS = RESOLVERS.ASSET_TTL_MS;
7
8
  const ACCOUNT_TTL_MS = RESOLVERS.ACCOUNT_TTL_MS;
@@ -14,6 +15,10 @@ function createResolvers(chainClient) {
14
15
  async function resolveAsset(idOrSymbol) {
15
16
  if (!idOrSymbol)
16
17
  throw new Error('asset id or symbol required');
18
+ // Canonicalize before the cache key and the chain call: a lowercase
19
+ // symbol would otherwise occupy a second cache slot and be echoed back
20
+ // lowercase to every caller.
21
+ idOrSymbol = normalizeAssetRef(idOrSymbol);
17
22
  const cacheKey = `asset:${idOrSymbol}`;
18
23
  const cached = assetCache.get(cacheKey);
19
24
  if (cached)
@@ -7,6 +7,7 @@ import { isSameBotName } from './utils/sanitize_key.js';
7
7
  import { isPositiveNumber, isPositiveNumberOrPercent, toDecimal } from './order/utils/math.js';
8
8
  import { resolveMinCollateralIncreaseThreshold } from './cr_planner.js';
9
9
  import { getErrorMessage } from './utils/errors.js';
10
+ import { canonicalizeBotAssetSymbols } from './utils/asset_symbols.js';
10
11
  const storage = getStorage();
11
12
  const { writeJSON } = storage;
12
13
  function loadSettingsFile(filePath, { silent = false, exitOnError = true } = {}) {
@@ -52,7 +53,18 @@ function normalizeBotEntry(entry, index = 0) {
52
53
  // active default + raw passthrough live in modules/bot_defaults.ts
53
54
  // (shared with the claw copy — one semantics for both).
54
55
  const normalized = seedBotEntry(entry);
55
- return { ...normalized, botIndex: index, botKey: createBotKey(normalized, index) };
56
+ // Asset symbols are canonical UPPERCASE on BitShares. A hand-edited
57
+ // lowercase "assetA": "tokena" is accepted by the chain without error but
58
+ // breaks every strict symbol comparison downstream (e.g. the core-asset
59
+ // side check that reads `assetA === 'CORE'`,
60
+ // getBtsSide, fee/pool cache keys), so canonicalize at this single read
61
+ // funnel — which key names hold a symbol is defined once, in
62
+ // modules/utils/asset_symbols.canonicalizeBotAssetSymbols, shared with
63
+ // analysis/bot_key_utils.loadBotMeta. botKey is unaffected: createBotKey
64
+ // runs the pair through sanitizeKey, which is case-insensitive.
65
+ const out = canonicalizeBotAssetSymbols({ ...normalized, botIndex: index });
66
+ out.botKey = createBotKey(out, index);
67
+ return out;
56
68
  }
57
69
  function normalizeBotEntries(rawEntries) {
58
70
  return rawEntries.map((entry, index) => normalizeBotEntry(entry, index));
@@ -113,6 +113,7 @@ import { BroadcastUncertainError } from './dexbot_credential_client.js';
113
113
  import { classifyBroadcastFailure } from './broadcast_failure.js';
114
114
  import Logger from './order/logger.js';
115
115
  import { getErrorMessage } from './utils/errors.js';
116
+ import { normalizeAssetRef } from './utils/asset_symbols.js';
116
117
  function getNodeManager() { return require('./bitshares_client').getNodeManager(); }
117
118
  const { toFiniteNumber } = Format;
118
119
  const chainOrdersLogger = new Logger('ChainOrders');
@@ -1404,7 +1405,7 @@ async function getOnChainAssetBalances(accountRef, assets, options = {}) {
1404
1405
  try {
1405
1406
  if (!/^1\.3\./.test(String(a))) {
1406
1407
  // symbol -> asset
1407
- const res = await BitShares.db.lookup_asset_symbols([String(a)]).catch(() => null);
1408
+ const res = await BitShares.db.lookup_asset_symbols([normalizeAssetRef(a)]).catch(() => null);
1408
1409
  if (res && res[0] && res[0].id)
1409
1410
  aid = res[0].id;
1410
1411
  }
@@ -404,6 +404,12 @@ declare let MARKET_ADAPTER: {
404
404
  DYNAMIC_WEIGHT_AMA_MAX_SLOPE_PCT: number;
405
405
  DYNAMIC_WEIGHT_KALMAN_MAX_SLOPE_PCT: number;
406
406
  DYNAMIC_WEIGHT_AMA_NEUTRAL_ZONE_PCT: number;
407
+ DYNAMIC_WEIGHT_AMA_HUBER: {
408
+ C: number;
409
+ ITERATIONS: number;
410
+ SCALE_FLOOR: number;
411
+ ZERO_EPSILON: number;
412
+ };
407
413
  DYNAMIC_WEIGHT_ALPHA: number;
408
414
  DYNAMIC_WEIGHT_DW: number;
409
415
  DYNAMIC_WEIGHT_GAIN: number;
@@ -1083,8 +1083,12 @@ let MARKET_ADAPTER = {
1083
1083
  // DYNAMIC_WEIGHT_AMA_LOOKBACK_BARS: Lookback window for measuring AMA trend.
1084
1084
  // Lower values react faster to recent price changes.
1085
1085
  // Higher values smooth the signal and require a more sustained move.
1086
+ // 20 (was 9): measured on the real 1h pools, the slope's bar-to-bar wobble
1087
+ // drops ~34% and slope-driven grid resets ~19%, while the band tilt is
1088
+ // unchanged; the cost is freshness — the window centre sits ~10 bars back
1089
+ // instead of ~4.5, so reversals are acted on later.
1086
1090
  // nob: lb (Lookback Bars)
1087
- DYNAMIC_WEIGHT_AMA_LOOKBACK_BARS: 9,
1091
+ DYNAMIC_WEIGHT_AMA_LOOKBACK_BARS: 20,
1088
1092
  // DYNAMIC_WEIGHT_AMA_MAX_SLOPE_PCT: Average per-bar trend size that counts as "full strength" for AMA.
1089
1093
  // Lower values make the AMA channel reach maximum influence more easily.
1090
1094
  // Higher values require a stronger price move before AMA reaches full effect.
@@ -1102,6 +1106,24 @@ let MARKET_ADAPTER = {
1102
1106
  // Lower values make the AMA channel react to smaller moves.
1103
1107
  // nob: nz% (Neutral Zone %)
1104
1108
  DYNAMIC_WEIGHT_AMA_NEUTRAL_ZONE_PCT: 0,
1109
+ // DYNAMIC_WEIGHT_AMA_HUBER: Single source of truth for the canonical AMA-slope
1110
+ // estimator (computeHuberWindowSlopePct in strategy/dynamic_weight_series.ts).
1111
+ // Every consumer — live market adapter, grid-reset replay, bot-fitting
1112
+ // backtests, both browser-embedded research charts — reads these values:
1113
+ // Node callers via the module import, generated HTML via an injected
1114
+ // `const AMA_SLOPE_HUBER = {...}` literal. Change a value here and every
1115
+ // slope computation follows; do not re-declare them per caller.
1116
+ // C Huber tuning constant (1.345 ~= 95% Gaussian efficiency)
1117
+ // ITERATIONS IRLS passes (converges in a few at the 20-bar window)
1118
+ // SCALE_FLOOR Floor for the 1.4826*MAD robust scale, in log units
1119
+ // ZERO_EPSILON Slopes below this (%/bar) snap to exactly 0
1120
+ // nob: n/a (algorithm-internal)
1121
+ DYNAMIC_WEIGHT_AMA_HUBER: {
1122
+ C: 1.345,
1123
+ ITERATIONS: 5,
1124
+ SCALE_FLOOR: 1e-6,
1125
+ ZERO_EPSILON: 1e-9,
1126
+ },
1105
1127
  // DYNAMIC_WEIGHT_ALPHA: Blend between AMA trend and Kalman trend.
1106
1128
  // 0 = pure Kalman, 1 = pure AMA.
1107
1129
  // Higher values trust AMA more, lower values trust Kalman more.
@@ -22,6 +22,7 @@ import { getStorage } from './storage/index.js';
22
22
  import { runtime } from './runtime.js';
23
23
  import { LRUCache } from './bitshares-native/lru_cache.js';
24
24
  import { getErrorMessage } from './utils/errors.js';
25
+ import { normalizeAssetRef } from './utils/asset_symbols.js';
25
26
  const { RESOLVERS } = NATIVE_CLIENT;
26
27
  const storage = getStorage();
27
28
  const { readJSON } = storage;
@@ -66,7 +67,9 @@ function setExternalAssetResolver(resolver) {
66
67
  async function resolveAssetRefToId(assetRef) {
67
68
  if (!assetRef || typeof assetRef !== 'string')
68
69
  return null;
69
- const cacheKey = String(assetRef);
70
+ // Canonical key + canonical ref for the external/native resolver, so the
71
+ // daemon and this process agree on one entry per asset.
72
+ const cacheKey = normalizeAssetRef(assetRef);
70
73
  const cached = assetRefResolutionCache.get(cacheKey);
71
74
  if (cached !== undefined)
72
75
  return cached;
@@ -12,6 +12,7 @@ import { createBotKey } from './account_orders.js';
12
12
  import * as fundRegistry from './fund_registry.js';
13
13
  import { writeJsonFileAtomic } from './bots_file_lock.js';
14
14
  import { resolveAssetByRef, nowIso } from './order/utils/system.js';
15
+ import { normalizeAssetRef } from './utils/asset_symbols.js';
15
16
  import { FEE_PARAMETERS, DEFAULT_TARGET_CR, TIMING, NATIVE_CLIENT } from './constants.js';
16
17
  import { PATHS } from './paths.js';
17
18
  import { deriveLiquidityPoolTokenValue, derivePriceWithBridges, ensureDir as ensureDirSync, } from './order/utils/system.js';
@@ -405,7 +406,10 @@ class CreditRuntime {
405
406
  async _resolveAsset(assetRef) {
406
407
  if (!assetRef)
407
408
  return null;
408
- const cacheKey = String(assetRef);
409
+ // Canonical key: debtPolicy.lending refs and the --asset/--collateral
410
+ // overrides of scripts/test-credit-renewal.ts would otherwise each get
411
+ // their own cache slot for the same asset.
412
+ const cacheKey = normalizeAssetRef(assetRef);
409
413
  if (this._assetCache.has(cacheKey)) {
410
414
  return this._assetCache.get(cacheKey);
411
415
  }
@@ -58,6 +58,7 @@ import * as OrderUtils from './order.js';
58
58
  import Logger from '../../order/logger.js';
59
59
  import { runtime } from '../../runtime.js';
60
60
  import { getErrorMessage } from '../../utils/errors.js';
61
+ import { normalizeAssetRef } from '../../utils/asset_symbols.js';
61
62
  import { withTimeout } from './timeout.js';
62
63
  const { ensureDir, readJSON } = storage;
63
64
  const systemLogger = new Logger('System');
@@ -117,6 +118,13 @@ const poolIdCache = new Map();
117
118
  export const lookupAsset = async (BitShares, s) => {
118
119
  if (!BitShares)
119
120
  return null;
121
+ // BitShares symbols are canonical UPPERCASE and object ids ("1.3.x") are
122
+ // passed through; normalizing here means every caller (price derivation,
123
+ // fee cache, pool lookup) hits the chain with the canonical spelling.
124
+ // Only real symbols are rewritten: a blank/non-string ref must keep its
125
+ // original spelling in the CRITICAL error below.
126
+ if (typeof s === 'string' && s.trim())
127
+ s = normalizeAssetRef(s);
120
128
  let cached = null;
121
129
  if (BitShares?.assets) {
122
130
  try {
@@ -161,7 +169,9 @@ export const lookupAsset = async (BitShares, s) => {
161
169
  export const resolveAssetByRef = async (BitShares, ref) => {
162
170
  if (!BitShares?.db)
163
171
  return null;
164
- const cacheKey = String(ref);
172
+ // Same rule as lookupAsset: canonicalize real symbols, leave anything else
173
+ // (object ids pass through, junk keeps its original spelling) untouched.
174
+ const cacheKey = typeof ref === 'string' ? normalizeAssetRef(ref) : String(ref);
165
175
  const method = /^1\.3\.\d+$/.test(cacheKey) ? 'get_assets' : 'lookup_asset_symbols';
166
176
  const camelMethod = method.replace(/_([a-z])/g, (_, c) => c.toUpperCase());
167
177
  try {
@@ -0,0 +1,59 @@
1
+ /**
2
+ * Central asset-symbol / asset-ref normalization.
3
+ *
4
+ * BitShares stores asset symbols canonically UPPERCASE, so the assetA and
5
+ * assetB symbols of a bot pair are always UPPERCASE on chain.
6
+ * Nodes accept a lowercase lookup and answer it without error, so a lowercase
7
+ * symbol never fails — it just travels on as lowercase into everything built
8
+ * from it: the `symbol` field we attach to resolved assets, chart titles,
9
+ * cache-file names, Kibana query terms, and strict in-process comparisons such
10
+ * as the core-asset side check `assetA === 'CORE'`. That is a
11
+ * silent-wrong-answer class of bug, not a loud
12
+ * one, so the conversion is done ONCE here and applied at every boundary that
13
+ * accepts a pair from a human (CLI prompts, `dexbot tv`/`dw` targets) or hands
14
+ * a symbol to the chain (`lookup_asset_symbols`).
15
+ *
16
+ * Rules:
17
+ * - Asset OBJECT IDs ("1.3.x") are not symbols: they are returned verbatim so
18
+ * ref-routing callers (get_assets vs lookup_asset_symbols) keep working.
19
+ * - Everything else is trimmed and uppercased.
20
+ * - Non-strings / empty input normalize to '' (never "undefined"/"null").
21
+ *
22
+ * Browser-safe: no node built-ins.
23
+ */
24
+ /** True when the value is a BitShares asset object id, not a symbol. */
25
+ export declare function isAssetObjectId(value: unknown): boolean;
26
+ /**
27
+ * Canonicalize an asset symbol (or pass an asset object id through untouched).
28
+ * This is the single conversion used before a symbol reaches the blockchain
29
+ * and before it is compared, cached, or rendered.
30
+ */
31
+ export declare function normalizeAssetSymbol(value: unknown): string;
32
+ /**
33
+ * Same as {@link normalizeAssetSymbol}; reads better at call sites that pass a
34
+ * mixed "id or symbol" reference (credit runtime, credential policy, pools).
35
+ */
36
+ export declare function normalizeAssetRef(value: unknown): string;
37
+ /** Case- and whitespace-insensitive asset-symbol equality. */
38
+ export declare function isSameAssetSymbol(a: unknown, b: unknown): boolean;
39
+ /**
40
+ * Split an "assetA/assetB" CLI target into the two normalized symbols.
41
+ * Whitespace around either leg is dropped and both legs are uppercased, so
42
+ * "assetb/asseta" and "ASSETB / ASSETA" produce the same assetA/assetB pair.
43
+ * @returns exactly two symbols, or [] when the target is not a usable pair.
44
+ */
45
+ export declare function splitPairTarget(target: unknown): string[];
46
+ /**
47
+ * Canonicalize the asset symbols of a bot config entry, recursively into
48
+ * `debtPolicy.lending[]`. This is the single definition of WHICH config keys
49
+ * hold symbols, shared by every config reader:
50
+ * - `modules/bot_settings.normalizeBotEntry` (production read funnel)
51
+ * - `analysis/bot_key_utils.loadBotMeta` (analysis/tools read funnel)
52
+ *
53
+ * Returns the SAME reference when there is nothing to canonicalize, so the
54
+ * common already-uppercase case costs one pass and no allocation, and a
55
+ * hand-edited lowercase entry never leaks into a chain call, a comparison or
56
+ * a rendered label. The input is never mutated.
57
+ */
58
+ export declare function canonicalizeBotAssetSymbols<T extends Record<string, any>>(entry: T): T;
59
+ //# sourceMappingURL=asset_symbols.d.ts.map