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
@@ -9,11 +9,10 @@ import { parseJsonWithComments, sleep, ensureDir } from '../modules/order/utils/
9
9
  import { readGeneralSettings } from '../modules/general_settings.js';
10
10
  import { DEFAULT_CONFIG, MARKET_ADAPTER, NATIVE_CLIENT, API_LIMITS, TIMING } from '../modules/constants.js';
11
11
  import { normalizeBotEntry } from '../modules/bot_settings.js';
12
- import { calculateAMA } from './core/strategies/ama.js';
13
12
  import * as kibanaSource from './inputs/kibana_source.js';
14
13
  import * as kibanaMarketSource from './core/kibana_market_candles.js';
15
14
  import { tradesToCandles, detectMissingCandleTimestamps, fillCandleGaps, detectStaleTail, pruneStaleTail, mergeCandles } from './candle_utils.js';
16
- import { toIntervalLabel } from './interval_utils.js';
15
+ import { toIntervalLabel, bucketStartMs, latestClosedBucketStartMs } from './interval_utils.js';
17
16
  import { loadMarketProfiles } from '../analysis/tradingview/tradingview_uplot_chart_generator.js';
18
17
  import { candleFileForBot as candleFilePathForLabel } from '../analysis/bot_key_utils.js';
19
18
  import { writeJsonAtomic } from './utils/atomic_write.js';
@@ -273,7 +272,6 @@ const DEFAULT_AMA_KEY = String(MARKET_ADAPTER.DEFAULT_AMA_KEY).toUpperCase();
273
272
  const BUILTIN_AMAS = MARKET_ADAPTER.AMAS;
274
273
  const DEFAULT_AMA = MARKET_ADAPTER.AMAS.AMA3;
275
274
  const AMA_KEYWORDS = new Set(['ama', 'ama1', 'ama2', 'ama3', 'ama4']);
276
- const AMA_PRESET_KEYS = ['AMA1', 'AMA2', 'AMA3', 'AMA4'];
277
275
  function normalizeAmaPreset(raw) {
278
276
  const erPeriod = Number(raw?.erPeriod);
279
277
  const fastPeriod = Number(raw?.fastPeriod);
@@ -355,26 +353,29 @@ function resolveErSmoothPeriodForBot(bot) {
355
353
  }
356
354
  return globalErSmoothPeriod;
357
355
  }
