dexbot 1.6.14 → 1.6.16

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 (134) hide show
  1. package/CHANGELOG.md +60 -4
  2. package/README.md +4 -4
  3. package/analysis/README.md +6 -6
  4. package/analysis/tradingview/README.md +2 -1
  5. package/claw/README.md +7 -7
  6. package/claw/docs/DEXBOT2_TUNING_CHEAT_SHEET.md +3 -2
  7. package/claw/modules/chain_queries.ts +3 -3
  8. package/claw/package.json +1 -1
  9. package/claw/runtimes/openclaw-plugin/openclaw.plugin.json +1 -1
  10. package/claw/runtimes/openclaw-plugin/package.json +1 -1
  11. package/dist/analysis/ama_fitting/fetch_lp_candles.js +8 -1
  12. package/dist/analysis/ama_fitting/optimizer_high_resolution.d.ts +50 -1
  13. package/dist/analysis/ama_fitting/optimizer_high_resolution.js +33 -7
  14. package/dist/analysis/bot_fitting/backtest_bot_fitting.d.ts +8 -6
  15. package/dist/analysis/bot_fitting/backtest_bot_fitting.js +8 -10
  16. package/dist/analysis/bot_key_utils.js +9 -7
  17. package/dist/analysis/chart_utils.d.ts +9 -2
  18. package/dist/analysis/chart_utils.js +51 -1
  19. package/dist/analysis/tradingview/tradingview_uplot_chart_generator.d.ts +2 -1
  20. package/dist/analysis/tradingview/tradingview_uplot_chart_generator.js +99 -11
  21. package/dist/analysis/trend_detection/dynamic_weight_chart_generator.js +57 -4
  22. package/dist/analysis/trend_detection/kalman_chart_generator.js +1 -0
  23. package/dist/analysis/trend_detection/regime_chart_generator.js +1 -1
  24. package/dist/analysis/trend_detection/volatility_chart_generator.js +1 -0
  25. package/dist/dexbot.js +112 -141
  26. package/dist/market_adapter/core/strategies/dynamic_weight_series.js +26 -11
  27. package/dist/market_adapter/inputs/fetch_book_data.js +36 -12
  28. package/dist/market_adapter/inputs/fetch_lp_data.d.ts +6 -0
  29. package/dist/market_adapter/inputs/fetch_lp_data.js +65 -19
  30. package/dist/market_adapter/inputs/kibana_feed_source.js +45 -12
  31. package/dist/market_adapter/inputs/window_cache.d.ts +14 -1
  32. package/dist/market_adapter/inputs/window_cache.js +53 -17
  33. package/dist/market_adapter/lp_chart_core.js +1 -0
  34. package/dist/market_adapter/utils/chain.js +4 -3
  35. package/dist/market_adapter/utils/pair_orientation.d.ts +60 -0
  36. package/dist/market_adapter/utils/pair_orientation.js +142 -0
  37. package/dist/modules/account_bots.d.ts +40 -3
  38. package/dist/modules/account_bots.js +80 -37
  39. package/dist/modules/account_orders.d.ts +4 -1
  40. package/dist/modules/account_orders.js +4 -1
  41. package/dist/modules/bitshares-native/resolvers.js +3 -3
  42. package/dist/modules/bitshares-native/subscriptions.js +1 -1
  43. package/dist/modules/bitshares_client.d.ts +12 -10
  44. package/dist/modules/bitshares_client.js +12 -10
  45. package/dist/modules/bot_defaults.d.ts +13 -2
  46. package/dist/modules/bot_defaults.js +31 -2
  47. package/dist/modules/bot_settings.js +6 -3
  48. package/dist/modules/chain_keys.d.ts +5 -1
  49. package/dist/modules/chain_keys.js +5 -1
  50. package/dist/modules/chain_orders.d.ts +6 -2
  51. package/dist/modules/chain_orders.js +6 -2
  52. package/dist/modules/constants.d.ts +11 -0
  53. package/dist/modules/constants.js +31 -1
  54. package/dist/modules/credit_runtime.d.ts +35 -5
  55. package/dist/modules/credit_runtime.js +219 -38
  56. package/dist/modules/dexbot_class.d.ts +22 -2
  57. package/dist/modules/dexbot_class.js +61 -21
  58. package/dist/modules/dexbot_cow_runtime.js +19 -18
  59. package/dist/modules/dexbot_fill_runtime.d.ts +1 -1
  60. package/dist/modules/dexbot_fill_runtime.js +4 -7
  61. package/dist/modules/dexbot_maintenance_runtime.d.ts +7 -2
  62. package/dist/modules/dexbot_maintenance_runtime.js +52 -7
  63. package/dist/modules/dexbot_startup_runtime.js +3 -2
  64. package/dist/modules/dexbot_state_recovery.js +1 -1
  65. package/dist/modules/graceful_shutdown.d.ts +6 -2
  66. package/dist/modules/graceful_shutdown.js +6 -2
  67. package/dist/modules/launcher/bot_supervisor.js +4 -0
  68. package/dist/modules/launcher/launch_modes.js +6 -3
  69. package/dist/modules/launcher/monolithic_runtime.d.ts +39 -1
  70. package/dist/modules/launcher/monolithic_runtime.js +60 -1
  71. package/dist/modules/launcher/runtime_mode.d.ts +79 -0
  72. package/dist/modules/launcher/runtime_mode.js +223 -0
  73. package/dist/modules/market_adapter_whitelist.d.ts +8 -0
  74. package/dist/modules/market_adapter_whitelist.js +8 -0
  75. package/dist/modules/order/accounting.d.ts +15 -1
  76. package/dist/modules/order/accounting.js +15 -1
  77. package/dist/modules/order/async_lock.d.ts +9 -3
  78. package/dist/modules/order/async_lock.js +9 -3
  79. package/dist/modules/order/export.d.ts +0 -5
  80. package/dist/modules/order/export.js +2 -7
  81. package/dist/modules/order/format.d.ts +6 -4
  82. package/dist/modules/order/format.js +6 -4
  83. package/dist/modules/order/grid.d.ts +147 -19
  84. package/dist/modules/order/grid.js +321 -68
  85. package/dist/modules/order/grid_reconcile.js +4 -3
  86. package/dist/modules/order/grid_reconcile_internal.js +13 -18
  87. package/dist/modules/order/index.d.ts +4 -2
  88. package/dist/modules/order/index.js +1 -1
  89. package/dist/modules/order/logger_state.d.ts +1 -1
  90. package/dist/modules/order/logger_state.js +1 -1
  91. package/dist/modules/order/manager.d.ts +1 -0
  92. package/dist/modules/order/manager.js +5 -14
  93. package/dist/modules/order/sync_engine.d.ts +26 -11
  94. package/dist/modules/order/sync_engine.js +44 -20
  95. package/dist/modules/order/utils/math.d.ts +157 -47
  96. package/dist/modules/order/utils/math.js +236 -78
  97. package/dist/modules/order/utils/order.d.ts +64 -20
  98. package/dist/modules/order/utils/order.js +80 -24
  99. package/dist/modules/order/utils/system.d.ts +41 -11
  100. package/dist/modules/order/utils/system.js +43 -13
  101. package/dist/modules/order/utils/validate.d.ts +6 -3
  102. package/dist/modules/order/utils/validate.js +53 -60
  103. package/dist/modules/types.d.ts +7 -0
  104. package/dist/modules/utils/asset_symbols.d.ts +5 -5
  105. package/dist/modules/utils/asset_symbols.js +5 -5
  106. package/dist/modules/utils/errors.d.ts +2 -1
  107. package/dist/modules/utils/errors.js +2 -1
  108. package/dist/scripts/analyze-credit.js +44 -27
  109. package/dist/scripts/diagnose-pool-history.js +35 -30
  110. package/dist/scripts/pnl.js +1 -1
  111. package/dist/scripts/rich_list.d.ts +50 -0
  112. package/dist/scripts/rich_list.js +469 -0
  113. package/dist/scripts/run-tests.js +80 -4
  114. package/dist/unlock.d.ts +2 -1
  115. package/dist/unlock.js +53 -21
  116. package/docs/BITSHARES_ONBOARDING.md +7 -0
  117. package/docs/COW_INVARIANTS.md +7 -1
  118. package/docs/DEXBOT_COMPARISON.md +6 -6
  119. package/docs/EVOLUTION.md +11 -9
  120. package/docs/FUND_MOVEMENT_AND_ACCOUNTING.md +3 -3
  121. package/docs/GRID_RECALCULATION.md +18 -6
  122. package/docs/LIFECYCLE.md +8 -8
  123. package/docs/LOGGING.md +16 -1
  124. package/docs/MPA_CREDIT_USAGE.md +10 -5
  125. package/docs/ORDER_ENGINE_POST_1.0_RETROSPECTIVE.md +163 -13
  126. package/docs/README.md +1 -1
  127. package/docs/WORKFLOW.md +6 -5
  128. package/docs/architecture.md +56 -2
  129. package/docs/developer_guide.md +5 -1
  130. package/market_adapter/README.md +14 -7
  131. package/modules/README.md +1 -1
  132. package/package.json +4 -1
  133. package/scripts/README.md +59 -32
  134. package/tests/README.md +40 -2
