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
@@ -33,6 +33,7 @@ const { FEE_PARAMETERS } = require('../modules/constants');
33
33
  const { PATHS } = require('../modules/paths');
34
34
  const { getErrorMessage } = require('../modules/utils/errors');
35
35
  const { sanitizeKey } = require('../modules/utils/sanitize_key');
36
+ const { normalizeAssetRef, normalizeAssetSymbol, isSameAssetSymbol } = require('../modules/utils/asset_symbols');
36
37
  const { loadSettingsFile, resolveRawBotEntries, normalizeBotEntries } = require('../modules/bot_settings');
37
38
  import { pathToFileURL } from 'node:url';
38
39
  // Terminal colors: centralized palette (modules/cli_colors.ts), shared with
@@ -239,7 +240,9 @@ async function main() {
239
240
  return (await assetInfo(assetId)).symbol;
240
241
  }
241
242
  async function resolveLendingRef(ref) {
242
- const s = String(ref);
243
+ // Refs come from bots.json debtPolicy.lending AND from --mpa/--collateral
244
+ // filters; canonicalize so a lowercase filter still matches the pair.
245
+ const s = normalizeAssetRef(ref);
243
246
  if (/^1\.3\.\d+$/.test(s)) {
244
247
  try {
245
248
  return { id: s, symbol: await symbolOf(s) };
@@ -387,9 +390,9 @@ async function main() {
387
390
  const resolvedMpa = await Promise.all(mpaFilterRefs.map(resolveLendingRef));
388
391
  const resolvedCredit = await Promise.all(creditFilterRefs.map(resolveLendingRef));
389
392
  const mpaIds = new Set(resolvedMpa.map((r) => r.id).filter(Boolean));
390
- const mpaSyms = new Set(resolvedMpa.map((r) => r.symbol.toUpperCase()));
393
+ const mpaSyms = new Set(resolvedMpa.map((r) => normalizeAssetSymbol(r.symbol)));
391
394
  const creditIds = new Set(resolvedCredit.map((r) => r.id).filter(Boolean));
392
- const creditSyms = new Set(resolvedCredit.map((r) => r.symbol.toUpperCase()));
395
+ const creditSyms = new Set(resolvedCredit.map((r) => normalizeAssetSymbol(r.symbol)));
393
396
  const filterActive = unionRefs.length > 0;
394
397
  async function debtMatches(debtAssetId, ids, syms) {
395
398
  if (!filterActive)
@@ -399,7 +402,7 @@ async function main() {
399
402
  if (ids.has(debtAssetId))
400
403
  return true;
401
404
  try {
402
- const sym = (await symbolOf(debtAssetId)).toUpperCase();
405
+ const sym = normalizeAssetSymbol(await symbolOf(debtAssetId));
403
406
  return syms.has(sym);
404
407
  }
405
408
  catch {
@@ -421,7 +424,7 @@ async function main() {
421
424
  symOk = true;
422
425
  else if (debtId) {
423
426
  try {
424
- symOk = creditSyms.has((await symbolOf(debtId)).toUpperCase());
427
+ symOk = creditSyms.has(normalizeAssetSymbol(await symbolOf(debtId)));
425
428
  }
426
429
  catch {
427
430
  symOk = false;
@@ -528,7 +531,7 @@ async function main() {
528
531
  });
529
532
  }
530
533
  const pairIdKeys = new Set(creditPairs.filter((p) => p.debtId && p.collId).map((p) => `${p.debtId}←${p.collId}`));
531
- const pairSymKeys = new Set(creditPairs.map((p) => `${p.debtSym.toUpperCase()}←${p.collSym.toUpperCase()}`));
534
+ const pairSymKeys = new Set(creditPairs.map((p) => `${normalizeAssetSymbol(p.debtSym)}←${normalizeAssetSymbol(p.collSym)}`));
532
535
  // Offer objects for the deals' conversion rates (debt per collateral).
533
536
  const dealOfferIds = creditDeals.map((d) => d?.offer_id).filter(Boolean).map(String);
534
537
  const offerById = await fetchOfferObjects(dealOfferIds);
@@ -643,7 +646,7 @@ async function main() {
643
646
  const feeDenom = Number(FEE_PARAMETERS?.GRAPHENE_FEE_RATE_DENOM) || 1000000;
644
647
  const walletRaw = await fetchWalletRaw(account);
645
648
  const matchPair = (pair, r) => (pair.debtId !== null && r.debtId !== null && pair.debtId === r.debtId && pair.collId !== null && r.collId !== null && pair.collId === r.collId) ||
646
- (pair.debtSym.toUpperCase() === r.debtSym.toUpperCase() && pair.collSym.toUpperCase() === r.collSym.toUpperCase());
649
+ (isSameAssetSymbol(pair.debtSym, r.debtSym) && isSameAssetSymbol(pair.collSym, r.collSym));
647
650
  if (avgCr !== null) {
648
651
  // Label in orange to distinguish from Curr. CR; value keeps the
649
652
  // original health color (single shared max → green/red, mixed or
@@ -32,6 +32,7 @@ const __dirname = path.dirname(__filename);
32
32
  import { loadBotMeta, loadBotSettings, computeBotKey } from '../analysis/bot_key_utils.js';
33
33
  import { PATHS } from '../modules/paths.js';
34
34
  import { normalizePoolId, resolveAsset, findPoolByAssets } from '../market_adapter/utils/chain.js';
35
+ import { normalizeAssetSymbol, splitPairTarget } from '../modules/utils/asset_symbols.js';
35
36
  import { fetchCandlesSequentially, outputPath } from '../market_adapter/inputs/fetch_lp_data.js';
36
37
  import { fetchMarketCandlesSequentially } from '../market_adapter/inputs/fetch_book_data.js';
37
38
  import { fetchFeedCandlesSequentially } from '../market_adapter/inputs/kibana_feed_source.js';
@@ -73,6 +74,7 @@ function printUsage(cmd = 'tv') {
73
74
  console.log(' <bot> Bot name or key from profiles/bots.json');
74
75
  console.log(' <pool-id> Liquidity pool id, e.g. 133 or 1.19.133 (always pool candles)');
75
76
  console.log(' AssetA/AssetB Pair symbols, e.g. TOKENA/TOKENB (pool-first, orderbook fallback)');
77
+ console.log(' Case-insensitive: assetA/assetB is uppercased before it reaches the chain');
76
78
  console.log(' MPA pairs (e.g. BTS/HONEST.USD) can chart price-feed history via --feed');
77
79
  console.log('');
78
80
  console.log('Options:');
@@ -87,6 +89,9 @@ async function resolveMpaBacking(mpaSymbol, bitsharesClient) {
87
89
  const db = bitsharesClient.BitShares?.db;
88
90
  if (!db || typeof db.lookup_asset_symbols !== 'function')
89
91
  return null;
92
+ // Canonical UPPERCASE symbol for the chain call and for every message
93
+ // below, so a lowercase assetA/assetB pair is reported UPPERCASE.
94
+ mpaSymbol = normalizeAssetSymbol(mpaSymbol);
90
95
  let mpa = null;
91
96
  try {
92
97
  const found = await db.lookup_asset_symbols([mpaSymbol]);
@@ -325,7 +330,10 @@ async function run(cmd) {
325
330
  const botHit = findBotByTarget(target);
326
331
  const poolTarget = !botHit && isPoolIdTarget(target);
327
332
  const pairTarget = !botHit && !poolTarget && target.includes('/');
328
- const pairParts = pairTarget ? target.split('/').map((s) => s.trim()).filter(Boolean) : [];
333
+ // A pair target may be typed in any case ("assetb/asseta"); the legs are
334
+ // canonicalized here so the chain call, the cache keys, the chart title and
335
+ // the exported HTML all speak the same UPPERCASE symbols.
336
+ const pairParts = pairTarget ? splitPairTarget(target) : [];
329
337
  if (!botHit && !poolTarget && !pairTarget) {
330
338
  const settings = loadBotSettings();
331
339
  const entries = Array.isArray(settings?.bots) ? settings.bots : [];
@@ -333,7 +341,7 @@ async function run(cmd) {
333
341
  throw new Error(`Unknown target "${target}". Use a bot name/key${keys.length ? ` (${keys.slice(0, 8).join(', ')}${keys.length > 8 ? ', …' : ''})` : ''}, a pool id (e.g. 133), or AssetA/AssetB.`);
334
342
  }
335
343
  if (pairTarget && pairParts.length !== 2)
336
- throw new Error(`Invalid pair "${target}". Use AssetA/AssetB, e.g. TOKENA/TOKENB`);
344
+ throw new Error(`Invalid pair "${target}". Use AssetA/AssetB, e.g. TOKENA/TOKENB (case is normalized to uppercase)`);
337
345
  const bitsharesClient = await import('../modules/bitshares_client.js');
338
346
  const { waitForConnected } = bitsharesClient;
339
347
  await waitForConnected();
@@ -349,8 +357,8 @@ async function run(cmd) {
349
357
  if (botHit) {
350
358
  botKey = botHit.botKey;
351
359
  botMeta = botHit.meta;
352
- const symA = botMeta.assetA;
353
- const symB = botMeta.assetB;
360
+ const symA = normalizeAssetSymbol(botMeta.assetA);
361
+ const symB = normalizeAssetSymbol(botMeta.assetB);
354
362
  if (!symA || !symB)
355
363
  throw new Error(`Bot '${target}' has no assetA/assetB pair in profiles/bots.json`);
356
364
  const [metaA, metaB] = await Promise.all([resolveAsset(symA, bitsharesClient), resolveAsset(symB, bitsharesClient)]);
@@ -176,6 +176,14 @@ const TESTS = [
176
176
  expectFail: false,
177
177
  externalizeNodeBuiltins: true,
178
178
  },
179
+ {
180
+ // The canonical AMA-slope estimator; guards the browser-safe surface now
181
+ // that this module imports modules/constants.ts.
182
+ label: 'market_adapter/core/strategies/dynamic_weight_series.ts (browser-safe)',
183
+ entry: 'market_adapter/core/strategies/dynamic_weight_series.ts',
184
+ expectFail: false,
185
+ externalizeNodeBuiltins: true,
186
+ },
179
187
  {
180
188
  label: 'modules/bitshares-native/serial/serializer.ts (browser-safe)',
181
189
  entry: 'modules/bitshares-native/serial/serializer.ts',
package/dist/unlock.js CHANGED
@@ -51,7 +51,7 @@ import { UPDATER, LAUNCHER } from './modules/constants.js';
51
51
  import { formatStartupNotice } from './modules/cli_start_output.js';
52
52
  import { runtime } from './modules/runtime.js';
53
53
  import { PATHS, printRelocationNotices } from './modules/paths.js';
54
- import { startVersionStatusCheck, flushVersionStatus, printVersionStatusWhenReady } from './modules/version_notice.js';
54
+ import { startVersionStatusCheck, flushVersionStatusOrHeader, printVersionStatusWhenReady } from './modules/version_notice.js';
55
55
  import { buildRuntimeScriptArgs } from './modules/launcher/runtime_entry.js';
56
56
  import { sendControlCommand } from './modules/launcher/supervisor_control.js';
57
57
  import { registerCleanup, setupGracefulShutdown } from './modules/graceful_shutdown.js';
@@ -505,7 +505,7 @@ async function main({ argv = process.argv, startupGraceMs = DEFAULT_STARTUP_GRAC
505
505
  printLauncherHeader({ botName: effectiveBotName || botName, clawOnly, creditOnly, isolated, dryrun, headless });
506
506
  console.log(`DEXBot2 already running in background (PID ${pid}).`);
507
507
  console.log('Use `dexbot stat` to inspect it, or `dexbot restart` to restart it.');
508
- await flushVersionStatus(versionStatus);
508
+ await flushVersionStatusOrHeader(versionStatus);
509
509
  process.exitCode = 0;
510
510
  return;
511
511
  }
@@ -565,7 +565,7 @@ async function main({ argv = process.argv, startupGraceMs = DEFAULT_STARTUP_GRAC
565
565
  if (pid > 0) {
566
566
  console.log(`DEXBot2 already running in background (PID ${pid}).`);
567
567
  console.log('Use `dexbot stat` to inspect it, or `dexbot restart` to restart it.');
568
- await flushVersionStatus(versionStatus);
568
+ await flushVersionStatusOrHeader(versionStatus);
569
569
  process.exitCode = 0;
570
570
  return;
571
571
  }
@@ -608,12 +608,12 @@ async function main({ argv = process.argv, startupGraceMs = DEFAULT_STARTUP_GRAC
608
608
  child.unref();
609
609
  storage.writeFile(MONOLITHIC_PID_FILE, String(child.pid), { mode: 0o600 });
610
610
  printLauncherStartupSummary({ botNames: launchedBotNames, mode: 'background' });
611
- await flushVersionStatus(versionStatus);
611
+ await flushVersionStatusOrHeader(versionStatus);
612
612
  process.exit(0);
613
613
  }
614
614
  if (clawOnly) {
615
615
  printLauncherSuccess({ clawOnly });
616
- await flushVersionStatus(versionStatus);
616
+ await flushVersionStatusOrHeader(versionStatus);
617
617
  const exitCode = await controller.waitForManagedDaemon();
618
618
  process.exitCode = exitCode || 0;
619
619
  return;
@@ -642,7 +642,7 @@ async function main({ argv = process.argv, startupGraceMs = DEFAULT_STARTUP_GRAC
642
642
  console.log(`Supervisor PID: ${supervisorPid}`);
643
643
  console.log(`Control socket: ${Config.DEXBOT_SUPERVISOR_SOCKET || SOCKET_PATH}`);
644
644
  console.log(`Supervisor logs: ${SUPERVISOR_OUT_LOG}`);
645
- await flushVersionStatus(versionStatus);
645
+ await flushVersionStatusOrHeader(versionStatus);
646
646
  process.exitCode = 0;
647
647
  return;
648
648
  }
@@ -715,7 +715,7 @@ async function main({ argv = process.argv, startupGraceMs = DEFAULT_STARTUP_GRAC
715
715
  if (!updater?.pendingRestart) {
716
716
  if (!isMonolithicBgChild) {
717
717
  printLauncherStartupSummary({ botNames: launchedBotNames, mode: 'foreground' });
718
- await flushVersionStatus(versionStatus);
718
+ await flushVersionStatusOrHeader(versionStatus);
719
719
  }
720
720
  }
721
721
  const onSigint = () => forwardSignal(botProcess, 'SIGINT');
@@ -1,7 +1,7 @@
1
1
  # DEXBot vs DEXBot2 — Detailed Comparison Report
2
2
 
3
3
  > **Date:** 2026-09-02 *(metrics refreshed against local source trees)*
4
- > **Scope:** Full architectural, functional, and operational comparison between the original [DEXBot](https://github.com/Codaone/DEXBot) (Python, v1.0.0) and DEXBot2 (TypeScript, v1.6.8).
4
+ > **Scope:** Full architectural, functional, and operational comparison between the original [DEXBot](https://github.com/Codaone/DEXBot) (Python, v1.0.0) and DEXBot2 (TypeScript, v1.6.10).
5
5
  > **Audience:** Developers, contributors, and operators evaluating or migrating between the two projects.
6
6
 
7
7
  ---
@@ -36,7 +36,7 @@
36
36
 
37
37
  | Attribute | DEXBot (original) | DEXBot2 |
38
38
  |---|---|---|
39
- | **Release Track** | 1.0.0 | v1.6.8 |
39
+ | **Release Track** | 1.0.0 | v1.6.10 |
40
40
  | **Language** | Python 3.6+ | TypeScript 5.x |
41
41
  | **Status** | Released 1.0.0, unmaintained | Active development |
42
42
  | **Last Repo Activity** | May 23, 2020 | 2026-09-02 |
@@ -776,7 +776,7 @@ Where:
776
776
 
777
777
  | Metric | DEXBot | DEXBot2 |
778
778
  |---|---|---|
779
- | **Release Track** | 1.0.0 | v1.6.8 |
779
+ | **Release Track** | 1.0.0 | v1.6.10 |
780
780
  | **Active Since** | ~2018 | December 2025 |
781
781
  | **Last Commit** | May 23, 2020 | 2026-09-02 |
782
782
  | **Total Commits** | 2281 | 2,125 (v1.4.25) |
package/docs/EVOLUTION.md CHANGED
@@ -2,14 +2,14 @@
2
2
 
3
3
  ## Executive Summary
4
4
 
5
- DEXBot2 is a sophisticated decentralized exchange trading bot for the BitShares blockchain. This report documents the complete evolution of the project from its inception in December 2025 through the current 1.6.8 release.
5
+ DEXBot2 is a sophisticated decentralized exchange trading bot for the BitShares blockchain. This report documents the complete evolution of the project from its inception in December 2025 through the current 1.6.10 release.
6
6
 
7
7
  ### Key Milestones
8
8
  - **Project Inception**: December 2, 2025
9
- - **Growth Phase**: 2,300 commits over ~9 active months
9
+ - **Growth Phase**: 2,315 commits over ~9 active months
10
10
  - **Code Maturity**: Evolution from basic utilities to a ~100,000+ LoC intelligent TypeScript system
11
11
  - **Stability**: Progression from manual testing to a suite of 305 automated test files
12
- - **Releases**: 140 version entries in the changelog (v0.1.0 to v1.6.8)
12
+ - **Releases**: 142 version entries in the changelog (v0.1.0 to v1.6.10)
13
13
 
14
14
  > **Post-1.0.0 "why":** the thematic story behind the hardening releases — root cause, recurring
15
15
  > bug families, and lessons — lives in
@@ -149,7 +149,7 @@ Evolved from a basic README to a comprehensive framework (50+ docs entries, 80%+
149
149
 
150
150
  ## Version History
151
151
 
152
- Compact, era-level view; commit counts are `git rev-list --count <tag>..<tag>` over the current history (2026-09-28), so the column sums to 2,194 — the 106 commits before the `v0.1.0` tag are not attributed to an era (2,194 + 106 = 2,300). Per-release detail lives in [CHANGELOG.md](../CHANGELOG.md); the thematic post-1.0.0 story in [ORDER_ENGINE_POST_1.0_RETROSPECTIVE.md](ORDER_ENGINE_POST_1.0_RETROSPECTIVE.md).
152
+ Compact, era-level view; commit counts are `git rev-list --count <tag>..<tag>` over the current history (2026-10-01), so the column sums to 2,209 — the 106 commits before the `v0.1.0` tag are not attributed to an era (2,209 + 106 = 2,315). Per-release detail lives in [CHANGELOG.md](../CHANGELOG.md); the thematic post-1.0.0 story in [ORDER_ENGINE_POST_1.0_RETROSPECTIVE.md](ORDER_ENGINE_POST_1.0_RETROSPECTIVE.md).
153
153
 
154
154
  | Era | Commits | Theme |
155
155
  |-----|--------:|-------|
@@ -161,16 +161,18 @@ Compact, era-level view; commit counts are `git rev-list --count <tag>..<tag>` o
161
161
  | v1.4.25 → v1.5.3 | 45 | Credit overview + whitelist-scoped CR, TradingView tooling, daemon-safe reload, gap-evacuation/rail-hole hardening, sync adoption hardening, boundary ownership |
162
162
  | v1.5.3 → v1.6.0 | 39 | Node-failure ledger, grid regeneration, reserve ladder, live-config pickup, owed-crawl persistence, fill-anchored boundary recovery, TradingView overlay |
163
163
  | v1.6.0 → v1.6.3 | 17 | Never-run-stale hardening, whitelist range-scaling opt-in, grid-price invariant, shard candle cache, correction-queue staleness, final pre-broadcast pivot gate |
164
- | v1.6.3 → v1.6.4 | 19 | Fund-driven spread correction, gapSlots+1 batch cap, VIRTUAL RMS divergence, sync-lock log fix, invariant-doc contract, analysis shared modules, window-aware profitability annualisation, portable chart exports, range-threshold restore, dead-code purge, doc consolidation |
165
- | v1.6.4 → v1.6.5 | 16 | Editor-managed whitelist flags + legacy generator removal, centralized bot defaults/settings docs, log-symmetric range-scaling tilt, AMA gridPrice default + unset → startPrice normalization, Pool default/warn-color cues, Grid Health AMA-slope Δ knob, dynamic-weight chart CLI, update dist-freshness self-heal, launcher worker rename, RMS log tagging |
166
- | v1.6.5 → v1.6.6 | 13 | Stale-cancellation guard hardening (live ownership, per-plan startup revalidation, COW orphan protection, settlement safety), editor label/menu realignment + colored bot list, grouped CLI help, poolRef aliases + startPrice priority, legacy SMA/MACD/RSI analyzer archived, run-relative candle-cache migration dropped, update dist-freshness tsconfig-exclude fix |
167
- | v1.6.6 → v1.6.7 | 11 | Native session/fill-channel recovery (dead-but-open forced reconnect, stale api_id self-heal, COW stale-plan recheck) + clean-process ecosystem regen, `dexbot start` onboarding redirect, key-manager cancellation + empty-vault onboarding link, LAST-FILL-GUARD pivot persistence (provenance-gated snapshot mirror, genesis-bound + TTL + on-grid restore with the boundary, centralized writer, generation invalidation mirroring the owed-crawl ledger) |
168
- | v1.6.7 → v1.6.8 | 12 | Correction-drain budget + broadcast-region timer/fill deferral (bounded `_gridLock` hold, backlog alarm, stale-flag-safe maintenance deferral, defer bound tied to the watchdog, per-group create yield) and its wall-clock follow-up, PM2 log-capture restore + `pm2-logrotate` enablement, passive new-version notice (bounded registry probe, notify-once latch committed only on display, install-kind hint, independent NOTICE kill switches) + review hardening (dryrun silence, status timeout, latch regression guard, terminal-path flushes, non-blocking print on the isolated-foreground launch path, AbortController-independent hard timeout backstop, centralized flush), changelog-gap close + stale-reference realignment, the genesis-less-snapshot refusal (ladder required at load; `MISSING_GENESIS_POLICY` rebuild/halt, sync-entry assert, persisted-row schema gate), and reserve window-exclusion classification (window members no longer read as reserves at any no-crawl/refill-wire site; legacy numeric `reserveOrders` read-time migration; retained-vs-dropped crawl log fix; shared rail-center helper), plus the legacy tolerance-matcher removal (frozen ladder the only price authority), the npm-tarball trim (explicit analysis asset list, sourcemaps dropped, test sources excluded, legacy Kalman suites rewired into `test:legacy`), the AMA grid-reset replay in the bot charts (with the slope-baseline, non-positive-threshold and config read-back runtime fixes), the `kalS%` default bump (1.0 → 1.11), the incremental/bounded Kibana tail refresh (timestamped coverage, per-gap settle horizon, gap merging, span cap, 48h ceiling), and the 1.4x range-threshold widening |
164
+ | v1.6.3 → v1.6.4 | 19 | Fund-driven spread correction, batched correction cap, RMS divergence, invariant-doc contract, shared analysis modules, window-aware profitability, portable chart exports, range-threshold restore, dead-code purge |
165
+ | v1.6.4 → v1.6.5 | 16 | Editor-managed whitelist flags, centralized bot defaults/settings, log-symmetric range tilt, AMA gridPrice normalization, Pool/Health cues, AMA-slope Δ knob, dynamic-weight CLI, update self-heal, RMS log tagging |
166
+ | v1.6.5 → v1.6.6 | 13 | Stale-cancellation guard hardening, editor/CLI realignment, poolRef aliases + startPrice priority, legacy SMA/MACD/RSI analyzer archived, run-relative candle-cache migration dropped, dist-freshness exclude fix |
167
+ | v1.6.6 → v1.6.7 | 11 | Session/fill-channel recovery, clean-process ecosystem regen, onboarding redirect and key-manager link fixes, LAST-FILL-GUARD pivot persistence |
168
+ | v1.6.7 → v1.6.8 | 14 | Correction-drain budget + broadcast-deferral bounds, PM2 log capture + rotation, passive version notice, genesis-ladder refusal, reserve window exclusion, legacy tolerance-matcher removal, npm-tarball trim, TV grid-reset replay, bounded Kibana tail refresh, 1.4x range-threshold widening |
169
+ | v1.6.8 → v1.6.9 | 6 | Market-adapter cycle-CPU cuts, candle-boundary off-hour idle, spread-correction spread-tightening guard |
170
+ | v1.6.9 → v1.6.10 | 7 | Huber-robust AMA slope, asset-pair uppercase canonicalization, TradingView indicator ownership (auto opt-in, span bounds) and chart-view preservation |
169
171
 
170
172
  ---
171
173
 
172
174
  **Report Originally Generated**: February 19, 2026
173
- **Last Updated**: September 28, 2026
174
- **Total Commits**: 2,300
175
- **Date Range**: December 2, 2025 – September 28, 2026
175
+ **Last Updated**: October 1, 2026
176
+ **Total Commits**: 2,315
177
+ **Date Range**: December 2, 2025 – October 1, 2026
176
178
  **Repository**: DEXBot2 (BitShares DEX Trading Bot)
@@ -801,4 +801,4 @@ To prevent "Time-of-Check to Time-of-Use" errors:
801
801
  **TOCTOU protection in `processFillAccounting`.** `_buildBtsDeferredRefundAdjustment` reads `btsFeeState` from `mgr.orders` while the order lock is held — the lock is acquired before accounting runs, and the POST-RESET and BOOTSTRAP tracked-fill accounting paths follow the same locking pattern.
802
802
 
803
803
  ---
804
- *Technical Reference for DEXBot2 v1.6.8 release*
804
+ *Technical Reference for DEXBot2 v1.6.10 release*
@@ -158,7 +158,6 @@ node dist/market_adapter/market_adapter.js --deltaPercent 2
158
158
  ```json
159
159
  {
160
160
  "ama": {
161
- "enabled": true,
162
161
  "erPeriod": 10, // Efficiency Ratio lookback period (candles)
163
162
  "fastPeriod": 2, // Fast smoothing period for trending markets
164
163
  "slowPeriod": 30, // Slow smoothing period for choppy markets
@@ -167,6 +166,12 @@ node dist/market_adapter/market_adapter.js --deltaPercent 2
167
166
  }
168
167
  ```
169
168
 
169
+ > **`gridPrice` is the only switch.** A bot is AMA-driven when `gridPrice` says
170
+ > so — `usesAmaGridPrice()`, the source of truth shared by the bot, maintenance
171
+ > and launcher runtimes. There is deliberately no `ama.enabled`: a second switch
172
+ > could only disagree with them, freezing the center the bot still trades on. To
173
+ > park a bot, set a non-AMA `gridPrice` (`"fixed"`, a number, `"pool"`, `"book"`).
174
+
170
175
  **Optional: `poolRef`** — pin a specific pool ID for price derivation when using `startPrice: "pool"`. Set in `bots.json` alongside the bot entry:
171
176
  ```json
172
177
  {
@@ -184,7 +189,6 @@ The pool is fetched directly by ID, bypassing pool discovery. Useful when the tr
184
189
  - If no pair profile matches, the bot's `ama` block is used as the fallback
185
190
 
186
191
  **AMA Parameters:**
187
- - `enabled`: Whether to track AMA and trigger grid resets (true/false)
188
192
  - `erPeriod`: How many candles to look back for trend detection
189
193
  - Higher values: More stable, slower response (e.g. `erPeriod=781` very stable)
190
194
  - Lower values: More responsive, catches quick moves
@@ -279,9 +283,28 @@ The snapshot fields involved are:
279
283
  `profiles/general.settings.json` and editable via `dexbot bot` → `1) Grid
280
284
  Drift` (`AMA-Slope Δ`). An explicit `amaSlopeDeltaThresholdPercent` in
281
285
  `profiles/market_adapter_settings.json` bypasses the factor and is used
282
- directly as an average percent-per-bar threshold.
283
-
284
- AMA slope values are stored and compared as average percent per bar. Older
286
+ directly as a percent-per-bar threshold (the same unit as the slope value
287
+ described below — no averaging is implied by the unit).
288
+
289
+ AMA slope values are stored and compared in percent per bar. The value itself
290
+ is a **Huber-robust linear regression of `ln(AMA)` over the lookback window**
291
+ (`computeHuberWindowSlopePct` in
292
+ `core/strategies/dynamic_weight_series.ts`; its tuning lives in
293
+ `MARKET_ADAPTER.DYNAMIC_WEIGHT_AMA_HUBER`) — a smooth, robust fit whose influence
294
+ function is bounded, so one outlier bar cannot drag it, which is what a plain
295
+ mean (and the older two-point endpoint difference it is equivalent to) would do.
296
+ Because the fit reports the log-return, a reading is ~`ln(1+r)` rather than the
297
+ arithmetic `r`: negligible at the sub-0.1 %/bar magnitudes the defaults use, but
298
+ ~3% lower at a 6%/bar saturation (`ln(1.06)*100 = 5.83`). A pre-existing user
299
+ override of `amaSlope.maxSlopePct` or `neutralZonePct` was tuned against the
300
+ arithmetic reading, so treat a saturated override as a hair tighter than before.
301
+
302
+ Changing the estimator changes the stored value: after a deploy, the first
303
+ cycle compares a new-algorithm reading against the baseline persisted by the
304
+ previous one (`botState.gridRangeScalingAmaSlope`). The magnitudes agree
305
+ closely, so the delta stays under the reset gate on ~98% of bars — a rare,
306
+ single extra recenter for whitelisted bots. No version marker is persisted to
307
+ suppress it. Older
285
308
  settings that used cumulative percent over the full lookback can either be
286
309
  divided by `amaSlope.lookbackBars`, or marked with
287
310
  `"amaSlopePercentMode": "window"` in `profiles/market_adapter_settings.json`
package/docs/README.md CHANGED
@@ -2,7 +2,7 @@
2
2
 
3
3
  This directory contains the comprehensive technical documentation for the DEXBot2 trading bot. It is designed to guide developers from high-level architecture down to the nuances of fund accounting and state management.
4
4
 
5
- **Version context:** v1.6.8 (released).
5
+ **Version context:** v1.6.10 (released).
6
6
 
7
7
  ---
8
8
 
@@ -211,7 +211,7 @@ While these docs explain the *why*, the *how* lives in the code. See the full [m
211
211
  - **`modules/order/strategy.ts`**: Grid rebalancing, order activation, consolidation, rotation, and spread management
212
212
  - **`modules/order/sync_engine.ts`**: Blockchain synchronization, fill detection, order reconciliation
213
213
  - **`modules/order/genesis_policy.ts`**: Missing-ladder refusal and the `MISSING_GENESIS_POLICY` rebuild/halt decision ([GRID_PRICE_INVARIANT.md](GRID_PRICE_INVARIANT.md))
214
- - **`modules/version_notice.ts`**: Passive installed-vs-published version probe and the single status-line renderer used by `start`/`pm2`/`status`
214
+ - **`modules/version_notice.ts`**: The single version probe and status-line renderer for every entry point (`stat`/`pm2`/`start`/`restart`). Two sources (npm, then GitHub releases), a 12h cache for successes and a 15min backoff for failures, an explicit reason when it cannot answer, and a staged wait in `dexbot stat` ending in "no current version information" rather than silence
215
215
  - **`modules/credit_runtime.ts`**: Bot-scoped debt workflow executor (MPA and credit offer accept/repay/reborrow)
216
216
  - **`modules/cr_planner.ts`**: Shared collateral-ratio math layer for debt-first planning
217
217
  - **`modules/order/utils/math.ts`**: Precision conversions, RMS divergence calculation, fund allocation math
@@ -292,6 +292,33 @@ Pair-specific AMA profiles live in `profiles/market_profiles.json`:
292
292
  }
293
293
  ```
294
294
 
295
+ ## Off-Hour Idle Behavior
296
+
297
+ The adapter only has work once per closed candle, so it stays quiet in between:
298
+
299
+ | Phase | Behavior |
300
+ |-------|----------|
301
+ | Startup | **Sleep-first, before any connection.** A respawned daemon checks whether every active AMA bot already consumed the newest closed candle; if so it sleeps to the next `pollSeconds` boundary (default 3600) without opening a socket, otherwise a catch-up cycle runs immediately. |
302
+ | Per bot, per cycle | **Closed-bucket gate before any fetch.** If the bot already consumed the newest closed bucket and its candle cache covers it (right source, no unresolved gaps, warmup target met), the bot is skipped before the native overlap fetch, the Kibana stale-tail check, and the candle re-serialize. |
303
+ | Between cycles | The BitShares socket is torn down after every cycle; the process sleeps with only an unref'd lock heartbeat. |
304
+
305
+ Both gates fail **open**: any input they cannot evaluate — fresh or unusable state, an interval that differs from the poll cadence (e.g. 2h candles polled hourly), a marker ahead of the clock (clock skew), an active bot with no row or no consumed marker (bootstrap owed), a bot whose last cycle left repair outstanding (`unresolvedGapCount > 0`, or `candleCount < rawKeepCount`, including an unknown count next to a known target) — runs the full cycle instead. Per-bot verdicts are never aggregated, so one lagging bot triggers a catch-up for everyone, and the veto is logged with its reason and bot keys:
306
+
307
+ ```
308
+ Startup: running a catch-up cycle now — no_state_row [broken-bot].
309
+ ```
310
+
311
+ Only bots the adapter would actually process are in scope, so a removed bot's leftover state row cannot keep the daemon awake. `kibanaBackfillCount`/`kibanaGapRepairCount` are deliberately ignored: they are action counts from a cycle that already applied its repair, not owed work.
312
+
313
+ Two deliberate trade-offs:
314
+
315
+ - An active bot that can *never* write state (unresolvable market, persistent pre-persist failure) disables the startup sleep for the whole daemon indefinitely — fail-safe by design, since healthy bots still take the per-bot skip; fixing or deactivating the bot restores the sleep.
316
+ - A config change made *after* the last cycle (e.g. a grown AMA window) waits for the next boundary. That backfill is bounded by one poll period, and no candle can close while the adapter sleeps, so no market value is ever late.
317
+
318
+ One-shot entry points (`--once`, and `runOnceForAma` behind `ama_signal_runner`) always run a full cycle — they exist to produce a computed AMA on demand, not a state-only "skipped" record with null prices.
319
+
320
+ Skipped work is visible in state: skipped bots record `lastCycleSource: "off-hour-skip"` with a fresh `lastCycleAt`, so monitoring can tell an idle-by-design adapter from a dead process. A skip record is a last-known snapshot, not an epoch reset: `amaPrice`, `amaCenterPrice`, `lastCandleTs` and the other data fields keep the values from the last full cycle, and only `lastCycleSource`/`lastCycleAt`/`pendingClosedCandle`/`lastTriggerSuppressedReason` are refreshed. Between-cycle consumers therefore read the most recent computed values rather than a hole.
321
+
295
322
  ## Live Writes and Dry-Run
296
323
 
297
324
  The whitelist controls what the adapter may write. Non-whitelisted bots are
@@ -661,7 +688,7 @@ This uses `dynamicWeights.trend`, `dynamicWeights.slopeOffset`, and
661
688
  weight shift. The whitelist flag is `asymmetricBounds`.
662
689
 
663
690
  ```
664
- slope = average AMA slope percent per bar over the lookback window
691
+ slope = Huber-robust regression of ln(AMA) over the lookback window, in percent per bar
665
692
  slopeOffset = slope normalized to the configured dynamic-weight slope cap
666
693
  asymmetry = min(|slopeOffset| / maxSlopeOffset, 1) × maxAsymmetryFactor
667
694
 
@@ -778,7 +805,7 @@ Main override knobs live in `profiles/market_adapter_settings.json`:
778
805
  | `alpha` | AMA vs Kalman blend |
779
806
  | `dw` | Kalman displacement weighting |
780
807
  | `gain` | Output amplitude |
781
- | `amaSlopePercentMode` | Slope override units: `perBar` for average percent per bar, or `window`/unset for legacy cumulative percent over the lookback |
808
+ | `amaSlopePercentMode` | Slope override units: `perBar` for percent per bar, or `window`/unset for legacy cumulative percent over the lookback |
782
809
  | `amaSlope.lookbackBars` | AMA slope lookback; slope is averaged per bar over this window |
783
810
  | `amaSlope.neutralZonePct` | Dead band around flat average AMA slope |
784
811
  | `amaSlope.maxSlopePct` | Average AMA slope saturation |
@@ -980,6 +1007,7 @@ Important fields in `market_adapter/state/market_adapter_state.json`:
980
1007
  | Field | Meaning |
981
1008
  |-------|---------|
982
1009
  | `meta.updatedAt` | Last completed adapter cycle (ISO timestamp) |
1010
+ | `lastCycleSource` | How the last cycle ended the bot: a fetch source (`native-incremental-overlap`, `kibana-backfill`, …) or `off-hour-skip` when the closed-candle gate skipped the work |
983
1011
  | `meta.metrics.processedBots` | Number of bots evaluated this cycle |
984
1012
  | `meta.metrics.durationMs` | Cycle wall-clock duration in milliseconds |
985
1013
  | `lastCycleAt` | Last cycle timestamp for a bot |
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "dexbot",
3
- "version": "1.6.8",
3
+ "version": "1.6.10",
4
4
  "description": "The first open source trading bot with zero runtime dependencies and a fully adaptive market making strategy.",
5
5
  "main": "dist/modules/dexbot_class.js",
6
6
  "exports": {