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.
Files changed (70) hide show
  1. package/CHANGELOG.md +42 -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 +57 -29
  20. package/dist/market_adapter/core/market_adapter_service.d.ts +81 -1
  21. package/dist/market_adapter/core/market_adapter_service.js +225 -18
  22. package/dist/market_adapter/core/signals/hurst_analyzer.d.ts +10 -1
  23. package/dist/market_adapter/core/signals/hurst_analyzer.js +40 -18
  24. package/dist/market_adapter/core/signals/permutation_entropy_analyzer.d.ts +26 -2
  25. package/dist/market_adapter/core/signals/permutation_entropy_analyzer.js +132 -29
  26. package/dist/market_adapter/core/strategies/ama_slope_model.d.ts +2 -2
  27. package/dist/market_adapter/core/strategies/ama_slope_model.js +12 -10
  28. package/dist/market_adapter/core/strategies/dynamic_weight_series.d.ts +41 -14
  29. package/dist/market_adapter/core/strategies/dynamic_weight_series.js +138 -30
  30. package/dist/market_adapter/core/strategies/regime_gate.d.ts +61 -3
  31. package/dist/market_adapter/core/strategies/regime_gate.js +207 -7
  32. package/dist/market_adapter/interval_utils.d.ts +18 -1
  33. package/dist/market_adapter/interval_utils.js +31 -1
  34. package/dist/market_adapter/lp_chart_strategy_loader.js +2 -1
  35. package/dist/market_adapter/market_adapter.d.ts +151 -2
  36. package/dist/market_adapter/market_adapter.js +378 -62
  37. package/dist/market_adapter/test_helpers.d.ts +2 -2
  38. package/dist/market_adapter/test_helpers.js +2 -2
  39. package/dist/market_adapter/utils/chain.d.ts +1 -1
  40. package/dist/market_adapter/utils/chain.js +8 -6
  41. package/dist/market_adapter/utils/file_json_cache.d.ts +29 -0
  42. package/dist/market_adapter/utils/file_json_cache.js +106 -0
  43. package/dist/modules/account_bots.js +5 -4
  44. package/dist/modules/bitshares-native/resolvers.js +5 -0
  45. package/dist/modules/bot_settings.js +13 -1
  46. package/dist/modules/chain_orders.js +2 -1
  47. package/dist/modules/config.d.ts +6 -0
  48. package/dist/modules/config.js +1 -0
  49. package/dist/modules/constants.d.ts +11 -1
  50. package/dist/modules/constants.js +64 -15
  51. package/dist/modules/credential_policy.js +4 -1
  52. package/dist/modules/credit_runtime.js +5 -1
  53. package/dist/modules/order/grid.js +95 -25
  54. package/dist/modules/order/utils/system.js +11 -1
  55. package/dist/modules/utils/asset_symbols.d.ts +59 -0
  56. package/dist/modules/utils/asset_symbols.js +128 -0
  57. package/dist/modules/version_notice.d.ts +166 -20
  58. package/dist/modules/version_notice.js +401 -56
  59. package/dist/pm2.js +9 -2
  60. package/dist/scripts/analyze-credit.js +10 -7
  61. package/dist/scripts/chart_command.js +12 -4
  62. package/dist/scripts/verify-browser-bundle.js +8 -0
  63. package/dist/unlock.js +7 -7
  64. package/docs/DEXBOT_COMPARISON.md +3 -3
  65. package/docs/EVOLUTION.md +14 -12
  66. package/docs/FUND_MOVEMENT_AND_ACCOUNTING.md +1 -1
  67. package/docs/GRID_RECALCULATION.md +28 -5
  68. package/docs/README.md +2 -2
  69. package/market_adapter/README.md +30 -2
  70. package/package.json +1 -1