358
- function buildAmaComparisonPresets(bot, ctx) {
359
- const profile = findAmaProfileForBot(bot, ctx);
360
- const erSmoothPeriod = resolveErSmoothPeriodForBot(bot);
361
- return AMA_PRESET_KEYS
362
- .map((key) => {
363
- const preset = getAmaPresetForKey(key, profile);
364
- if (!preset)
365
- return null;
366
- return {
367
- name: key,
368
- erPeriod: preset.erPeriod,
369
- fastPeriod: preset.fastPeriod,
370
- slowPeriod: preset.slowPeriod,
371
- erSmoothPeriod,
372
- };
373
- })
374
- .filter(Boolean);
375
- }
376
356
  function getAmaFromProfilesForBot(bot, ctx, cfg) {
357
+ const selected = resolveAmaPresetForBot(bot, ctx, cfg);
358
+ if (!selected)
359
+ return null;
360
+ return {
361
+ enabled: true,
362
+ name: selected.name,
363
+ erPeriod: selected.erPeriod,
364
+ fastPeriod: selected.fastPeriod,
365
+ slowPeriod: selected.slowPeriod,
366
+ erSmoothPeriod: selected.erSmoothPeriod,
367
+ };
368
+ }
369
+ /**
370
+ * Resolve which AMA preset key a bot actually trades on, and with what
371
+ * parameters. Returns null when no preset/profile entry applies.
372
+ *
373
+ * The chosen key rides along as `name` on the returned config so the cycle log
374
+ * and the state snapshot can say "this bot runs AMA2" without re-deriving it.
375
+ */
376
+ function resolveAmaPresetForBot(bot, ctx, cfg) {
377
377
  const profile = findAmaProfileForBot(bot, ctx);
378
+ const erSmoothPeriod = resolveErSmoothPeriodForBot(bot);
378
379
  if (!profile)
379
380
  return null;
380
381
  const rawGridPrice = String(bot?.gridPrice || '').trim().toLowerCase();
@@ -384,26 +385,223 @@ function getAmaFromProfilesForBot(bot, ctx, cfg) {
384
385
  : (isAmaKeyword(rawGridPrice)
385
386
  ? normalizeAmaKey(rawGridPrice)
386
387
  : (overrideDefaultAmaKey || normalizeAmaKey(profile?.defaultAma)));
387
- const selected = normalizeAmaPreset(profile?.amas?.[requestedKey])
388
- || normalizeAmaPreset(profile?.amas?.[overrideDefaultAmaKey || DEFAULT_AMA_KEY])
389
- || getAmaPresetForKey(requestedKey, profile)
390
- || getAmaPresetForKey(overrideDefaultAmaKey || DEFAULT_AMA_KEY, profile);
388
+ // Keep the (key, preset) pair so the effective preset name is the one that
389
+ // actually won the fallback chain, not merely the one that was requested.
390
+ const selected = pairAmaKey(requestedKey, normalizeAmaPreset(profile?.amas?.[requestedKey]))
391
+ || pairAmaKey(overrideDefaultAmaKey || DEFAULT_AMA_KEY, normalizeAmaPreset(profile?.amas?.[overrideDefaultAmaKey || DEFAULT_AMA_KEY]))
392
+ || pairAmaKey(requestedKey, getAmaPresetForKey(requestedKey, profile))
393
+ || pairAmaKey(overrideDefaultAmaKey || DEFAULT_AMA_KEY, getAmaPresetForKey(overrideDefaultAmaKey || DEFAULT_AMA_KEY, profile));
391
394
  if (!selected)
392
395
  return null;
393
396
  return {
394
397
  enabled: true,
395
- erPeriod: selected.erPeriod,
396
- fastPeriod: selected.fastPeriod,
397
- slowPeriod: selected.slowPeriod,
398
+ name: selected.key,
399
+ erPeriod: selected.preset.erPeriod,
400
+ fastPeriod: selected.preset.fastPeriod,
401
+ slowPeriod: selected.preset.slowPeriod,
402
+ erSmoothPeriod,
398
403
  };
399
404
  }
405
+ function pairAmaKey(key, preset) {
406
+ if (!preset)
407
+ return null;
408
+ return { key: String(key), preset };
409
+ }
400
410
  function sleepUntilAlignedBoundary(pollSeconds, referenceNowMs = Date.now(), nowMs = Date.now()) {
401
- const intervalMs = Math.max(1, Math.floor(Number(pollSeconds) || 0)) * 1000;
411
+ const normalizedPollSeconds = Math.max(1, Math.floor(Number(pollSeconds) || 0));
412
+ const intervalMs = normalizedPollSeconds * 1000;
402
413
  const bufferMs = 1000;
403
- const targetBoundaryMs = Math.floor(Number(referenceNowMs) / intervalMs) * intervalMs + intervalMs;
414
+ // The bucket containing the reference instant; its immediate successor is
415
+ // the boundary to align to. Shared bucket helper keeps this on the same
416
+ // grid as the closed-candle gate and the startup sleep.
417
+ const referenceBucketMs = bucketStartMs(referenceNowMs, normalizedPollSeconds);
418
+ // null (unusable reference clock/interval) means "do not wait": treat the
419
+ // reference as the first boundary, so the delay collapses to the buffer
420
+ // floor below. Never interpret it as an extra period, which would postpone
421
+ // a cycle instead of running it.
422
+ const targetBoundaryMs = (referenceBucketMs === null ? 0 : referenceBucketMs) + intervalMs;
404
423
  const delayMs = targetBoundaryMs - Number(nowMs) + bufferMs;
405
424
  return Math.max(bufferMs, delayMs);
406
425
  }
426
+ /**
427
+ * Sleep-first startup decision for the daemon.
428
+ *
429
+ * Returns `{ delayMs, veto }`: `delayMs` is how long to wait before the first
430
+ * cycle (0 = run a catch-up cycle now); `veto` is null when the adapter may
431
+ * sleep, otherwise `{ reason, botKeys }` saying why not. The wait uses the
432
+ * SAME poll boundary the loop aligns to (sleepUntilAlignedBoundary with
433
+ * cfg.pollSeconds, default 3600s), so the timing setting is honoured, not
434
+ * hardcoded.
435
+ *
436
+ * `veto` is non-null — and `delayMs` 0 — when:
437
+ * - state is fresh/empty (first run, cleared state — bootstrap lives in the
438
+ * cycle),
439
+ * - no in-scope bot has a consumed closed-candle marker yet,
440
+ * - ANY in-scope bot's consumed marker is not exactly the newest closed bucket
441
+ * (older = that bot still owes a cycle; newer = the clocks disagree, so do
442
+ * not trust the marker). Evaluated per bot, never aggregated: one lagging
443
+ * bot is invisible behind a max() over the others, and that bot is exactly
444
+ * what a catch-up cycle is for.
445
+ * - the candle interval is not the poll cadence, or the clock cannot be
446
+ * evaluated,
447
+ * - an active bot's last cycle left repair work still outstanding
448
+ * (unresolved gaps, or a cache shorter than its own warmup target),
449
+ * - an active bot has never been processed (no state row, or no consumed
450
+ * marker) — its bootstrap is still owed,
451
+ * - the active bot list cannot be read (then every state entry counts).
452
+ *
453
+ * The interval guard matters: the newest closed bucket is computed on the
454
+ * poll grid, while the markers in state are candle-bucket starts. With a
455
+ * mismatch (e.g. 2h candles polled hourly) the two grids only coincide by
456
+ * accident, and "coincide" here would delay a real cycle by up to one poll
457
+ * period. Refuse to sleep unless the grids are identical, i.e. unless one
458
+ * cycle per poll actually is one cycle per candle.
459
+ *
460
+ * One grid for every bot is correct because `intervalSeconds` is not in the
461
+ * per-pair/per-bot override whitelist, so all bots in a cycle share a bucket
462
+ * size. If that ever changes, the comparison has to become per bot.
463
+ *
464
+ * Otherwise it returns the wait until the next poll boundary. Mid-hour
465
+ * respawns (the common case: wrapper restart, crash recovery) therefore sleep
466
+ * instead of running a full cycle that the closed-candle gate would discard
467
+ * anyway. That wait is always shorter than one poll period, so at most one
468
+ * boundary is ever passed over: a candle that closes during the sleep is
469
+ * picked up by the very next cycle, never skipped.
470
+ *
471
+ * Only entries for bots the adapter would actually process are considered
472
+ * (activeBotKeys). A removed bot's leftover row, or a fixed-price bot, must
473
+ * not be able to defeat the sleep for everyone else — such an entry either
474
+ * has no marker at all or a marker that is months old. An active bot with NO
475
+ * row is treated exactly like an active bot with a row but no marker: both owe
476
+ * a bootstrap, so both veto the sleep and that bot goes live on the next cycle
477
+ * rather than up to a poll period later.
478
+ *
479
+ * Repair work is judged from the state entry, which records how the previous
480
+ * cycle ended. Two of its fields are deliberately distinguished:
481
+ *
482
+ * - `unresolvedGapCount` is a STANDING condition — it is measured on the final
483
+ * candle set, so a non-zero value means gaps are still missing right now.
484
+ * - `candleCount < rawKeepCount` is standing too: the cache has not reached
485
+ * the bot's own warmup target.
486
+ *
487
+ * `kibanaBackfillCount` is deliberately NOT consulted. It is an action count —
488
+ * how many candles the last completed cycle happened to fetch — and that cycle
489
+ * already applied them. A non-zero value means "repair was needed and was
490
+ * done", not "repair is owed". Because a skip carries the persisted entry
491
+ * forward, treating it as outstanding would keep vetoing the sleep after every
492
+ * backfill until some full cycle happened to rewrite the field with a zero.
493
+ * Cache shortness is the real signal, and it is checked directly above. The
494
+ * standing verdict is computed by evaluateStateRepairVeto in
495
+ * market_adapter_service.ts, immediately before the candle-file mirror
496
+ * (candleFileCoversClosedBucket), so a new standing signal is added once.
497
+ *
498
+ * None of this can see a config change made after that cycle (a grown AMA
499
+ * window, for instance): the backfill for that is then deferred to the next
500
+ * boundary, bounded by one poll period. Reading the state entry costs no extra
501
+ * I/O — no candle file is re-read and no connection is opened (the startup
502
+ * decision reads bots.json to build the active list, and each cycle reads it
503
+ * again).
504
+ *
505
+ * Known consequence of the "active bot with no row vetoes" rule: an active bot
506
+ * that can never reach a state write (unresolvable market, persistent
507
+ * pre-persist failure) keeps the sleep disabled for the whole daemon. That is
508
+ * intentional and fail-safe — healthy bots still take the in-cycle off-hour
509
+ * skip, so only the startup sleep is lost — and the veto is reported with its
510
+ * reason and bot keys so the situation is visible instead of silent.
511
+ */
512
+ function evaluateStartupSleep(cfg, state, nowMs = Date.now(), activeBotKeys = null) {
513
+ const vetoes = {};
514
+ const veto = (reason, key) => {
515
+ if (key == null)
516
+ return;
517
+ if (!vetoes[reason])
518
+ vetoes[reason] = [];
519
+ vetoes[reason].push(key);
520
+ };
521
+ // Whole-fleet refusals: the condition is about the configuration or the
522
+ // inputs, not about a particular bot, so there is nothing to attribute and
523
+ // botKeys stays empty. Per-bot refusals are collected in `vetoes` by the
524
+ // loop below and returned with their bot list. Deliberately NOT reading
525
+ // `vetoes[reason]` here — that would silently return another bot's keys if
526
+ // a denied() call were ever made after the loop has populated it.
527
+ const denied = (reason) => ({ delayMs: 0, veto: { reason, botKeys: [] } });
528
+ // Deliberate normalization asymmetry: pollSeconds is clamped to >=1 because
529
+ // it is the grid the sleep aligns to, while intervalSeconds is left as a
530
+ // bare floor so an invalid interval (0, negative, NaN) can NEVER equal the
531
+ // clamped poll value and therefore always takes interval_mismatch below —
532
+ // i.e. runs a catch-up cycle. Do not "simplify" by clamping both: that
533
+ // would let an unconfigured interval match and authorize a sleep on a grid
534
+ // the persisted markers were not written on.
535
+ const pollSeconds = Math.max(1, Math.floor(Number(cfg?.pollSeconds) || 0));
536
+ const intervalSeconds = Math.floor(Number(cfg?.intervalSeconds) || 0);
537
+ if (intervalSeconds !== pollSeconds)
538
+ return denied('interval_mismatch');
539
+ const now = Number(nowMs);
540
+ if (!Number.isFinite(now) || now <= 0)
541
+ return denied('clock_unusable');
542
+ const bots = state?.bots;
543
+ if (!bots || typeof bots !== 'object')
544
+ return denied('state_unusable');
545
+ // An empty active-bot list means the adapter has nothing to do; do not
546
+ // interpret it as "unknown scope" and fall back to scanning every row.
547
+ if (Array.isArray(activeBotKeys) && activeBotKeys.length === 0)
548
+ return denied('no_active_bots');
549
+ // Newest fully closed bucket: its start. A cycle that consumed it has
550
+ // done all the work available until the next bucket closes. Shared helper
551
+ // so the startup sleep and the in-cycle gate agree by construction.
552
+ const latestClosed = latestClosedBucketStartMs(now, pollSeconds);
553
+ if (latestClosed === null)
554
+ return denied('clock_unusable');
555
+ // With a known active set, every one of those bots is judged on its own.
556
+ // Unknown set (bot list unreadable) falls back to the state rows present.
557
+ const scope = Array.isArray(activeBotKeys) ? activeBotKeys : Object.keys(bots);
558
+ if (scope.length === 0)
559
+ return denied('no_state_rows');
560
+ for (const key of scope) {
561
+ const entry = bots[key];
562
+ // An active bot with no state row at all still owes its first cycle.
563
+ if (!entry || typeof entry !== 'object') {
564
+ veto('no_state_row', key);
565
+ continue;
566
+ }
567
+ const consumed = Number(entry.lastClosedCandleTs || 0);
568
+ // No consumed marker yet: this bot still owes a bootstrap/warmup cycle.
569
+ if (!Number.isFinite(consumed) || consumed <= 0) {
570
+ veto('no_consumed_marker', key);
571
+ continue;
572
+ }
573
+ // Per bot, never aggregated across bots: one lagging bot is exactly the
574
+ // reason a catch-up cycle is needed, and a max() would hide it.
575
+ if (consumed !== latestClosed) {
576
+ veto(consumed < latestClosed ? 'behind_latest_closed_candle' : 'marker_ahead_of_clock', key);
577
+ continue;
578
+ }
579
+ // Standing repair conditions, as measured by the previous cycle. Shared
580
+ // with candleFileCoversClosedBucket's state-side mirror so the two gates
581
+ // cannot drift apart.
582
+ const repairReason = evaluateStateRepairVeto(entry);
583
+ if (repairReason) {
584
+ veto(repairReason, key);
585
+ continue;
586
+ }
587
+ }
588
+ if (Object.keys(vetoes).length > 0) {
589
+ // Every distinct reason is reported, so a permanent veto (an active bot
590
+ // that can never be persisted) is diagnosable from the log alone.
591
+ const reason = Object.keys(vetoes).sort().join('+');
592
+ return { delayMs: 0, veto: { reason, botKeys: [...new Set(Object.values(vetoes).flat())] } };
593
+ }
594
+ return { delayMs: sleepUntilAlignedBoundary(pollSeconds, now, now), veto: null };
595
+ }
596
+ /**
597
+ * Numeric form of evaluateStartupSleep: the wait before the daemon's first
598
+ * cycle, or 0 to run a catch-up cycle now. The decision rules — and the reasons
599
+ * it can refuse — are documented there; this wrapper exists so callers that
600
+ * only need the wait do not have to unpack a verdict object.
601
+ */
602
+ function computeStartupDelayMs(cfg, state, nowMs = Date.now(), activeBotKeys = null) {
603
+ return evaluateStartupSleep(cfg, state, nowMs, activeBotKeys).delayMs;
604
+ }
407
605
  function withRetries(fn, attempts, baseDelayMs, label) {
408
606
  return (async () => {
409
607
  let lastErr;
@@ -644,23 +842,53 @@ function computeCandleStaleness(lastCandleTs, maxStaleHours) {
644
842
  const staleAgeHours = Number.isFinite(staleAgeMs) ? (staleAgeMs / 3600000) : null;
645
843
  return { staleData, staleAgeHours };
646
844
  }
845
+ /**
846
+ * Resolve the AMA configuration a bot trades on.
847
+ *
848
+ * Precedence, as implemented: when a market profile applies for the pair, the
849
+ * preset is chosen from the profile by the bot's `gridPrice` keyword, else the
850
+ * profile/`AMA3` default (a profile entry always wins over the bot's numeric
851
+ * `ama` block). Without a profile, the bot's own `ama` numbers are used, with
852
+ * the `gridPrice` keyword preset filling any missing period and AMA3 as the last
853
+ * resort.
854
+ *
855
+ * The winning preset key — or 'custom' when the numbers came from the bot's own
856
+ * `ama` block — rides along as `name`, so the cycle log and the state snapshot
857
+ * can state which AMA this bot runs without re-deriving it.
858
+ *
859
+ * `enabled` is a derived invariant, always true here. `gridPrice` is the single
860
+ * switch that decides whether a bot is AMA-driven — `usesAmaGridPrice()` reads
861
+ * it in the bot runtime, the maintenance runtime and the launcher — so an
862
+ * `ama.enabled` flag could only ever disagree with them. It used to: this
863
+ * function honoured it on the profile-less path and hardcoded `true` on the
864
+ * profile path, and because the bot side ignores the flag, honouring it froze
865
+ * the published center while the bot kept trading on it. Callers must gate AMA
866
+ * work on `usesAmaGridPrice(bot)`.
867
+ */
647
868
  function resolveAmaForBot(bot, ctx = null, cfg = null) {
648
869
  const raw = (bot && typeof bot.ama === 'object' && bot.ama !== null) ? bot.ama : {};
649
870
  const erSmoothPeriod = resolveErSmoothPeriodForBot(bot);
650
871
  const fromProfiles = getAmaFromProfilesForBot(bot, ctx, cfg);
651
- if (fromProfiles) {
652
- fromProfiles.erSmoothPeriod = erSmoothPeriod;
872
+ if (fromProfiles)
653
873
  return fromProfiles;
654
- }
655
874
  const amaCfg = {
656
875
  erPeriod: Number(raw.erPeriod),
657
876
  fastPeriod: Number(raw.fastPeriod),
658
877
  slowPeriod: Number(raw.slowPeriod),
659
878
  erSmoothPeriod,
660
- enabled: raw.enabled !== false,
879
+ enabled: true,
880
+ name: 'custom',
661
881
  };
882
+ // Which preset the periods came from — tracked so the reported name
883
+ // describes the SOURCE, not merely the values (a bot that hand-writes the
884
+ // AMA3 numbers is still its own configuration, not "AMA3").
885
+ const botSuppliedPeriod = Number.isFinite(Number(raw.erPeriod))
886
+ || Number.isFinite(Number(raw.fastPeriod))
887
+ || Number.isFinite(Number(raw.slowPeriod));
888
+ let presetKey = null;
662
889
  if (isAmaKeyword(bot?.gridPrice)) {
663
- const preset = getAmaPresetForKey(normalizeAmaKey(bot.gridPrice), null);
890
+ const key = normalizeAmaKey(bot.gridPrice);
891
+ const preset = getAmaPresetForKey(key, null);
664
892
  if (preset) {
665
893
  if (!Number.isFinite(amaCfg.erPeriod))
666
894
  amaCfg.erPeriod = preset.erPeriod;
@@ -668,6 +896,7 @@ function resolveAmaForBot(bot, ctx = null, cfg = null) {
668
896
  amaCfg.fastPeriod = preset.fastPeriod;
669
897
  if (!Number.isFinite(amaCfg.slowPeriod))
670
898
  amaCfg.slowPeriod = preset.slowPeriod;
899
+ presetKey = key;
671
900
  }
672
901
  }
673
902
  if (!Number.isFinite(amaCfg.erPeriod) || amaCfg.erPeriod < 1)
@@ -676,6 +905,9 @@ function resolveAmaForBot(bot, ctx = null, cfg = null) {
676
905
  amaCfg.fastPeriod = DEFAULT_AMA.fastPeriod;
677
906
  if (!Number.isFinite(amaCfg.slowPeriod) || amaCfg.slowPeriod < 1)
678
907
  amaCfg.slowPeriod = DEFAULT_AMA.slowPeriod;
908
+ // Periods the bot supplied itself win, so the config is 'custom'; otherwise
909
+ // the name is the preset the periods came from (keyword, else the default).
910
+ amaCfg.name = botSuppliedPeriod ? 'custom' : (presetKey || DEFAULT_AMA_KEY);
679
911
  if (amaCfg.fastPeriod > amaCfg.slowPeriod) {
680
912
  const t = amaCfg.fastPeriod;
681
913
  amaCfg.fastPeriod = amaCfg.slowPeriod;
@@ -690,26 +922,39 @@ function pruneCandles(candles, keepCount) {
690
922
  return candles;
691
923
  return candles.slice(candles.length - keepCount);
692
924
  }
693
- function calcAmaComparison(candles, bot = null, ctx = null) {
694
- const closes = (candles || []).map((c) => Number(c?.[4])).filter((v) => Number.isFinite(v) && v > 0);
695
- const out = [];
696
- const presets = buildAmaComparisonPresets(bot, ctx);
697
- for (const p of presets) {
698
- const minNeeded = p.erPeriod + 1;
699
- if (closes.length < minNeeded) {
700
- out.push({ ...p, value: null, ok: false });
701
- continue;
702
- }
703
- const values = calculateAMA(closes, {
704
- erPeriod: p.erPeriod,
705
- fastPeriod: p.fastPeriod,
706
- slowPeriod: p.slowPeriod,
707
- erSmoothPeriod: p.erSmoothPeriod,
708
- });
709
- const value = values[values.length - 1];
710
- out.push({ ...p, value: Number.isFinite(value) ? value : null, ok: Number.isFinite(value) });
925
+ /**
926
+ * Build the per-bot AMA record that is logged and persisted in the state file.
927
+ *
928
+ * It reports the ONE AMA the bot actually trades on — the value the cycle has
929
+ * already computed as `amaValues` — instead of re-running `calculateAMA` for the
930
+ * AMA1..AMA4 preset sweep. Those four extra passes cost ~0.3 ms each per bot per
931
+ * hour and fed nothing but the old "AMA compare:" log line: the presets are
932
+ * research knobs, not a signal, and the bot's price always came from its own
933
+ * configured parameters. So the comparison was 4 duplications of work whose
934
+ * result no decision, log consumer or dashboard ever read.
935
+ *
936
+ * The array shape (one entry, same fields) is kept so the state schema and the
937
+ * cycle log stay stable; the field is still called `amaComparison` in the
938
+ * persisted state for backwards compatibility with existing snapshots.
939
+ */
940
+ function buildAmaRecord(botAma, amaPrice) {
941
+ const erPeriod = Number(botAma?.erPeriod);
942
+ const fastPeriod = Number(botAma?.fastPeriod);
943
+ const slowPeriod = Number(botAma?.slowPeriod);
944
+ const erSmoothPeriod = Number(botAma?.erSmoothPeriod);
945
+ if (!Number.isFinite(erPeriod) || !Number.isFinite(fastPeriod) || !Number.isFinite(slowPeriod)) {
946
+ return [];
711
947
  }
712
- return out;
948
+ const value = Number(amaPrice);
949
+ return [{
950
+ name: String(botAma?.name || 'active'),
951
+ erPeriod,
952
+ fastPeriod,
953
+ slowPeriod,
954
+ erSmoothPeriod: Number.isFinite(erSmoothPeriod) ? erSmoothPeriod : 0,
955
+ value: Number.isFinite(value) ? value : null,
956
+ ok: Number.isFinite(value),
957
+ }];
713
958
  }
714
959
  async function fetchNativeTradesSince(poolId, sinceMs, pageLimit, maxPages) {
715
960
  const { BitShares } = getBitsharesClient();
@@ -956,7 +1201,7 @@ function writeBotDynamicGrid(botKey, gridCenterPrice, options = {}) {
956
1201
  return false;
957
1202
  }
958
1203
  }
959
- import { MarketAdapterService, AMA_SLOPE_PERCENT_MODE_PER_BAR, normalizeAmaSlopePercentMode, convertSlopePercentToPerBar, } from './core/market_adapter_service.js';
1204
+ import { MarketAdapterService, AMA_SLOPE_PERCENT_MODE_PER_BAR, normalizeAmaSlopePercentMode, convertSlopePercentToPerBar, evaluateStateRepairVeto, } from './core/market_adapter_service.js';
960
1205
  import { getErrorMessage } from '../modules/utils/errors.js';
961
1206
  const adapterService = new MarketAdapterService({
962
1207
  resolveBotContext,
@@ -979,7 +1224,7 @@ const adapterService = new MarketAdapterService({
979
1224
  pruneStaleTail,
980
1225
  mergeCandles,
981
1226
  pruneCandles,
982
- calcAmaComparison,
1227
+ buildAmaRecord,
983
1228
  writeGridResetTrigger,
984
1229
  writeBotDynamicGrid,
985
1230
  isBotWhitelisted,
@@ -1085,6 +1330,18 @@ async function runOnce(cfg, state, contextCache) {
1085
1330
  });
1086
1331
  continue;
1087
1332
  }
1333
+ // Off-hour skip: nothing to compute, so log one compact line
1334
+ // instead of the full signal block (which would print n/a for
1335
+ // every field and bury the hourly cycle in noise).
1336
+ if (r.source === 'off-hour-skip') {
1337
+ log(cfg, `skip (no new closed candle, last processed ${Number.isFinite(r.lastClosedCandleTs) ? new Date(r.lastClosedCandleTs).toISOString() : 'n/a'})`);
1338
+ results.push({
1339
+ botName: bot.name,
1340
+ botKey: bot.botKey,
1341
+ ...r,
1342
+ });
1343
+ continue;
1344
+ }
1088
1345
  const amaText = Number.isFinite(r.amaPrice) ? r.amaPrice.toFixed(8) : 'n/a';
1089
1346
  const prevCenterText = Number.isFinite(r.previousCenterPrice) ? r.previousCenterPrice.toFixed(8) : 'n/a';
1090
1347
  const deltaText = Number.isFinite(r.deltaPercent) ? `${r.deltaPercent.toFixed(3)}%` : 'n/a';
@@ -1148,7 +1405,7 @@ async function runOnce(cfg, state, contextCache) {
1148
1405
  const erSmoothText = Number.isFinite(Number(a.erSmoothPeriod)) ? `/es${fixedTo(a.erSmoothPeriod, 0)}` : '';
1149
1406
  return `${a.name}[${a.erPeriod}/${a.fastPeriod}/${a.slowPeriod}${erSmoothText}]=${val}`;
1150
1407
  });
1151
- log(cfg, ` AMA compare: ${parts.join(' | ')}`);
1408
+ log(cfg, ` AMA active: ${parts.join(' | ')}`);
1152
1409
  }
1153
1410
  results.push({
1154
1411
  botName: bot.name,
@@ -1256,6 +1513,53 @@ async function main() {
1256
1513
  log(cfg, 'Dry run: config validation + lock acquisition OK (no network, no writes).');
1257
1514
  return 0;
1258
1515
  }
1516
+ // Read state before the sleep: the lock guarantees no other adapter can
1517
+ // rewrite it in the meantime, and the same object is then used by the
1518
+ // first cycle, so the file is parsed exactly once per start.
1519
+ const state = loadJson(STATE_FILE, { meta: {}, bots: {} });
1520
+ const contextCache = new Map();
1521
+ // Sleep-first startup, decided BEFORE the first connection: a respawned
1522
+ // daemon (wrapper restart, crash recovery, manual start) must not run a
1523
+ // full cycle immediately — mid-hour that cycle can only hit the
1524
+ // closed-candle gate after paying the chain handshake + per-bot native
1525
+ // fetch. Instead, align to the SAME boundary the loop uses
1526
+ // (pollSeconds, default 3600s) and only run early when some active bot
1527
+ // still owes a cycle.
1528
+ //
1529
+ // Ordering matters: connecting first and sleeping afterwards would hold
1530
+ // an idle socket for the whole hour, which is exactly what the
1531
+ // per-cycle connect/disconnect below exists to avoid. The lock is
1532
+ // already held (and its heartbeat is unref'd but armed), so a sleeping
1533
+ // adapter still looks alive to the watchdog, which decides staleness by
1534
+ // holder liveness rather than by lock age.
1535
+ if (!cfg.once) {
1536
+ // Only bots the adapter would actually process may veto the sleep:
1537
+ // a removed bot's leftover state row (or a fixed-price bot) must
1538
+ // not force a full cycle on every restart. If the bot list cannot be
1539
+ // read, every state row is judged instead (conservative).
1540
+ let activeAmaBotKeys = null;
1541
+ try {
1542
+ activeAmaBotKeys = loadActiveBots()
1543
+ .filter((bot) => usesAmaGridPrice(bot))
1544
+ .map((bot) => bot.botKey);
1545
+ }
1546
+ catch (_) {
1547
+ activeAmaBotKeys = null;
1548
+ }
1549
+ const verdict = evaluateStartupSleep(cfg, state, Date.now(), activeAmaBotKeys);
1550
+ if (verdict.delayMs > 0) {
1551
+ log(cfg, `Startup: every active bot consumed the newest closed candle and no repair is outstanding — sleeping ${(verdict.delayMs / 1000).toFixed(0)}s until the next ${cfg.pollSeconds}s boundary (no connection held).`);
1552
+ await sleep(verdict.delayMs);
1553
+ }
1554
+ else {
1555
+ // Name the reason and the bots: a veto caused by one
1556
+ // unprocessable bot would otherwise look like "the adapter just
1557
+ // never sleeps" with nothing in the log to explain it.
1558
+ const v = verdict.veto || { reason: 'unknown', botKeys: [] };
1559
+ const who = v.botKeys.length > 0 ? ` [${v.botKeys.join(', ')}]` : '';
1560
+ log(cfg, `Startup: running a catch-up cycle now — ${v.reason}${who}.`);
1561
+ }
1562
+ }
1259
1563
  {
1260
1564
  const maxRetries = 5;
1261
1565
  let lastErr = null;
@@ -1281,8 +1585,6 @@ async function main() {
1281
1585
  }
1282
1586
  }
1283
1587
  log(cfg, 'Connected to BitShares');
1284
- const state = loadJson(STATE_FILE, { meta: {}, bots: {} });
1285
- const contextCache = new Map();
1286
1588
  if (cfg.once) {
1287
1589
  const run = await runOnce(cfg, state, contextCache);
1288
1590
  const allProcessedFailed = run.metrics.processedBots > 0 && run.metrics.successBots === 0;
@@ -1291,8 +1593,12 @@ async function main() {
1291
1593
  while (true) {
1292
1594
  const started = Date.now();
1293
1595
  log(cfg, `\n[cycle ${new Date(started).toISOString()}]`);
1294
- // Connect for this cycle using the lightweight native read-only client.
1295
- // Tear down after runOnce so the connection never sits idle.
1596
+ // Connect for this cycle using the lightweight native read-only
1597
+ // client, and tear it down after runOnce so the connection never
1598
+ // sits idle. A socket that outlives its cycle can be half-open when
1599
+ // the next one starts (the peer drops it with no close frame, so
1600
+ // readyState stays 1 and nothing notices); the per-cycle handshake
1601
+ // re-validates chain id and api id before any RPC goes out on it.
1296
1602
  try {
1297
1603
  const { connectClient } = getBitsharesClient();
1298
1604
  await connectClient();
@@ -1307,6 +1613,16 @@ async function main() {
1307
1613
  disconnectClient();
1308
1614
  }
1309
1615
  catch (_) { }
1616
+ const cycleMs = Date.now() - started;
1617
+ const pollMs = Math.max(1, Number(cfg.pollSeconds) || 0) * 1000;
1618
+ if (cycleMs >= pollMs) {
1619
+ // The cadence is slipping: this cycle alone consumed a full
1620
+ // period, so the next one starts immediately (1000ms floor) and
1621
+ // the backlog drains one cycle at a time. Surfaced explicitly,
1622
+ // because a silent backlog is indistinguishable from an adapter
1623
+ // that "runs every hour" in the log.
1624
+ logger.warn(`Cycle took ${(cycleMs / 1000).toFixed(0)}s, at or beyond the ${cfg.pollSeconds}s poll period — running the next cycle immediately to catch up.`);
1625
+ }
1310
1626
  const sleepMs = sleepUntilAlignedBoundary(cfg.pollSeconds, started, Date.now());
1311
1627
  await sleep(sleepMs);
1312
1628
  }
@@ -1323,5 +1639,5 @@ if (process.argv[1] && import.meta.url === pathToFileURL(process.argv[1]).href)
1323
1639
  process.exit(1);
1324
1640
  });
1325
1641
  }
1326
- export { main, runOnceForAma, DEFAULT_AMA, DEFAULTS, calculateBotThreshold, calcAmaComparison, computeCandleStaleness, normalizeMarketSource, sleepUntilAlignedBoundary, resolveAmaForBot, resolveDeltaThresholdPercentFromGeneralSettings, resolveAmaSlopeDeltaThresholdPercentFromGeneralSettings, applyRuntimeDefaultsFromGeneralSettings, resolveBotCfg, usesAmaGridPrice, isBotWhitelisted, isBotDynamicWeightWhitelisted, isBotAsymmetricBoundsWhitelisted, _resetCycleCache, writeCenterSnapshot, writeBotDynamicGrid, writeGridResetTrigger, mergeGridResetMetadataFromDynamicGrid, normalizeNativeMarketHistoryCandles, fetchNativeMarketHistorySince, setBitsharesClientForTests as _setBitsharesClientForTests, loadMarketAdapterSettings, findPairForBot };
1642
+ export { main, runOnceForAma, DEFAULT_AMA, DEFAULTS, calculateBotThreshold, buildAmaRecord, computeCandleStaleness, normalizeMarketSource, sleepUntilAlignedBoundary, computeStartupDelayMs, evaluateStartupSleep, resolveAmaForBot, resolveDeltaThresholdPercentFromGeneralSettings, resolveAmaSlopeDeltaThresholdPercentFromGeneralSettings, applyRuntimeDefaultsFromGeneralSettings, resolveBotCfg, usesAmaGridPrice, isBotWhitelisted, isBotDynamicWeightWhitelisted, isBotAsymmetricBoundsWhitelisted, _resetCycleCache, writeCenterSnapshot, writeBotDynamicGrid, writeGridResetTrigger, mergeGridResetMetadataFromDynamicGrid, normalizeNativeMarketHistoryCandles, fetchNativeMarketHistorySince, setBitsharesClientForTests as _setBitsharesClientForTests, loadMarketAdapterSettings, findPairForBot };
1327
1643
  //# sourceMappingURL=market_adapter.js.map
@@ -4,7 +4,7 @@
4
4
  * Canonical import point for tests that need internal market-adapter helpers.
5
5
  * Keeps test dependencies centralized and explicit.
6
6
  */
7
- import { writeCenterSnapshot, writeBotDynamicGrid, writeGridResetTrigger, sleepUntilAlignedBoundary } from './market_adapter.js';
7
+ import { writeCenterSnapshot, writeBotDynamicGrid, writeGridResetTrigger, sleepUntilAlignedBoundary, computeStartupDelayMs, evaluateStartupSleep } from './market_adapter.js';
8
8
  import { resolveAsset, resolveBotContext, resolveMarketSourceForBot } from './utils/chain.js';
9
- export { writeCenterSnapshot, writeBotDynamicGrid, writeGridResetTrigger, sleepUntilAlignedBoundary, resolveMarketSourceForBot, resolveAsset, resolveBotContext };
9
+ export { writeCenterSnapshot, writeBotDynamicGrid, writeGridResetTrigger, sleepUntilAlignedBoundary, computeStartupDelayMs, evaluateStartupSleep, resolveMarketSourceForBot, resolveAsset, resolveBotContext };
10
10
  //# sourceMappingURL=test_helpers.d.ts.map
@@ -5,7 +5,7 @@
5
5
  * Canonical import point for tests that need internal market-adapter helpers.
6
6
  * Keeps test dependencies centralized and explicit.
7
7
  */
8
- import { writeCenterSnapshot, writeBotDynamicGrid, writeGridResetTrigger, sleepUntilAlignedBoundary, } from './market_adapter.js';
8
+ import { writeCenterSnapshot, writeBotDynamicGrid, writeGridResetTrigger, sleepUntilAlignedBoundary, computeStartupDelayMs, evaluateStartupSleep, } from './market_adapter.js';
9
9
  import { resolveAsset, resolveBotContext, resolveMarketSourceForBot, } from './utils/chain.js';
10
- export { writeCenterSnapshot, writeBotDynamicGrid, writeGridResetTrigger, sleepUntilAlignedBoundary, resolveMarketSourceForBot, resolveAsset, resolveBotContext };
10
+ export { writeCenterSnapshot, writeBotDynamicGrid, writeGridResetTrigger, sleepUntilAlignedBoundary, computeStartupDelayMs, evaluateStartupSleep, resolveMarketSourceForBot, resolveAsset, resolveBotContext };
11
11
  //# sourceMappingURL=test_helpers.js.map
@@ -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);