@@ -0,0 +1,142 @@
1
+ 'use strict';
2
+ /**
3
+ * PAIR ORIENTATION — one definition of "the same pair, seen from the other
4
+ * side", shared by the LP / order-book / feed candle caches.
5
+ *
6
+ * The three candle sources historically keyed their cache on the exact typed
7
+ * orientation (assetA/assetB in order), so `BTS/IOB.XRP` and `IOB.XRP/BTS`
8
+ * were two unrelated cache families holding reciprocal data. They now store
9
+ * under ONE canonical orientation and translate on the way in/out:
10
+ *
11
+ * canonical — the asset with the lower id is leg A (BTS-first for ids
12
+ * `1.3.0` vs `1.3.5537`). Deterministic and request-independent,
13
+ * so both directions resolve to the same folder.
14
+ * inversion — OHLC reciprocals with high/low swapped. open↔open and
15
+ * close↔close (NOT swapped): that is exactly what a direct
16
+ * fetch of the inverse pair produces for a chronological
17
+ * bucket. Verified against real pool shards (`bts_iob_xrp`
18
+ * open 0.00099711 ↔ `iob_xrp_bts` open 1002.8976).
19
+ *
20
+ * Also the single home for the folder slug, the same/swapped asset-identity
21
+ * checks and the legacy-inverse sibling-path rule, so the three source
22
+ * fetchers cannot drift on what "the other orientation" means.
23
+ *
24
+ * Pure and I/O-free (only path arithmetic and string slugs) so any runtime
25
+ * can import it.
26
+ */
27
+ import { path } from '../../modules/path_api.js';
28
+ import { slugPart } from '../interval_utils.js';
29
+ /** Numeric-aware compare of dotted BitShares ids (`1.3.2` < `1.3.10`). */
30
+ function compareAssetIds(a, b) {
31
+ const pa = String(a ?? '').split('.');
32
+ const pb = String(b ?? '').split('.');
33
+ const n = Math.max(pa.length, pb.length);
34
+ for (let i = 0; i < n; i++) {
35
+ const x = Number(pa[i]);
36
+ const y = Number(pb[i]);
37
+ if (Number.isFinite(x) && Number.isFinite(y)) {
38
+ if (x !== y)
39
+ return x - y;
40
+ }
41
+ else {
42
+ const sx = String(pa[i] ?? '');
43
+ const sy = String(pb[i] ?? '');
44
+ if (sx !== sy)
45
+ return sx < sy ? -1 : 1;
46
+ }
47
+ }
48
+ return 0;
49
+ }
50
+ /**
51
+ * Order a pair canonically (lower asset id first). Falls back to symbol order
52
+ * when ids are missing, and keeps the caller's order (flipped=false) when
53
+ * neither can order the legs.
54
+ */
55
+ function canonicalPair(assetA, assetB) {
56
+ let cmp = compareAssetIds(assetA?.id, assetB?.id);
57
+ if (cmp === 0) {
58
+ const sa = String(assetA?.symbol ?? '');
59
+ const sb = String(assetB?.symbol ?? '');
60
+ cmp = sa === sb ? 0 : (sa < sb ? -1 : 1);
61
+ }
62
+ if (cmp <= 0)
63
+ return { assetA, assetB, flipped: false };
64
+ return { assetA: assetB, assetB: assetA, flipped: true };
65
+ }
66
+ /** Slug of the pair cache folder (`bts_iob_xrp`), canonical-agnostic. */
67
+ function pairFolderSlug(assetA, assetB) {
68
+ return `${slugPart(assetA?.symbol || assetA?.id)}_${slugPart(assetB?.symbol || assetB?.id)}`;
69
+ }
70
+ /** Same asset legs, same order (id + precision). */
71
+ function sameAssets(meta, requestKey) {
72
+ return meta?.assetA?.id != null
73
+ && meta.assetB?.id != null
74
+ && meta.assetA.id === requestKey?.assetA?.id
75
+ && meta.assetB.id === requestKey?.assetB?.id
76
+ && meta.assetA.precision === requestKey?.assetA?.precision
77
+ && meta.assetB.precision === requestKey?.assetB?.precision;
78
+ }
79
+ /** Same asset legs, opposite order — a legacy pre-canonicalization shard. */
80
+ function swappedAssets(meta, requestKey) {
81
+ return meta?.assetA?.id != null
82
+ && meta.assetB?.id != null
83
+ && meta.assetA.id === requestKey?.assetB?.id
84
+ && meta.assetB.id === requestKey?.assetA?.id
85
+ && meta.assetA.precision === requestKey?.assetB?.precision
86
+ && meta.assetB.precision === requestKey?.assetA?.precision;
87
+ }
88
+ /**
89
+ * Opposite-orientation twin of a standard-layout cache path, or null for a
90
+ * custom path. Migration source only: the pre-canonicalization cache wrote the
91
+ * inverse pair to its own folder. The parent folder must be the canonical
92
+ * pair folder (so test temp dirs and `--out` targets are skipped), and callers
93
+ * that encode the folder in the filename (book) pass `inverseBaseName`.
94
+ */
95
+ function inverseSiblingOutPath(outPath, canonicalA, canonicalB, inverseBaseName) {
96
+ const resolved = path.resolve(outPath);
97
+ const parent = path.dirname(resolved);
98
+ if (path.basename(parent) !== pairFolderSlug(canonicalA, canonicalB))
99
+ return null;
100
+ return path.join(path.dirname(parent), pairFolderSlug(canonicalB, canonicalA), inverseBaseName || path.basename(resolved));
101
+ }
102
+ /**
103
+ * Invert a candle series to the opposite pair orientation.
104
+ *
105
+ * `volume`:
106
+ * - 'scale' (LP / order-book): new base volume ≈ old base volume × close,
107
+ * the same approximation the TV chart uses for its inverse view.
108
+ * - 'preserve' (feed): volume is a publish count, unchanged.
109
+ *
110
+ * Rows whose OHLC are not all finite and positive pass through untouched
111
+ * (defensive; cache data should never hit this, and dropping rows would break
112
+ * gap-filled continuity).
113
+ */
114
+ function invertCandleSeries(candles, opts = {}) {
115
+ const preserveVolume = opts.volume === 'preserve';
116
+ const list = Array.isArray(candles) ? candles : [];
117
+ const out = [];
118
+ for (const c of list) {
119
+ if (!Array.isArray(c) || c.length < 5) {
120
+ out.push(c);
121
+ continue;
122
+ }
123
+ const [ts, open, high, low, close] = c;
124
+ if (![open, high, low, close].every((v) => Number.isFinite(Number(v)) && Number(v) > 0)) {
125
+ out.push(c);
126
+ continue;
127
+ }
128
+ const volume = Number(c[5] ?? 0);
129
+ const nextVolume = !Number.isFinite(volume)
130
+ ? 0
131
+ : preserveVolume
132
+ ? volume
133
+ : volume * Number(close);
134
+ const next = [ts, 1 / close, 1 / low, 1 / high, 1 / open, nextVolume];
135
+ for (let i = 6; i < c.length; i++)
136
+ next.push(c[i]);
137
+ out.push(next);
138
+ }
139
+ return out;
140
+ }
141
+ export { compareAssetIds, canonicalPair, pairFolderSlug, sameAssets, swappedAssets, inverseSiblingOutPath, invertCandleSeries };
142
+ //# sourceMappingURL=pair_orientation.js.map
@@ -5,7 +5,7 @@
5
5
  * Manages multi-bot configuration and metadata.