@@ -0,0 +1,29 @@
1
+ /**
2
+ * Read and parse a JSON file through `loader`, reusing the value this process
3
+ * wrote earlier only while the file is provably unchanged. The entry is
4
+ * consumed on use, so at most one cycle benefits from any single write.
5
+ */
6
+ declare function readCachedJson(filePath: any, loader: () => any): any;
7
+ /**
8
+ * Record that `filePath` now holds exactly `value` on disk, so the next read can
9
+ * skip the parse. Call this right after writing.
10
+ *
11
+ * CONTRACT: `value` is held by reference and there is no copy. The caller must
12
+ * not mutate it afterwards (and must not hand the same object to anything else
13
+ * that will), otherwise the cache would serve something that no longer matches
14
+ * the file. The current call site serializes `value` and then never touches it
15
+ * again, so it satisfies this.
16
+ *
17
+ * KNOWN RACE (accepted): the stamp is taken after the write, so another writer
18
+ * landing between our write and our stat() would make this entry carry its
19
+ * stamp with our value, and a later read could serve that stale payload. The
20
+ * window is sub-millisecond and the adapter is the only writer of these files
21
+ * in-process, so this is not worth a hash of a 250 KiB payload; a genuine
22
+ * cross-process writer is far better served by the mtime check failing on its
23
+ * own write than by a cache that guesses.
24
+ */
25
+ declare function noteJsonWritten(filePath: any, value: any): void;
26
+ /** Drop every cached entry (config reload, tests, explicit cache busting). */
27
+ declare function clearJsonCache(): void;
28
+ export { readCachedJson, noteJsonWritten, clearJsonCache };
29
+ //# sourceMappingURL=file_json_cache.d.ts.map
@@ -0,0 +1,106 @@
1
+ 'use strict';
2
+ import { getStorage } from '../../modules/storage/index.js';
3
+ /**
4
+ * market_adapter/utils/file_json_cache.ts — write-through JSON read cache
5
+ *
6
+ * The hourly cycle re-read every bot's candle file (6 x ~250 KiB) before writing
7
+ * it straight back, which cost ~1.4 ms of JSON.parse per file per cycle for data
8
+ * this process had just serialized itself. Nothing else normally writes those
9
+ * files, but "normally" is not "never" (a gap-repair run, ama_signal_runner or
10
+ * the clear script can), so the cache never trusts process-local state blindly:
11
+ *
12
+ * - Entries exist only for files THIS process wrote (`noteJsonWritten`), so
13
+ * the cached value is known to be what was just serialized to disk.
14
+ * - A cached entry is served only while the file's mtime still matches the
15
+ * stamp taken right after that write, and its size still matches wherever
16
+ * the storage adapter reports one. Any other writer invalidates it. (The
17
+ * browser storage adapter's stat() has no size, so in a browser bundle this
18
+ * degrades to mtime-only; the cache is only wired into the Node runtime.)
19
+ * - A served entry is consumed (deleted). A cycle that reads the file, mutates
20
+ * the object and then fails before writing therefore cannot poison the next
21
+ * cycle: the entry is already gone, and the next read re-parses.
22
+ * - When the file cannot be stat'ed (missing, no storage adapter, or a test
23
+ * injecting its own loader) nothing is cached and the loader always runs.
24
+ *
25
+ * Net effect for the hourly loop: the parse this process would have paid to read
26
+ * back its own previous output disappears, with no path to stale data.
27
+ */
28
+ // Resolved per call, not at import time, so a later setAdapter() (DI in tests, a
29
+ // different bundle entry point) is honoured instead of silently ignored.
30
+ function statOf(filePath) {
31
+ try {
32
+ const st = getStorage().stat(filePath);
33
+ if (!st || !Number.isFinite(st.mtimeMs))
34
+ return null;
35
+ return { mtimeMs: st.mtimeMs, size: Number(st.size) || 0 };
36
+ }
37
+ catch (_) {
38
+ return null;
39
+ }
40
+ }
41
+ // Bounded: one entry per candle file the process has written. 32 covers far more
42
+ // bots than any deployment runs, and each entry is a few hundred KB at most.
43
+ const CACHE_LIMIT = 32;
44
+ const _cache = new Map();
45
+ function _store(filePath, entry) {
46
+ _cache.delete(filePath);
47
+ _cache.set(filePath, entry);
48
+ while (_cache.size > CACHE_LIMIT) {
49
+ const oldest = _cache.keys().next();
50
+ if (oldest.done)
51
+ break;
52
+ _cache.delete(oldest.value);
53
+ }
54
+ }
55
+ /**
56
+ * Read and parse a JSON file through `loader`, reusing the value this process
57
+ * wrote earlier only while the file is provably unchanged. The entry is
58
+ * consumed on use, so at most one cycle benefits from any single write.
59
+ */
60
+ function readCachedJson(filePath, loader) {
61
+ const stamp = statOf(filePath);
62
+ if (!stamp) {
63
+ // Cannot validate -> never serve, and forget anything we had.
64
+ _cache.delete(filePath);
65
+ return loader();
66
+ }
67
+ const hit = _cache.get(filePath);
68
+ if (hit && hit.mtimeMs === stamp.mtimeMs && hit.size === stamp.size) {
69
+ _cache.delete(filePath);
70
+ return hit.value;
71
+ }
72
+ _cache.delete(filePath);
73
+ return loader();
74
+ }
75
+ /**
76
+ * Record that `filePath` now holds exactly `value` on disk, so the next read can
77
+ * skip the parse. Call this right after writing.
78
+ *
79
+ * CONTRACT: `value` is held by reference and there is no copy. The caller must
80
+ * not mutate it afterwards (and must not hand the same object to anything else
81
+ * that will), otherwise the cache would serve something that no longer matches
82
+ * the file. The current call site serializes `value` and then never touches it
83
+ * again, so it satisfies this.
84
+ *
85
+ * KNOWN RACE (accepted): the stamp is taken after the write, so another writer
86
+ * landing between our write and our stat() would make this entry carry its
87
+ * stamp with our value, and a later read could serve that stale payload. The
88
+ * window is sub-millisecond and the adapter is the only writer of these files
89
+ * in-process, so this is not worth a hash of a 250 KiB payload; a genuine
90
+ * cross-process writer is far better served by the mtime check failing on its
91
+ * own write than by a cache that guesses.
92
+ */
93
+ function noteJsonWritten(filePath, value) {
94
+ const stamp = statOf(filePath);
95
+ if (!stamp) {
96
+ _cache.delete(filePath);
97
+ return;
98
+ }
99
+ _store(filePath, { mtimeMs: stamp.mtimeMs, size: stamp.size, value });
100
+ }
101
+ /** Drop every cached entry (config reload, tests, explicit cache busting). */
102
+ function clearJsonCache() {
103
+ _cache.clear();
104
+ }
105
+ export { readCachedJson, noteJsonWritten, clearJsonCache };
106
+ //# sourceMappingURL=file_json_cache.js.map
@@ -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
  }
@@ -11,6 +11,12 @@ declare const Config: {
11
11
  DEXBOT_LAUNCHER_WORKER: boolean;
12
12
  DEXBOT_UPDATE_SKIP_RELOAD: boolean;
13
13
  DEXBOT_SKIP_VERSION_NOTICE: boolean;
14
+ /** Bypass the version-probe cache for one run (`dexbot stat` with
15
+ * DEXBOT_VERSION_CHECK_FORCE=1 re-probes instead of answering from the
16
+ * 12h cache). The diagnostic escape hatch for "is the registry reachable
17
+ * right now?" — a stale cached failure otherwise looks identical to a
18
+ * live one. */
19
+ DEXBOT_VERSION_CHECK_FORCE: boolean;
14
20
  NO_COLOR: string | undefined;
15
21
  PM2_HOME: string | undefined;
16
22
  DEXBOT_SUPERVISOR_SOCKET: string | undefined;
@@ -54,6 +54,7 @@ const Config = {
54
54
  DEXBOT_LAUNCHER_WORKER: bool('DEXBOT_LAUNCHER_WORKER'),
55
55
  DEXBOT_UPDATE_SKIP_RELOAD: bool('DEXBOT_UPDATE_SKIP_RELOAD'),
56
56
  DEXBOT_SKIP_VERSION_NOTICE: bool('DEXBOT_SKIP_VERSION_NOTICE'),
57
+ DEXBOT_VERSION_CHECK_FORCE: bool('DEXBOT_VERSION_CHECK_FORCE'),
57
58
  NO_COLOR: str('NO_COLOR'),
58
59
  // ── Paths ───────────────────────────────────────────────────────
59
60
  PM2_HOME: str('PM2_HOME'),
@@ -73,7 +73,7 @@
73
73
  * AMA_DELTA_THRESHOLD_PERCENT: % change in AMA center price that triggers grid reset
74
74
  * DEFAULT_AMA_KEY: Default AMA profile used for `gridPrice: "ama"`
75
75
  * AMAS: Built-in AMA1..AMA4 presets for market adapter defaults
76
- * Related to bot AMA configuration (profiles/bots.json: ama.enabled, erPeriod, etc.)
76
+ * Related to bot AMA configuration (profiles/bots.json: gridPrice keyword, ama.erPeriod, etc.)
77
77
  * Stored in: profiles/general.settings.json
78
78
  *
79
79
  * MAINTENANCE & MONITORING:
@@ -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;
@@ -574,9 +580,13 @@ declare let UPDATER: {
574
580
  SCHEDULE: string;
575
581
  NOTICE_ENABLED: boolean;
576
582
  NOTICE_INTERVAL_MS: number;
583
+ NOTICE_RETRY_MS: number;
577
584
  NOTICE_TIMEOUT_MS: number;
578
585
  NOTICE_STATUS_TIMEOUT_MS: number;
586
+ NOTICE_STAGE_GRACE_MS: number;
579
587
  REGISTRY_URL: string;
588
+ GITHUB_RELEASE_URL: string;
589
+ GITHUB_API_BASE: string;
580
590
  };
581
591
  declare let LAUNCHER: {
582
592
  MONOLITHIC: {
@@ -74,7 +74,7 @@
74
74
  * AMA_DELTA_THRESHOLD_PERCENT: % change in AMA center price that triggers grid reset
75
75
  * DEFAULT_AMA_KEY: Default AMA profile used for `gridPrice: "ama"`
76
76
  * AMAS: Built-in AMA1..AMA4 presets for market adapter defaults
77
- * Related to bot AMA configuration (profiles/bots.json: ama.enabled, erPeriod, etc.)
77
+ * Related to bot AMA configuration (profiles/bots.json: gridPrice keyword, ama.erPeriod, etc.)
78
78
  * Stored in: profiles/general.settings.json
79
79
  *
80
80
  * MAINTENANCE & MONITORING:
@@ -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.
@@ -1432,19 +1454,46 @@ let UPDATER = {
1432
1454
  // switch means the default-off auto-updater does not also silence the
1433
1455
  // "you are running an outdated build" warning.
1434
1456
  NOTICE_ENABLED: true,
1435
- // Minimum gap between registry probes (24h). Also throttles failures, so an
1436
- // offline node pays the network timeout at most once a day, not per start.
1437
- // Set 0 to probe on every launcher start (an explicit opt-in to always-check).
1438
- NOTICE_INTERVAL_MS: 86_400_000,
1439
- // Hard timeout for the registry request. The check never blocks startup,
1440
- // but a hung socket must not keep the launcher alive either.
1441
- NOTICE_TIMEOUT_MS: 2_000,
1442
- // Shorter cap for `dexbot status`, which awaits the probe inline (no
1443
- // startup work overlaps it), so a stale/offline probe cannot stall the
1444
- // status output for the full NOTICE_TIMEOUT_MS.
1445
- NOTICE_STATUS_TIMEOUT_MS: 750,
1446
- // Registry document queried for the published `latest` version.
1447
- REGISTRY_URL: "https://registry.npmjs.org/dexbot/latest"
1457
+ // Minimum gap between probes AFTER A SUCCESSFUL observation (12h). A
1458
+ // successful answer is stable, so it is cached and costs no request on
1459
+ // every run that consults it. Half a day rather than a full day: the
1460
+ // published version does not move under us, but `dexbot stat` is the
1461
+ // command an operator runs to ask "am I current?", and 24h let that answer
1462
+ // come from an observation taken the previous morning. Set 0 to probe on
1463
+ // every run (an explicit opt-in to always-check, which disables the
1464
+ // failure backoff too).
1465
+ NOTICE_INTERVAL_MS: 43_200_000,
1466
+ // Backoff after a FAILED probe. A failure is the one observation that
1467
+ // decays fastest: throttling it for the full NOTICE_INTERVAL_MS turned a
1468
+ // 5s network hiccup into a permanent gray "?" for a day, with no retry to
1469
+ // disprove it. A failure is therefore re-tried after 15 minutes while the
1470
+ // last good answer is still served from the cache in the meantime.
1471
+ NOTICE_RETRY_MS: 900_000,
1472
+ // Total network budget for one probe, shared evenly across the configured
1473
+ // sources. The check never blocks startup, but a hung socket must not keep
1474
+ // the launcher alive either.
1475
+ NOTICE_TIMEOUT_MS: 4_000,
1476
+ // Budget for the final re-probe in `dexbot stat`. That command gives the
1477
+ // probe 1s at the top of the report, 1s more at the end, and then this
1478
+ // budget for a forced second attempt; when even that answers nothing the
1479
+ // verdict says "no current version information" instead of leaving the
1480
+ // operator to infer it from a missing line. Kept at 3s so the whole
1481
+ // escalation costs ~4s of waiting, all of it at the bottom of the report.
1482
+ NOTICE_STATUS_TIMEOUT_MS: 3_000,
1483
+ // How long `dexbot stat` waits for an answer before printing the rest of
1484
+ // the report. A valid cache or a quick registry answer lands inside this
1485
+ // and the command never notices the wait.
1486
+ NOTICE_STAGE_GRACE_MS: 1_000,
1487
+ // Source 1 — the npm dist-tag document. Empty disables the source.
1488
+ REGISTRY_URL: "https://registry.npmjs.org/dexbot/latest",
1489
+ // Source 2 — the GitHub "latest release" document, the fallback for a host
1490
+ // that cannot reach registry.npmjs.org. Empty DERIVES the URL from
1491
+ // REPOSITORY_URL (so a fork/self-hosted mirror is honoured); set it to a
1492
+ // non-GitHub value to pin the endpoint, or to 'off' to disable the source.
1493
+ GITHUB_RELEASE_URL: "",
1494
+ // Base for the derived GitHub source. Split out so a GitHub Enterprise
1495
+ // mirror is a config change, not a code change.
1496
+ GITHUB_API_BASE: "https://api.github.com"
1448
1497
  };
1449
1498
  let LAUNCHER = {
1450
1499
  MONOLITHIC: {
@@ -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
  }
@@ -2609,29 +2609,74 @@ export async function prepareSpreadCorrectionOrders(manager, preferredSide, outO
2609
2609
  // boundary-correct type so a SPREAD slot that, after a boundary shift, now sits
2610
2610
  // in the BUY or SELL zone is excluded — it would otherwise be placed on the
2611
2611
  // correction side at a price the grid already considers the opposite side.
2612
- // Candidate ordering: window-contiguous-first when the rail has live
2613
- // orders to extend (BUY lowest first, SELL highest first, both adjacent
2614
- // to the live window top). A fully-empty rail has no window anchor —
2615
- // "lowest buy" would be the rail bottom, placing deep orders while the
2616
- // near-market gap stays open — so it falls back to spread-edge-first
2617
- // (BUY highest, SELL lowest) to close the spread near market first.
2618
- // The gap-band promotion path below stays edge-first by necessity
2619
- // (boundary derivation requires contiguity), so under fund shortage
2620
- // in-rail holes heal before band slots.
2621
- const railHasLiveOrders = allOrders.some((o) => getSlotCorrectType(o) === railType && isOrderPlaced(o));
2622
- const sortCandidates = (a, b) => {
2623
- const edgeFirst = railType === ORDER_TYPES.BUY
2624
- ? b.price - a.price
2625
- : a.price - b.price;
2626
- const windowFirst = railType === ORDER_TYPES.BUY
2627
- ? a.price - b.price
2628
- : b.price - a.price;
2629
- return railHasLiveOrders ? windowFirst : edgeFirst;
2612
+ //
2613
+ // Candidate ordering: MARKET-NEAREST FIRST, one comparator for both
2614
+ // rail states. A correction is only useful if it tightens bestBuy/bestSell,
2615
+ // which means it must land on the market side of the live window — the
2616
+ // highest empty BUY (live window is the rail top) or the lowest empty
2617
+ // SELL (live window is the rail bottom). Empty slots always sit on the
2618
+ // far side of the live window, so "adjacent to the window" and "closest
2619
+ // to market" are the same slot, and the same comparator also gives the
2620
+ // correct answer for a fully-empty rail (no window anchor, so the
2621
+ // market-nearest slot is by definition the best one to create).
2622
+ //
2623
+ // This previously had two branches — windowFirst (windowed) vs
2624
+ // edgeFirst (empty) — that were written as exact OPPOSITES, so a SELL
2625
+ // rail with a live window sorted DESCENDING and picked the grid
2626
+ // ceiling: an order ~50% above bestSell that cannot tighten the spread
2627
+ // by a single tick, and that the next resync then cancels as surplus.
2628
+ const sortCandidates = (a, b) => railType === ORDER_TYPES.BUY
2629
+ ? b.price - a.price
2630
+ : a.price - b.price;
2631
+ // SPREAD-TIGHTENING GUARD: on a rail that already has a live order, only
2632
+ // a candidate that IMPROVES that rail's best price is a spread repair at
2633
+ // all. A SELL must land below the lowest live sell, a BUY above the
2634
+ // highest live buy. Anything else merely parks funds in a slot that sits
2635
+ // beyond the live window and leaves bestBuy/bestSell — and therefore the
2636
+ // measured spread — bit-for-bit unchanged.
2637
+ //
2638
+ // Sorting alone cannot enforce this: the orphan pool is rail-wide (every
2639
+ // empty slot on the side), so market-nearest still resolves to the first
2640
+ // empty slot PAST the window, which is on the wrong side of the live
2641
+ // best. Observed on a live market-pair bot whose live sells sat at
2642
+ // 1071-1134 with 116 empty sell slots above them: correction kept
2643
+ // creating orders at 1136, 1140, ... and eventually 1600/1605, none of
2644
+ // which could narrow the spread, until the next resync cancelled them
2645
+ // all as surplus. This guard makes the grid edge structurally
2646
+ // unreachable for a correction rather than merely sorted last.
2647
+ //
2648
+ // The reference is taken from `_getOnChainOrders` — the SAME input set
2649
+ // `calculateCurrentSpread` measures the spread from — so "does this
2650
+ // placement narrow the spread" is answered against literally the same
2651
+ // book the flag was raised from, and there is no second definition of
2652
+ // "counts as an on-chain order" to drift out of sync.
2653
+ //
2654
+ // Note the deliberate classifier asymmetry: the ANCHOR is matched by
2655
+ // stored `o.type` (inherited from _getOnChainOrders), while CANDIDATES
2656
+ // below are matched by `getSlotCorrectType` geometry. That is right
2657
+ // for both: an anchor is a live on-chain order whose side is what the
2658
+ // spread is actually computed from, whereas an empty candidate slot has
2659
+ // a normalized (often SPREAD) stored type and its intended side is the
2660
+ // geometric one.
2661
+ //
2662
+ // With no live order on the side there is no reference to improve, so
2663
+ // the market-nearest slot is by definition the best available and the
2664
+ // guard stays open.
2665
+ const { onChainBuys, onChainSells } = _getOnChainOrders(manager);
2666
+ const railBestIsMax = railType === ORDER_TYPES.BUY;
2667
+ const bestLiveOnRail = railBestIsMax
2668
+ ? (onChainBuys.length ? Math.max(...onChainBuys.map((o) => o.price)) : null)
2669
+ : (onChainSells.length ? Math.min(...onChainSells.map((o) => o.price)) : null);
2670
+ const tightensSpread = (c) => {
2671
+ if (bestLiveOnRail == null || c?.price == null)
2672
+ return true;
2673
+ return railBestIsMax ? c.price > bestLiveOnRail : c.price < bestLiveOnRail;
2630
2674
  };
2631
2675
  const typedSpreadCandidates = allOrders
2632
2676
  .filter((o) => o.type === ORDER_TYPES.SPREAD
2633
2677
  && isSlotAvailable(o)
2634
2678
  && getSlotCorrectType(o) === railType)
2679
+ .filter(tightensSpread)
2635
2680
  .sort(sortCandidates)
2636
2681
  .slice(0, missingSlots);
2637
2682
  // Secondary candidates: orphaned virtual slots that have lost their
@@ -2664,6 +2709,7 @@ export async function prepareSpreadCorrectionOrders(manager, preferredSide, outO
2664
2709
  && o.state === ORDER_STATES.VIRTUAL
2665
2710
  && !o.orderId
2666
2711
  && getSlotCorrectType(o) === railType)
2712
+ .filter(tightensSpread)
2667
2713
  .sort(sortCandidates)
2668
2714
  .slice(0, missingSlots);
2669
2715
  // If the funded rail is full, the spread itself may be stale: the
@@ -2711,22 +2757,44 @@ export async function prepareSpreadCorrectionOrders(manager, preferredSide, outO
2711
2757
  if (promotedCandidates.length > 0) {
2712
2758
  manager.logger?.log?.(`[SPREAD-CORRECTION] ${promotedCandidates.length} gap slot(s) available for boundary promotion on ${sideName}`, 'info');
2713
2759
  }
2760
+ else {
2761
+ // Promotion produced nothing. Name the BINDING constraint —
2762
+ // the three are operationally different (a config change fixes
2763
+ // one, a geometry change fixes the others) and a bare "skipped"
2764
+ // makes all three look identical.
2765
+ const bandSize = Math.max(0, sellStartIdx - buyEndIdx - 1);
2766
+ const oppositeSide = railType === ORDER_TYPES.BUY ? 'sell' : 'buy';
2767
+ const reason = maxPromotionDepth <= 0
2768
+ ? `stranding cap is 0 — a boundary slide would swallow a placed ${oppositeSide} order into the implied spread band`
2769
+ : (bandSize <= spreadReserve
2770
+ ? `gap band (${bandSize} slot(s)) is at or below the MIN_SPREAD_ORDERS reserve (${spreadReserve})`
2771
+ : 'no contiguous empty run from the rail edge into the band');
2772
+ manager.logger?.log?.(`[SPREAD-CORRECTION] no gap slot available on ${sideName} — ${reason}; the spread is not correctable on this side this cycle`, 'info');
2773
+ }
2714
2774
  }
2715
- // Merge: prefer orphaned virtuals (they already occupy correct grid positions) then
2716
- // fall back to SPREAD slots for any remaining quota.
2775
+ // Merge, GAP BAND FIRST. A boundary promotion is the only candidate
2776
+ // kind that places INSIDE the empty spread band, so it is listed ahead
2777
+ // of the rail pools. In practice the promotion GATE above (only promote
2778
+ // when the rail pools under-fill the quota) already keeps the two from
2779
+ // competing: once the spread-tightening guard empties the rail pool of
2780
+ // useless far-rail slots, the gate opens and the band is asked. The
2781
+ // ordering below is the belt to that braces — if the gate is ever
2782
+ // relaxed, the band still wins by default rather than losing to a
2783
+ // rail-wide pool that is capped at missingSlots on its own and so can
2784
+ // consume the whole quota without ever entering the gap.
2717
2785
  const remainingQuota = Math.max(0, missingSlots - orphanedVirtualCandidates.length);
2718
2786
  let spreadCandidates = [
2719
- ...orphanedVirtualCandidates,
2787
+ ...promotedCandidates,
2720
2788
  ...typedSpreadCandidates.slice(0, remainingQuota),
2721
- ...promotedCandidates
2789
+ ...orphanedVirtualCandidates
2722
2790
  ];
2723
2791
  // Dedupe by slot id: an empty in-rail slot typed SPREAD (normalized) now
2724
2792
  // qualifies for BOTH orphanedVirtualCandidates and typedSpreadCandidates
2725
2793
  // (both accept SPREAD type + rail geometry), so a single slot can be
2726
2794
  // planned twice. Duplicate CREATEs would inflate the sizing denominator
2727
2795
  // (diluting every order), mislead the plan counts, and get dropped by the
2728
- // COW same-batch collision filter anyway. Keep the first occurrence
2729
- // (orphaned-priority — those already occupy correct grid positions).
2796
+ // COW same-batch collision filter anyway. Keep the first occurrence —
2797
+ // which under the gap-first merge is the band slot where one exists.
2730
2798
  {
2731
2799
  const seenSlotIds = new Set();
2732
2800
  spreadCandidates = spreadCandidates.filter((c) => {
@@ -2770,7 +2838,9 @@ export async function prepareSpreadCorrectionOrders(manager, preferredSide, outO
2770
2838
  manager.logger?.log?.(`[SPREAD-CORRECTION] Identified ${spreadCandidates.length}/${missingSlots} slot(s) for activation on ${sideName} (orphaned=${orphanedVirtualCandidates.length}, spread=${spreadCandidates.length - orphanedVirtualCandidates.length})`, 'debug');
2771
2839
  }
2772
2840
  if (!edgePartial && spreadCandidates.length === 0) {
2773
- manager.logger?.log?.(`[SPREAD-CORRECTION] No suitable partials, orphaned virtual slots, or spread slots found. Skipping.`, 'warn');
2841
+ manager.logger?.log?.(bestLiveOnRail == null
2842
+ ? `[SPREAD-CORRECTION] No suitable partials, orphaned virtual slots, or spread slots found. Skipping.`
2843
+ : `[SPREAD-CORRECTION] No spread-tightening slot on ${sideName} (best live ${bestLiveOnRail}); every remaining empty slot sits beyond the live window and cannot narrow the spread. Skipping.`, 'warn');
2774
2844
  return { ordersToPlace: [], ordersToUpdate: [], origin: 'spread-correction' };
2775
2845
  }
2776
2846
  const orphanedIds = new Set(orphanedVirtualCandidates.map((o) => o.id));