6
6
  *
7
7
  * ===============================================================================
8
- * EXPORTS (10 functions)
8
+ * EXPORTS (12 functions)
9
9
  * ===============================================================================
10
10
  *
11
11
  * MAIN ENTRY POINT:
@@ -21,7 +21,7 @@
21
21
  * SUPPORTING EXPORTS:
22
22
  * ensureBotAccountId, parseJsonWithComments, parseBooleanInput,
23
23
  * colorGridPriceValue, formatPoolRefLabel, isPoolStartPrice,
24
- * isPoolRefClearInput
24
+ * isPoolRefClearInput, resolveAdapterCommitPlan, sameAdapterFlags
25
25
  *
26
26
  * INTERNAL HELPERS (not exported):
27
27
  * ask* prompt family (askString, askNumberWithBounds, askIntegerInRange,
@@ -157,6 +157,8 @@ declare function loadGeneralSettings(): {
157
157
  FILL_TOTALS_RETRY_MAX_MS: number;
158
158
  SPREAD_STALE_WARN_MS: number;
159
159
  SPREAD_STALE_ESCALATE_MS: number;
160
+ SPREAD_CORRECTION_MAX_ATTEMPTS: number;
161
+ SPREAD_STALE_TRANSIENT_GRACE: number;
160
162
  SPREAD_CORRECTION_SYNC_FRESH_MS: number;
161
163
  SPREAD_STALE_RESYNC_COOLDOWN_MS: number;
162
164
  BOUNDARY_HOLD_RESYNC_THRESHOLD: number;
@@ -393,6 +395,7 @@ declare function loadGeneralSettings(): {
393
395
  FILL_PROCESSING: {
394
396
  MODE: string;
395
397
  OPERATION_TYPE: number;
398
+ COALESCE_BACKLOG_REPLAY: boolean;
396
399
  MAX_CONSECUTIVE_CONSUMER_FAILURES: number;
397
400
  CONSUMER_BACKOFF_INITIAL_MS: number;
398
401
  CONSUMER_BACKOFF_MAX_MS: number;
@@ -754,10 +757,44 @@ declare function ensureBotAccountId(data: Record<string, unknown>, timeoutMs?: n
754
757
  id: string | null;
755
758
  reason: string;
756
759
  }>;
760
+ interface AdapterFlags {
761
+ ama: boolean;
762
+ dynamicWeight: boolean;
763
+ asymmetricBounds: boolean;
764
+ }
765
+ interface AdapterCommitPlan {
766
+ /** Source key to move first, or null when no entry is being renamed. */
767
+ renameFrom: string | null;
768
+ /** Key read to decide whether the stored flags already match. */
769
+ compareKey: string;
770
+ /** Key the flags are written to when they differ. */
771
+ writeKey: string;
772
+ }
773
+ /**
774
+ * Decide how an editor save should commit the adapter whitelist entry,
775
+ * independent of I/O so the copy/rename semantics are unit-testable:
776
+ *
777
+ * - new bot : no rename; compare and write the new key.
778
+ * - modify : no rename; compare and write the same key.
779
+ * - modify/rename: move baseKey -> newKey; compare the source pre-move so an
780
+ * unchanged flag set still performs the move.
781
+ * - copy : never moves — the source entry must survive — so compare
782
+ * and write the new key.
783
+ *
784
+ * An empty newKey (or baseKey) can not be a rename target and falls back to
785
+ * comparing the source.
786
+ */
787
+ declare function resolveAdapterCommitPlan({ baseKey, newKey, isCopy }: {
788
+ baseKey: string;
789
+ newKey: string;
790
+ isCopy: boolean;
791
+ }): AdapterCommitPlan;
792
+ /** Field-wise comparison of two adapter flag sets. */
793
+ declare function sameAdapterFlags(a: AdapterFlags, b: AdapterFlags): boolean;
757
794
  /**
758
795
  * Entry point exposing a menu-driven interface for creating, modifying, and reviewing bots.
759
796
  * @returns {Promise<void>}
760
797
  */
761
798
  declare function main(): Promise<void>;
762
- export { main, normalizeBotDraft, ensureBotAccountId, parseJsonWithComments, parseBooleanInput, colorGridPriceValue, formatPoolRefLabel, isPoolStartPrice, isPoolRefClearInput, loadGeneralSettings };
799
+ export { main, normalizeBotDraft, ensureBotAccountId, parseJsonWithComments, parseBooleanInput, colorGridPriceValue, formatPoolRefLabel, isPoolStartPrice, isPoolRefClearInput, loadGeneralSettings, resolveAdapterCommitPlan, sameAdapterFlags };
763
800
  //# sourceMappingURL=account_bots.d.ts.map
@@ -5,7 +5,7 @@
5
5
  * Manages multi-bot configuration and metadata.
6
6
  *
7
7
  * ===============================================================================
8
- * EXPORTS (10 functions)
8
+ * EXPORTS (12 functions)
9
9
  * ===============================================================================
10
10
  *
11
11
  * MAIN ENTRY POINT:
@@ -21,7 +21,7 @@
21
21
  * SUPPORTING EXPORTS:
22
22
  * ensureBotAccountId, parseJsonWithComments, parseBooleanInput,
23
23
  * colorGridPriceValue, formatPoolRefLabel, isPoolStartPrice,
24
- * isPoolRefClearInput
24
+ * isPoolRefClearInput, resolveAdapterCommitPlan, sameAdapterFlags
25
25
  *
26
26
  * INTERNAL HELPERS (not exported):
27
27
  * ask* prompt family (askString, askNumberWithBounds, askIntegerInRange,
@@ -1226,21 +1226,56 @@ async function ensureBotAccountId(data, timeoutMs = 15000, quiet = false, force
1226
1226
  }
1227
1227
  }
1228
1228
  }
1229
+ /**
1230
+ * Decide how an editor save should commit the adapter whitelist entry,
1231
+ * independent of I/O so the copy/rename semantics are unit-testable:
1232
+ *
1233
+ * - new bot : no rename; compare and write the new key.
1234
+ * - modify : no rename; compare and write the same key.
1235
+ * - modify/rename: move baseKey -> newKey; compare the source pre-move so an
1236
+ * unchanged flag set still performs the move.
1237
+ * - copy : never moves — the source entry must survive — so compare
1238
+ * and write the new key.
1239
+ *
1240
+ * An empty newKey (or baseKey) can not be a rename target and falls back to
1241
+ * comparing the source.
1242
+ */
1243
+ function resolveAdapterCommitPlan({ baseKey, newKey, isCopy }) {
1244
+ const base = String(baseKey || '');
1245
+ const next = String(newKey || '');
1246
+ const renameFrom = (!isCopy && base && next && base !== next) ? base : null;
1247
+ return {
1248
+ renameFrom,
1249
+ compareKey: isCopy ? next : (base || next),
1250
+ writeKey: next,
1251
+ };
1252
+ }
1253
+ /** Field-wise comparison of two adapter flag sets. */
1254
+ function sameAdapterFlags(a, b) {
1255
+ return a.ama === b.ama
1256
+ && a.dynamicWeight === b.dynamicWeight
1257
+ && a.asymmetricBounds === b.asymmetricBounds;
1258
+ }
1229
1259
  /**
1230
1260
  * Interactive menu to edit bot data.
1231
1261
  * @param {Object} [base={}] - The initial bot data to edit.
1232
1262
  * @param {number} [index=0] - Position the edited bot will occupy in the
1233
1263
  * bots array (used to derive the same botKey the runtime uses for unnamed
1234
1264
  * fallback entries).
1235
- * @param {number} [baseIndex=index] - Position the base entry currently
1236
- * occupies (differs from `index` for copies, whose source sits elsewhere).
1237
- * @returns {Promise<{ data: any, commitAdapter: (() => void)|null }|null>}
1265
+ * @param {BotEditorMode} [mode='new'] - Editor intent. `copy` derives the
1266
+ * source whitelist key from `sourceIndex` and never moves it; `modify`
1267
+ * renames/moves the entry when the name changes; `new` starts empty.
1268
+ * @param {number} [sourceIndex=index] - Position the base entry currently
1269
+ * occupies (differs from `index` only for copies).
1270
+ * @returns {Promise<{ data: any, commitAdapter: (() => 'saved'|'unchanged'|'failed')|null }|null>}
1238
1271
  * The edited draft plus a commit hook for staged `6) Adapter` flags — the
1239
1272
  * caller MUST run `commitAdapter()` only after its bots.json save succeeded
1240
1273
  * (so a failed save never leaves the whitelist out of sync), or null when
1241
- * cancelled.
1274
+ * cancelled. The hook reports whether the whitelist write actually happened
1275
+ * ('saved'), was unnecessary ('unchanged'), or failed ('failed', already
1276
+ * printed as a warning) so the caller can fold it into one status line.
1242
1277
  */
1243
- async function promptBotData(base = {}, index = 0, baseIndex = index) {
1278
+ async function promptBotData(base = {}, index = 0, mode = 'new', sourceIndex = index) {
1244
1279
  const data = normalizeBotDraft(base);
1245
1280
  // Market-adapter flags (6) Adapter) live in
1246
1281
  // profiles/market_adapter_whitelist.json keyed by botKey — the same file
@@ -1248,8 +1283,9 @@ async function promptBotData(base = {}, index = 0, baseIndex = index) {
1248
1283
  // commit hook so Cancel (or a failed bots.json save) discards them
1249
1284
  // together with the rest of the draft.
1250
1285
  const baseEntry = base && typeof base === 'object' && Object.keys(base).length > 0 ? base : null;
1251
- const baseBotKey = baseEntry ? String(normalizeBotEntry(baseEntry, baseIndex).botKey || '') : '';
1252
- const isNewBot = !baseEntry;
1286
+ const baseBotKey = baseEntry ? String(normalizeBotEntry(baseEntry, sourceIndex).botKey || '') : '';
1287
+ const isNewBot = mode === 'new';
1288
+ const isCopy = mode === 'copy';
1253
1289
  let adapterStaged = null;
1254
1290
  const isAmaGridPriceDraft = () => /^ama(?:[1-4])?$/.test(String(data.gridPrice ?? '').trim().toLowerCase());
1255
1291
  // Staged menu-6 edits win. Otherwise an existing bot uses its stored entry;
@@ -1505,32 +1541,30 @@ async function promptBotData(base = {}, index = 0, baseIndex = index) {
1505
1541
  // flags already match what is stored — an unchanged save never creates a
1506
1542
  // placeholder entry.
1507
1543
  const stagedFlags = adapterStaged;
1508
- // A new bot also commits without an explicit menu-6 edit: its resolved
1509
- // default (record if present, else AMA-on) must be persisted so the market
1510
- // adapter sees the same value the editor displayed. An unchanged save still
1511
- // writes nothing.
1512
- const commitAdapter = (stagedFlags || isNewBot) ? () => {
1513
- const newKey = String(normalizeBotEntry(data, index).botKey || '');
1514
- const needRename = !!(baseBotKey && newKey && baseBotKey !== newKey);
1544
+ // Resolve the whitelist commit up front. A rename must arm the hook even
1545
+ // when menu 6 was never touched, otherwise the entry stays under the old
1546
+ // key and the renamed bot silently falls back to defaults. An unchanged
1547
+ // save still writes nothing.
1548
+ const newKey = String(normalizeBotEntry(data, index).botKey || '');
1549
+ const adapterPlan = resolveAdapterCommitPlan({ baseKey: baseBotKey, newKey, isCopy });
1550
+ const commitAdapter = (stagedFlags || isNewBot || isCopy || adapterPlan.renameFrom) ? () => {
1515
1551
  const desired = stagedFlags || adapterFlags();
1516
- const current = getWhitelistFlags(baseBotKey || newKey);
1517
- const unchanged = desired.ama === current.ama
1518
- && desired.dynamicWeight === current.dynamicWeight
1519
- && desired.asymmetricBounds === current.asymmetricBounds;
1520
- if (needRename && !renameWhitelistEntry(baseBotKey, newKey)) {
1552
+ // Read before any rename: for a rename the compare key still holds the
1553
+ // pre-move entry, which is what decides "unchanged".
1554
+ const unchanged = sameAdapterFlags(desired, getWhitelistFlags(adapterPlan.compareKey));
1555
+ if (adapterPlan.renameFrom && !renameWhitelistEntry(adapterPlan.renameFrom, adapterPlan.writeKey)) {
1521
1556
  console.log(`${COLORS.yellow}Adapter flags not saved — see the warning above.${COLORS.reset}`);
1522
- return;
1557
+ return 'failed';
1523
1558
  }
1524
1559
  // Unchanged flags need no write — a successful rename above already
1525
1560
  // migrated the entry under the new key.
1526
1561
  if (unchanged)
1527
- return;
1528
- if (!setWhitelistFlags(newKey, desired)) {
1562
+ return 'unchanged';
1563
+ if (!setWhitelistFlags(adapterPlan.writeKey, desired)) {
1529
1564
  console.log(`${COLORS.yellow}Warning: adapter flags not saved — could not write ${whitelistFile()}.${COLORS.reset}`);
1565
+ return 'failed';
1530
1566
  }
1531
- else {
1532
- console.log(`${COLORS.green}Adapter flags saved for '${newKey}'. Price/Weight are picked up on the adapter's next cycle; Range scaling applies after 'dexbot reset ${data.name}'.${COLORS.reset}`);
1533
- }
1567
+ return 'saved';
1534
1568
  } : null;
1535
1569
  // Return the final data structure, preserving ALL fields from the normalized
1536
1570
  // draft (deep-copy of base + defaults, minus stripped runtime-managed fields).
@@ -1736,13 +1770,19 @@ async function main() {
1736
1770
  case '1': {
1737
1771
  while (true) {
1738
1772
  try {
1739
- const result = await promptBotData({}, config.bots.length);
1773
+ const result = await promptBotData({}, config.bots.length, 'new');
1740
1774
  if (!result)
1741
1775
  break;
1742
1776
  config.bots.push(result.data);
1743
1777
  saveBotsConfig(config, filePath);
1744
- result.commitAdapter?.();
1745
- console.log(`\nAdded bot '${result.data.name}' to ${path.basename(filePath)}.`);
1778
+ const adapterStatus = result.commitAdapter?.();
1779
+ const adapterNote = adapterStatus === 'saved'
1780
+ ? ` Adapter flags saved: Price/Weight apply on the adapter's next cycle; Range scaling after 'dexbot reset ${result.data.name}'.`
1781
+ : '';
1782
+ console.log(`\n${COLORS.green}Added bot '${result.data.name}' to ${path.basename(filePath)}.${adapterNote}${COLORS.reset}`);
1783
+ // Return to the Actions menu instead of immediately
1784
+ // opening another blank New Bot editor.
1785
+ break;
1746
1786
  }
1747
1787
  catch (err) {
1748
1788
  console.log(`\n❌ Invalid input: ${getErrorMessage(err)}\n`);
@@ -1757,13 +1797,13 @@ async function main() {
1757
1797
  if (idx === null || idx === '\x1b')
1758
1798
  break;
1759
1799
  try {
1760
- const result = await promptBotData(config.bots[idx], idx);
1800
+ const result = await promptBotData(config.bots[idx], idx, 'modify');
1761
1801
  if (result) {
1762
1802
  config.bots[idx] = result.data;
1763
1803
  saveBotsConfig(config, filePath);
1764
- result.commitAdapter?.();
1804
+ const adapterStatus = result.commitAdapter?.();
1765
1805
  const entry = result.data;
1766
- console.log(`saved settings '${entry.name}' in ${path.basename(filePath)}.\n`);
1806
+ console.log(`saved settings '${entry.name}' in ${path.basename(filePath)}.${adapterStatus === 'saved' ? ' Adapter flags saved.' : ''}\n`);
1767
1807
  console.log(`Live pickup (~1min, no reload needed): ${BOT_LIVE_CONFIG_KEYS.join(' / ')}.`);
1768
1808
  console.log(`Grid geometry needs 'dexbot reset ${entry.name}' (or 'dexbot reload' for everything at once); market/account changes need 'dexbot reload'.\n`);
1769
1809
  }
@@ -1809,12 +1849,15 @@ async function main() {
1809
1849
  if (idx === null || idx === '\x1b')
1810
1850
  break;
1811
1851
  try {
1812
- const result = await promptBotData(config.bots[idx], idx + 1, idx);
1852
+ const result = await promptBotData(config.bots[idx], idx + 1, 'copy', idx);
1813
1853
  if (result) {
1814
1854
  config.bots.splice(idx + 1, 0, result.data);
1815
1855
  saveBotsConfig(config, filePath);
1816
- result.commitAdapter?.();
1817
- console.log(`Copied bot '${result.data.name}' into ${path.basename(filePath)}.\n`);
1856
+ const adapterStatus = result.commitAdapter?.();
1857
+ const adapterNote = adapterStatus === 'saved'
1858
+ ? ` Adapter flags saved: Price/Weight apply on the adapter's next cycle; Range scaling after 'dexbot reset ${result.data.name}'.`
1859
+ : '';
1860
+ console.log(`${COLORS.green}Copied bot '${result.data.name}' into ${path.basename(filePath)}.${adapterNote}${COLORS.reset}\n`);
1818
1861
  }
1819
1862
  }
1820
1863
  catch (err) {
@@ -1838,5 +1881,5 @@ async function main() {
1838
1881
  }
1839
1882
  console.log('Botmanager closed!');
1840
1883
  }
1841
- export { main, normalizeBotDraft, ensureBotAccountId, parseJsonWithComments, parseBooleanInput, colorGridPriceValue, formatPoolRefLabel, isPoolStartPrice, isPoolRefClearInput, loadGeneralSettings };
1884
+ export { main, normalizeBotDraft, ensureBotAccountId, parseJsonWithComments, parseBooleanInput, colorGridPriceValue, formatPoolRefLabel, isPoolStartPrice, isPoolRefClearInput, loadGeneralSettings, resolveAdapterCommitPlan, sameAdapterFlags };
1842
1885
  //# sourceMappingURL=account_bots.js.map
@@ -10,7 +10,7 @@
10
10
  * which makes the doubled-entry bug structurally impossible.
11
11
  *
12
12
  * ===============================================================================
13
- * EXPORTS (1 class + 1 helper)
13
+ * EXPORTS (1 class + 2 helpers)
14
14
  * ===============================================================================
15
15
  *
16
16
  * 1. AccountOrders(options) - Class for per-bot order persistence
@@ -26,6 +26,9 @@
26
26
  * 2. createBotKey(bot, index) - Generate unique bot key string
27
27
  * Uses sanitized bot.name; unnamed bots fall back to asset pair + index
28
28
  *
29
+ * 3. sanitizeKey(value) - Re-export of utils/sanitize_key: filename-safe key
30
+ * normalization (trim, lowercase, collapse non-alphanumeric runs to '-')
31
+ *
29
32
  * ===============================================================================
30
33
  *
31
34
  * FILE STRUCTURE (profiles/orders/{botKey}.json):
@@ -10,7 +10,7 @@
10
10
  * which makes the doubled-entry bug structurally impossible.
11
11
  *
12
12
  * ===============================================================================
13
- * EXPORTS (1 class + 1 helper)
13
+ * EXPORTS (1 class + 2 helpers)
14
14
  * ===============================================================================
15
15
  *
16
16
  * 1. AccountOrders(options) - Class for per-bot order persistence
@@ -26,6 +26,9 @@
26
26
  * 2. createBotKey(bot, index) - Generate unique bot key string
27
27
  * Uses sanitized bot.name; unnamed bots fall back to asset pair + index
28
28
  *
29
+ * 3. sanitizeKey(value) - Re-export of utils/sanitize_key: filename-safe key
30
+ * normalization (trim, lowercase, collapse non-alphanumeric runs to '-')
31
+ *
29
32
  * ===============================================================================
30
33
  *
31
34
  * FILE STRUCTURE (profiles/orders/{botKey}.json):
@@ -15,9 +15,9 @@ function createResolvers(chainClient) {
15
15
  async function resolveAsset(idOrSymbol) {
16
16
  if (!idOrSymbol)
17
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.
18
+ // Canonicalize before the cache key and the chain call: the chain
19
+ // lookup is case-sensitive, so a lowercase symbol would both miss the
20
+ // cache and fail to resolve.
21
21
  idOrSymbol = normalizeAssetRef(idOrSymbol);
22
22
  const cacheKey = `asset:${idOrSymbol}`;
23
23
  const cached = assetCache.get(cacheKey);
@@ -1079,7 +1079,7 @@ function createSubscriptionManager(chainClient, overrides = {}) {
1079
1079
  // already armed by handleNotice cursor advances and by
1080
1080
  // resubscribeEntry/resubscribeAll on disconnects. Poll does NOT arm
1081
1081
  // unconditionally — that would turn every 60s tick into a 40-page
1082
- // re-fetch forever (~80 pages/min for bbot9+bbot4). If a gap-recovery
1082
+ // re-fetch forever (~80 pages/min across several tracked accounts). If a gap-recovery
1083
1083
  // fetch previously threw, _gapRecovery stays true and the next poll
1084
1084
  // will run the lookback; otherwise this tick is just a plain >cursor
1085
1085
  // scan with no lookback. Eager gap-recovery scheduled in handleNotice
@@ -10,7 +10,7 @@
10
10
  * - Subscription and event handling
11
11
  *
12
12
  * ===============================================================================
13
- * EXPORTS (16 items)
13
+ * EXPORTS (17 items)
14
14
  * ===============================================================================
15
15
  *
16
16
  * 1. BitShares - Shared BitShares class for database operations
@@ -23,15 +23,17 @@
23
23
  * 5. disconnectClient() - Disconnect the client
24
24
  * 6. reconnectForCycle() - Reconnect for maintenance cycle
25
25
  * 7. setSuppressConnectionLog(bool) - Suppress/restore connection log output
26
- * 8. getNodeManager() - Get the NodeManager instance
27
- * 9. getNodeStats() - Get node health statistics
28
- * 10. getNodeSummary() - Get node summary
29
- * 11. getConnectionError() - Get last connection error
30
- * 12. onReconnect(callback) - Register reconnect callback
31
- * 13. onReconnect(callback) - Register reconnect callback
32
- * 14. withTimeout(promise, timeoutMs, options) - Wrap promise with timeout (re-exported from order/utils/timeout.js)
33
- * 15. _assessFailover() - Internal failover assessment
34
- * 16. _internal - @internal Internal state (connected flag) — test-only, do not rely on in production
26
+ * 8. isSuppressConnectionLog() - Whether connection log output is currently suppressed
27
+ * 9. shouldCountNodeStrike(source) - Whether a transport-reported node failure
28
+ * should count as a persistent strike against the node
29
+ * 10. getNodeManager() - Get the NodeManager instance
30
+ * 11. getNodeStats() - Get node health statistics
31
+ * 12. getNodeSummary() - Get node summary
32
+ * 13. getConnectionError() - Get last connection error
33
+ * 14. onReconnect(callback) - Register reconnect callback
34
+ * 15. withTimeout(promise, timeoutMs, options) - Wrap promise with timeout (re-exported from order/utils/timeout.js)
35
+ * 16. _assessFailover() - Internal failover assessment
36
+ * 17. _internal - @internal Internal state (connected flag) — test-only, do not rely on in production
35
37
  * ===============================================================================
36
38
  */
37
39
  import NodeManager from './node_manager.js';
@@ -10,7 +10,7 @@
10
10
  * - Subscription and event handling
11
11
  *
12
12
  * ===============================================================================
13
- * EXPORTS (16 items)
13
+ * EXPORTS (17 items)
14
14
  * ===============================================================================
15
15
  *
16
16
  * 1. BitShares - Shared BitShares class for database operations
@@ -23,15 +23,17 @@
23
23
  * 5. disconnectClient() - Disconnect the client
24
24
  * 6. reconnectForCycle() - Reconnect for maintenance cycle
25
25
  * 7. setSuppressConnectionLog(bool) - Suppress/restore connection log output
26
- * 8. getNodeManager() - Get the NodeManager instance
27
- * 9. getNodeStats() - Get node health statistics
28
- * 10. getNodeSummary() - Get node summary
29
- * 11. getConnectionError() - Get last connection error
30
- * 12. onReconnect(callback) - Register reconnect callback
31
- * 13. onReconnect(callback) - Register reconnect callback
32
- * 14. withTimeout(promise, timeoutMs, options) - Wrap promise with timeout (re-exported from order/utils/timeout.js)
33
- * 15. _assessFailover() - Internal failover assessment
34
- * 16. _internal - @internal Internal state (connected flag) — test-only, do not rely on in production
26
+ * 8. isSuppressConnectionLog() - Whether connection log output is currently suppressed
27
+ * 9. shouldCountNodeStrike(source) - Whether a transport-reported node failure
28
+ * should count as a persistent strike against the node
29
+ * 10. getNodeManager() - Get the NodeManager instance
30
+ * 11. getNodeStats() - Get node health statistics
31
+ * 12. getNodeSummary() - Get node summary
32
+ * 13. getConnectionError() - Get last connection error
33
+ * 14. onReconnect(callback) - Register reconnect callback
34
+ * 15. withTimeout(promise, timeoutMs, options) - Wrap promise with timeout (re-exported from order/utils/timeout.js)
35
+ * 16. _assessFailover() - Internal failover assessment
36
+ * 17. _internal - @internal Internal state (connected flag) — test-only, do not rely on in production
35
37
  * ===============================================================================
36
38
  */
37
39
  import { TIMING, NODE_MANAGEMENT, NATIVE_CLIENT } from './constants.js';
@@ -18,7 +18,7 @@
18
18
  * Mode rules are pinned by tests/test_bot_defaults_characterization.ts and
19
19
  * tests/test_bot_defaults_parity.ts — update them together with this file.
20
20
  */
21
- import type { UnknownRecord } from './types.js';
21
+ import type { UnknownRecord, BotMetrics } from './types.js';
22
22
  interface SeedOptions {
23
23
  /** Defaults source; omit to use the merged DEFAULT_CONFIG. */
24
24
  defaults?: UnknownRecord;
@@ -27,7 +27,9 @@ interface SeedOptions {
27
27
  * DEFAULT_CONFIG keys the draft seed must NEVER add. Seeding these would change
28
28
  * persisted bots.json bytes for existing bots and pre-satisfy
29
29
  * `validateBotEntry`'s required-key check (assetA/assetB), hiding genuine
30
- * configuration mistakes from the validator.
30
+ * configuration mistakes from the validator. `activeOrders`/`reserveOrders` are
31
+ * legacy aliases migrated to `coreOrders`/`edgeOrders`, kept here so an older
32
+ * general.settings.json that still carries them does not fail the parity guard.
31
33
  */
32
34
  export declare const DRAFT_EXCLUDED_KEYS: string[];
33
35
  /**
@@ -100,5 +102,14 @@ export declare function seedBotEntry<T extends UnknownRecord>(entry: T, options?
100
102
  * (the historical shallow spread aliased every nested default object).
101
103
  */
102
104
  export declare function seedBotRuntimeConfig(config?: UnknownRecord, options?: SeedOptions): UnknownRecord;
105
+ /**
106
+ * Fresh zeroed metrics for the bot and its order manager. Both layers used to
107
+ * declare the shared counters independently, so a new shared counter had to be
108
+ * added twice (and could drift). The manager spreads this base and adds its own
109
+ * runtime-only counters (lock stats, sync timing, start time); the bot uses it
110
+ * verbatim. Single source of truth for the shared `BotMetrics` defaults.
111
+ * @returns {Object} A new metrics object with every shared counter zeroed
112
+ */
113
+ export declare function createDefaultBotMetrics(): BotMetrics;
103
114
  export {};
104
115
  //# sourceMappingURL=bot_defaults.d.ts.map