dexbot 1.6.12 → 1.6.14

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 (213) hide show
  1. package/CHANGELOG.md +65 -1
  2. package/README.md +2 -2
  3. package/analysis/README.md +9 -11
  4. package/analysis/ama_fitting/README.md +5 -3
  5. package/claw/README.md +1 -0
  6. package/claw/docs/AI_BOT_LIBRARY_API.md +3 -1
  7. package/claw/docs/DEXBOT2_TUNING_CHEAT_SHEET.md +4 -4
  8. package/claw/modules/claw_bridge.ts +0 -3
  9. package/claw/modules/claw_catalog.ts +8 -4
  10. package/claw/modules/claw_skill_md.ts +1 -0
  11. package/claw/modules/dexbot_profiles.ts +59 -15
  12. package/claw/modules/types.ts +2 -1
  13. package/claw/package.json +3 -3
  14. package/claw/runtimes/openclaw-plugin/openclaw.plugin.json +1 -1
  15. package/claw/runtimes/openclaw-plugin/package.json +1 -1
  16. package/claw/skills/margin-trading/SKILL.md +1 -1
  17. package/claw/skills/margin-trading/references/position-management.md +1 -1
  18. package/claw/tsconfig.json +2 -2
  19. package/dist/analysis/ama_fitting/analyze_lambda_vs_slow.js +1 -14
  20. package/dist/analysis/ama_fitting/fetch_lp_candles.js +51 -41
  21. package/dist/analysis/ama_fitting/generate_unified_comparison_chart.d.ts +1 -24
  22. package/dist/analysis/ama_fitting/generate_unified_comparison_chart.js +36 -18
  23. package/dist/analysis/ama_fitting/optimizer_high_resolution.js +18 -66
  24. package/dist/analysis/analyze_args.d.ts +12 -0
  25. package/dist/analysis/analyze_args.js +20 -0
  26. package/dist/analysis/bot_fitting/backtest_ama_sweep.d.ts +1 -16
  27. package/dist/analysis/bot_fitting/backtest_ama_sweep.js +20 -101
  28. package/dist/analysis/bot_fitting/backtest_bot_fitting.js +26 -92
  29. package/dist/analysis/bot_fitting/backtest_lookback_drawdown.js +19 -34
  30. package/dist/analysis/bot_fitting/shared_utils.d.ts +71 -3
  31. package/dist/analysis/bot_fitting/shared_utils.js +124 -8
  32. package/dist/analysis/chart_ui.d.ts +30 -1
  33. package/dist/analysis/chart_ui.js +37 -1
  34. package/dist/analysis/fills_cache.d.ts +3 -23
  35. package/dist/analysis/fills_cache.js +3 -84
  36. package/dist/analysis/fills_source.d.ts +31 -1
  37. package/dist/analysis/fills_source.js +69 -1
  38. package/dist/analysis/grid_correction_check.d.ts +1 -23
  39. package/dist/analysis/grid_correction_check.js +15 -58
  40. package/dist/analysis/math_utils.d.ts +85 -1
  41. package/dist/analysis/math_utils.js +116 -1
  42. package/dist/analysis/price_sources.d.ts +22 -1
  43. package/dist/analysis/price_sources.js +23 -0
  44. package/dist/analysis/resolve_source.js +31 -10
  45. package/dist/analysis/trade_profitability.d.ts +6 -0
  46. package/dist/analysis/trade_profitability.js +23 -97
  47. package/dist/analysis/tradingview/analyze_tradingview.d.ts +1 -17
  48. package/dist/analysis/tradingview/analyze_tradingview.js +1 -1
  49. package/dist/analysis/tradingview/tradingview_uplot_chart_generator.js +27 -40
  50. package/dist/analysis/trend_detection/backtest_ama_slope_huber.d.ts +1 -101
  51. package/dist/analysis/trend_detection/backtest_ama_slope_huber.js +22 -80
  52. package/dist/analysis/trend_detection/dynamic_weight_chart_generator.js +11 -37
  53. package/dist/analysis/trend_detection/volatility_chart_generator.js +9 -10
  54. package/dist/analysis/worker_pool.d.ts +38 -0
  55. package/dist/analysis/worker_pool.js +67 -0
  56. package/dist/dexbot.js +67 -48
  57. package/dist/market_adapter/ama_signal_runner.js +21 -54
  58. package/dist/market_adapter/candle_utils.d.ts +7 -1
  59. package/dist/market_adapter/candle_utils.js +11 -1
  60. package/dist/market_adapter/cli_args.d.ts +22 -0
  61. package/dist/market_adapter/cli_args.js +30 -0
  62. package/dist/market_adapter/core/config_normalizers.js +11 -6
  63. package/dist/market_adapter/core/kibana_candles.d.ts +3 -1
  64. package/dist/market_adapter/core/kibana_candles.js +3 -2
  65. package/dist/market_adapter/core/market_adapter_service.d.ts +85 -85
  66. package/dist/market_adapter/core/market_adapter_service.js +93 -158
  67. package/dist/market_adapter/core/signals/hurst_analyzer.d.ts +1 -6
  68. package/dist/market_adapter/core/signals/hurst_analyzer.js +1 -1
  69. package/dist/market_adapter/core/signals/permutation_entropy_analyzer.d.ts +1 -11
  70. package/dist/market_adapter/core/signals/permutation_entropy_analyzer.js +1 -1
  71. package/dist/market_adapter/inputs/fetch_book_data.js +0 -1
  72. package/dist/market_adapter/inputs/fetch_cex_synthetic_data.js +63 -107
  73. package/dist/market_adapter/inputs/fetch_lp_data.d.ts +8 -1
  74. package/dist/market_adapter/inputs/fetch_lp_data.js +25 -7
  75. package/dist/market_adapter/inputs/kibana_feed_source.js +4 -26
  76. package/dist/market_adapter/inputs/window_cache.d.ts +4 -72
  77. package/dist/market_adapter/inputs/window_cache.js +52 -177
  78. package/dist/market_adapter/interval_utils.d.ts +11 -1
  79. package/dist/market_adapter/interval_utils.js +16 -1
  80. package/dist/market_adapter/lp_chart_runner.d.ts +3 -0
  81. package/dist/market_adapter/lp_chart_runner.js +37 -19
  82. package/dist/market_adapter/market_adapter.js +27 -72
  83. package/dist/market_adapter/utils/data_discovery.d.ts +45 -1
  84. package/dist/market_adapter/utils/data_discovery.js +220 -27
  85. package/dist/market_adapter/utils/month_shards.d.ts +84 -0
  86. package/dist/market_adapter/utils/month_shards.js +237 -0
  87. package/dist/modules/account_bots.d.ts +8 -6
  88. package/dist/modules/account_bots.js +112 -131
  89. package/dist/modules/account_orders.d.ts +49 -4
  90. package/dist/modules/account_orders.js +114 -49
  91. package/dist/modules/bitshares-native/chain_client.d.ts +1 -1
  92. package/dist/modules/bitshares-native/chain_client.js +14 -13
  93. package/dist/modules/bitshares-native/crypto/ecc_core.d.ts +1 -2
  94. package/dist/modules/bitshares-native/crypto/ecc_core.js +1 -1
  95. package/dist/modules/bitshares-native/resolvers.js +22 -25
  96. package/dist/modules/bitshares-native/serial/chain_constants.d.ts +1 -2
  97. package/dist/modules/bitshares-native/serial/chain_constants.js +1 -2
  98. package/dist/modules/bitshares-native/serial/types.js +22 -50
  99. package/dist/modules/bitshares-native/signing_client.d.ts +1 -1
  100. package/dist/modules/bot_defaults.d.ts +18 -3
  101. package/dist/modules/bot_defaults.js +34 -8
  102. package/dist/modules/bot_settings.d.ts +5 -1
  103. package/dist/modules/bot_settings.js +55 -21
  104. package/dist/modules/broadcast_failure.d.ts +2 -1
  105. package/dist/modules/chain_orders.d.ts +1 -1
  106. package/dist/modules/chain_orders.js +51 -96
  107. package/dist/modules/cli_start_onboarding.d.ts +2 -1
  108. package/dist/modules/config.js +6 -1
  109. package/dist/modules/constants.d.ts +14 -6
  110. package/dist/modules/constants.js +32 -6
  111. package/dist/modules/cr_planner.d.ts +1 -1
  112. package/dist/modules/cr_planner.js +1 -5
  113. package/dist/modules/credit_pricing.d.ts +2 -1
  114. package/dist/modules/credit_pricing.js +36 -40
  115. package/dist/modules/credit_runtime.d.ts +7 -0
  116. package/dist/modules/credit_runtime.js +45 -73
  117. package/dist/modules/daemon_node_health.d.ts +4 -3
  118. package/dist/modules/dexbot_class.d.ts +33 -17
  119. package/dist/modules/dexbot_class.js +113 -61
  120. package/dist/modules/dexbot_cow_runtime.d.ts +62 -181
  121. package/dist/modules/dexbot_cow_runtime.js +380 -69
  122. package/dist/modules/dexbot_credential_client.d.ts +1 -23
  123. package/dist/modules/dexbot_credential_client.js +2 -3
  124. package/dist/modules/dexbot_fill_runtime.d.ts +2 -3
  125. package/dist/modules/dexbot_fill_runtime.js +17 -7
  126. package/dist/modules/dexbot_maintenance_runtime.d.ts +36 -81
  127. package/dist/modules/dexbot_maintenance_runtime.js +137 -133
  128. package/dist/modules/dexbot_startup_runtime.d.ts +0 -1
  129. package/dist/modules/dexbot_startup_runtime.js +25 -14
  130. package/dist/modules/dexbot_state_recovery.js +16 -0
  131. package/dist/modules/general_settings.d.ts +1 -1
  132. package/dist/modules/graceful_shutdown.js +17 -11
  133. package/dist/modules/key_store.d.ts +0 -5
  134. package/dist/modules/key_store.js +1 -2
  135. package/dist/modules/lazy_shim.d.ts +11 -0
  136. package/dist/modules/lazy_shim.js +16 -0
  137. package/dist/modules/node_connect_policy.d.ts +3 -2
  138. package/dist/modules/node_failure_ledger.d.ts +6 -5
  139. package/dist/modules/order/accounting.js +11 -11
  140. package/dist/modules/order/export.js +2 -2
  141. package/dist/modules/order/format.d.ts +26 -3
  142. package/dist/modules/order/format.js +33 -3
  143. package/dist/modules/order/genesis_policy.d.ts +4 -4
  144. package/dist/modules/order/genesis_policy.js +6 -3
  145. package/dist/modules/order/grid.d.ts +26 -12
  146. package/dist/modules/order/grid.js +468 -80
  147. package/dist/modules/order/grid_reconcile.d.ts +1 -1
  148. package/dist/modules/order/grid_reconcile.js +5 -5
  149. package/dist/modules/order/grid_reconcile_internal.js +48 -40
  150. package/dist/modules/order/index.d.ts +35 -8
  151. package/dist/modules/order/logger.d.ts +1 -8
  152. package/dist/modules/order/logger.js +2 -11
  153. package/dist/modules/order/manager.d.ts +18 -15
  154. package/dist/modules/order/manager.js +91 -74
  155. package/dist/modules/order/strategy.d.ts +2 -2
  156. package/dist/modules/order/strategy.js +51 -21
  157. package/dist/modules/order/sync_engine.js +4 -0
  158. package/dist/modules/order/utils/math.d.ts +3 -3
  159. package/dist/modules/order/utils/math.js +38 -27
  160. package/dist/modules/order/utils/order.d.ts +58 -58
  161. package/dist/modules/order/utils/order.js +158 -137
  162. package/dist/modules/order/utils/system.d.ts +202 -35
  163. package/dist/modules/order/utils/system.js +409 -31
  164. package/dist/modules/order/utils/validate.js +28 -6
  165. package/dist/modules/order/utils/withPoolRef.d.ts +2 -1
  166. package/dist/modules/paths.js +32 -34
  167. package/dist/modules/runtime_settings.d.ts +3 -5
  168. package/dist/modules/runtime_settings.js +3 -3
  169. package/dist/modules/settings_merge.d.ts +2 -2
  170. package/dist/modules/socket_json_client.d.ts +2 -1
  171. package/dist/modules/types.d.ts +89 -30
  172. package/dist/modules/utils/errors.js +1 -3
  173. package/dist/modules/version_notice.d.ts +11 -10
  174. package/dist/pm2.d.ts +0 -1
  175. package/dist/pm2.js +56 -35
  176. package/dist/scripts/analyze-git.js +2 -15
  177. package/dist/scripts/analyze-orders.d.ts +1 -1
  178. package/dist/scripts/analyze-orders.js +4 -4
  179. package/dist/scripts/chart_command.js +2 -2
  180. package/dist/scripts/check_any.d.ts +4 -0
  181. package/dist/scripts/check_any.js +53 -21
  182. package/dist/scripts/diagnose-pool-history.js +1 -6
  183. package/dist/scripts/divergence-calc.js +6 -6
  184. package/dist/scripts/run-tests.js +0 -1
  185. package/dist/scripts/sync-version.js +0 -10
  186. package/dist/scripts/validate_bots.d.ts +1 -1
  187. package/dist/scripts/validate_bots.js +3 -3
  188. package/dist/unlock.js +7 -2
  189. package/docs/BITSHARES_ONBOARDING.md +8 -12
  190. package/docs/COPY_ON_WRITE_MASTER_PLAN.md +2 -3
  191. package/docs/COW_INVARIANTS.md +6 -6
  192. package/docs/DEXBOT_COMPARISON.md +7 -7
  193. package/docs/EVOLUTION.md +10 -8
  194. package/docs/FUND_MOVEMENT_AND_ACCOUNTING.md +8 -6
  195. package/docs/GRID_PRICE_INVARIANT.md +3 -3
  196. package/docs/GRID_RECALCULATION.md +4 -1
  197. package/docs/GRID_RECONCILE.md +4 -4
  198. package/docs/LIFECYCLE.md +11 -11
  199. package/docs/LOGGING.md +14 -0
  200. package/docs/MPA_CREDIT_USAGE.md +1 -1
  201. package/docs/ORDER_ENGINE_POST_1.0_RETROSPECTIVE.md +12 -4
  202. package/docs/README.md +3 -3
  203. package/docs/WORKFLOW.md +1 -0
  204. package/docs/architecture.md +25 -16
  205. package/docs/developer_guide.md +7 -2
  206. package/market_adapter/README.md +6 -4
  207. package/package.json +6 -9
  208. package/scripts/README.md +43 -38
  209. package/tests/README.md +26 -11
  210. package/dist/scripts/diagnose-kibana-candles.d.ts +0 -3
  211. package/dist/scripts/diagnose-kibana-candles.js +0 -82
  212. package/scripts/git-viewer.sh +0 -489
  213. package/scripts/postinstall.js +0 -16
@@ -0,0 +1,237 @@
1
+ 'use strict';
2
+ /**
3
+ * MONTH-SHARD GEOMETRY & COVERAGE — the one place that defines how calendar-
4
+ * month cache shards are named, located, and how recorded query coverage is
5
+ * merged and compared.
6
+ *
7
+ * Two independent caches store one `{ meta, ... }` file per UTC month named
8
+ * `<base>.shard_YYYY-MM.json`:
9
+ * - the candle cache (`market_adapter/inputs/window_cache.ts`)
10
+ * - the fills cache (`analysis/fills_cache.ts`)
11
+ *
12
+ * They previously carried private, near-identical copies of every helper
13
+ * below. The geometry in particular must never drift: two caches that disagree
14
+ * on a month boundary silently double-fetch or drop a bucket. Keeping it here
15
+ * makes the layout a single contract.
16
+ *
17
+ * Pure and I/O-free (only path arithmetic) so it is safe to import from any
18
+ * runtime, including browser-safe code that merely checks a filename.
19
+ */
20
+ import { path } from '../../modules/path_api.js';
21
+ const SHARD_MARKER = '.shard_';
22
+ const SHARD_KEY_RE = /^\d{4}-\d{2}$/;
23
+ // ─── Month-shard naming ───────────────────────────────────────────────────────
24
+ // Shard key is the UTC calendar month; bounds are half-open [start, end) so
25
+ // every timestamp maps to exactly one shard (a value exactly at a month
26
+ // boundary belongs to the new month).
27
+ function shardKeyForTimestamp(tsMs) {
28
+ const d = new Date(Number(tsMs));
29
+ return `${d.getUTCFullYear()}-${String(d.getUTCMonth() + 1).padStart(2, '0')}`;
30
+ }
31
+ function shardBoundsForKey(key) {
32
+ const parts = String(key).split('-').map(Number);
33
+ const start = Date.UTC(parts[0], parts[1] - 1, 1);
34
+ const end = parts[1] === 12 ? Date.UTC(parts[0] + 1, 0, 1) : Date.UTC(parts[0], parts[1], 1);
35
+ return { start, end };
36
+ }
37
+ function shardKeysForRange(gteMs, lteMs) {
38
+ const keys = [];
39
+ const cursor = new Date(Date.UTC(new Date(Number(gteMs)).getUTCFullYear(), new Date(Number(gteMs)).getUTCMonth(), 1));
40
+ const last = new Date(Number(lteMs));
41
+ while (cursor <= last) {
42
+ keys.push(shardKeyForTimestamp(cursor.getTime()));
43
+ cursor.setUTCMonth(cursor.getUTCMonth() + 1);
44
+ }
45
+ return keys;
46
+ }
47
+ function shardPathFor(basePath, shardKey) {
48
+ const parsed = path.parse(basePath);
49
+ return path.join(parsed.dir, `${parsed.name}${SHARD_MARKER}${shardKey}${parsed.ext}`);
50
+ }
51
+ /**
52
+ * If `name` is a shard file for `baseName`, return its `YYYY-MM` key;
53
+ * otherwise null. Guards the `sibling`/family scans against stray files.
54
+ */
55
+ function shardKeyFromName(name, baseName, ext = '.json') {
56
+ const prefix = `${baseName}${SHARD_MARKER}`;
57
+ if (ext && !name.endsWith(ext))
58
+ return null;
59
+ if (!name.startsWith(prefix))
60
+ return null;
61
+ const key = name.slice(prefix.length, name.length - ext.length);
62
+ return SHARD_KEY_RE.test(key) ? key : null;
63
+ }
64
+ /**
65
+ * The base stem of a shard filename, or null when `name` is not a shard.
66
+ * `lp_pool_133_1h.shard_2026-10.json` → `lp_pool_133_1h`. Callers that must
67
+ * group or upgrade a family use this instead of re-deriving the marker regex.
68
+ */
69
+ function shardStemFromName(name, ext = '.json') {
70
+ if (ext && !name.endsWith(ext))
71
+ return null;
72
+ const body = ext ? name.slice(0, name.length - ext.length) : name;
73
+ const idx = body.lastIndexOf(SHARD_MARKER);
74
+ if (idx < 0)
75
+ return null;
76
+ const key = body.slice(idx + SHARD_MARKER.length);
77
+ return SHARD_KEY_RE.test(key) ? body.slice(0, idx) : null;
78
+ }
79
+ // ─── Coverage spans ───────────────────────────────────────────────────────────
80
+ /** Parse a verification timestamp: epoch ms or ISO. Anything else is unknown. */
81
+ function timestampMs(raw) {
82
+ // `null`/`undefined`/`''` mean "not recorded". They must NOT fall through
83
+ // to Number(): Number(null) === 0 is finite, which would read an unknown
84
+ // verification time as "verified at the epoch" — i.e. as maximally stale.
85
+ if (raw == null || raw === '')
86
+ return null;
87
+ if (typeof raw === 'string') {
88
+ const parsed = Date.parse(raw);
89
+ return Number.isFinite(parsed) ? parsed : null;
90
+ }
91
+ const at = Number(raw);
92
+ return Number.isFinite(at) ? at : null;
93
+ }
94
+ function verifiedAt(range) {
95
+ return timestampMs(range?.at);
96
+ }
97
+ /**
98
+ * Normalize recorded spans: sort, then merge overlapping / bucket-adjacent
99
+ * ones — but ONLY when they assert the same verification time. Merging spans
100
+ * with different `at` would have to pick one verdict for the whole union, and
101
+ * either pick loses (min → the merged span vouches for buckets the older
102
+ * query never saw; max → buckets verified long ago look freshly verified).
103
+ * Keeping them separate preserves exact per-bucket freshness. The same-`at`
104
+ * case (bulk fetches, and every pre-`at` shard) collapses to one span.
105
+ *
106
+ * `bucketMs` widens adjacency: `0` merges only overlaps, `1` merges adjacent
107
+ * integer-ms spans (fills), a bucket size merges spans a bucket apart (candles).
108
+ */
109
+ function unionQueriedRanges(ranges, bucketMs = 0) {
110
+ const clean = (ranges || [])
111
+ .filter((q) => q && Number.isFinite(Number(q.gte)) && Number.isFinite(Number(q.lte)) && Number(q.lte) >= Number(q.gte))
112
+ .map((q) => ({ gte: Number(q.gte), lte: Number(q.lte), at: verifiedAt(q) }))
113
+ .sort((a, b) => a.gte - b.gte || a.lte - b.lte);
114
+ const merged = [];
115
+ const gap = Number.isFinite(Number(bucketMs)) && Number(bucketMs) > 0 ? Number(bucketMs) : 0;
116
+ for (const q of clean) {
117
+ const top = merged[merged.length - 1];
118
+ if (top && q.gte <= top.lte + gap && top.at === q.at) {
119
+ if (q.lte > top.lte)
120
+ top.lte = q.lte;
121
+ }
122
+ else {
123
+ merged.push({ gte: q.gte, lte: q.lte, at: q.at });
124
+ }
125
+ }
126
+ return merged;
127
+ }
128
+ /**
129
+ * Bound the persisted span list. Because spans merge only when they assert the
130
+ * same `at`, a shard that is re-verified on every run gains one span per run
131
+ * and would otherwise grow without limit. Dropping the OLDEST spans never
132
+ * invents emptiness. The input is already sorted by extent, so the tail is
133
+ * newest.
134
+ */
135
+ function compactCoverage(spans, maxSpans) {
136
+ const list = spans || [];
137
+ const max = Number.isFinite(Number(maxSpans)) && Number(maxSpans) >= 1 ? Math.floor(Number(maxSpans)) : list.length;
138
+ return list.length <= max ? list : list.slice(list.length - max);
139
+ }
140
+ function rangesCoveredBy(have, want) {
141
+ for (const w of want || []) {
142
+ let covered = false;
143
+ for (const h of have || []) {
144
+ if (h.gte <= w.gte && h.lte >= w.lte) {
145
+ covered = true;
146
+ break;
147
+ }
148
+ }
149
+ if (!covered)
150
+ return false;
151
+ }
152
+ return true;
153
+ }
154
+ /**
155
+ * Change detection for shard writes: `have` already accounts for every span in
156
+ * `want`, in extent AND in verification time. Without the `at` half, a run
157
+ * whose only news is "these buckets were re-verified 1h later" would skip the
158
+ * write and the next run would fall back to the wide fixed refresh window.
159
+ * An unknown `at` on either side is never treated as fresh.
160
+ */
161
+ function coverageSatisfied(have, want) {
162
+ if (!rangesCoveredBy(have, want))
163
+ return false;
164
+ for (const w of want || []) {
165
+ const wAt = verifiedAt(w);
166
+ if (wAt == null)
167
+ continue;
168
+ let fresh = false;
169
+ for (const h of have || []) {
170
+ if (h.gte > w.gte || h.lte < w.lte)
171
+ continue;
172
+ const hAt = verifiedAt(h);
173
+ if (hAt != null && hAt >= wAt) {
174
+ fresh = true;
175
+ break;
176
+ }
177
+ }
178
+ if (!fresh)
179
+ return false;
180
+ }
181
+ return true;
182
+ }
183
+ /** Every recorded span across the loaded files, newest verification included. */
184
+ function allQueriedRanges(fileCover) {
185
+ const out = [];
186
+ for (const f of fileCover || []) {
187
+ for (const q of f?.queried || []) {
188
+ if (q && Number.isFinite(Number(q.gte)) && Number.isFinite(Number(q.lte)))
189
+ out.push(q);
190
+ }
191
+ }
192
+ return out;
193
+ }
194
+ function clipRangeTo(q, gteMs, lteMs) {
195
+ const gte = Math.max(q.gte, gteMs);
196
+ const lte = Math.min(q.lte, lteMs);
197
+ return lte >= gte ? { gte, lte, at: verifiedAt(q) } : null;
198
+ }
199
+ /** Sort and merge overlapping / adjacent (integer-ms) spans. */
200
+ function mergeSpans(spans) {
201
+ const sorted = [...spans].sort((a, b) => a.gte - b.gte || a.lte - b.lte);
202
+ const merged = [];
203
+ for (const s of sorted) {
204
+ const top = merged[merged.length - 1];
205
+ if (top && s.gte <= top.lte + 1) {
206
+ if (s.lte > top.lte)
207
+ top.lte = s.lte;
208
+ }
209
+ else {
210
+ merged.push({ ...s });
211
+ }
212
+ }
213
+ return merged;
214
+ }
215
+ /** `span` minus the union of `covered` (both as inclusive ms ranges). */
216
+ function subtractRanges(span, covered) {
217
+ let parts = [{ ...span }];
218
+ for (const c of mergeSpans(covered)) {
219
+ const next = [];
220
+ for (const p of parts) {
221
+ if (c.lte < p.gte || c.gte > p.lte) {
222
+ next.push(p);
223
+ continue;
224
+ }
225
+ if (c.gte > p.gte)
226
+ next.push({ gte: p.gte, lte: Math.min(p.lte, c.gte - 1) });
227
+ if (c.lte < p.lte)
228
+ next.push({ gte: Math.max(p.gte, c.lte + 1), lte: p.lte });
229
+ }
230
+ parts = next.filter((p) => p.lte >= p.gte);
231
+ if (parts.length === 0)
232
+ break;
233
+ }
234
+ return parts;
235
+ }
236
+ export { shardKeyForTimestamp, shardBoundsForKey, shardKeysForRange, shardPathFor, shardKeyFromName, shardStemFromName, timestampMs, verifiedAt, unionQueriedRanges, compactCoverage, rangesCoveredBy, coverageSatisfied, allQueriedRanges, clipRangeTo, mergeSpans, subtractRanges, };
237
+ //# sourceMappingURL=month_shards.js.map
@@ -64,8 +64,8 @@
64
64
  * "targetSpreadPercent": 2,
65
65
  * "weightDistribution": { "sell": 1, "buy": 1 },
66
66
  * "botFunds": { "sell": "100%", "buy": "100%" },
67
- * "activeOrders": { "sell": 20, "buy": 20 },
68
- * "reserveOrders": { "buy": 0, "sell": 0 }, // Edge reserves: extra live orders (buy: floor, sell: ceiling)
67
+ * "coreOrders": { "sell": 20, "buy": 20 },
68
+ * "edgeOrders": { "buy": 0, "sell": 0 }, // Edge orders: extra live orders (buy: floor, sell: ceiling)
69
69
  * "poolRef": null, // Optional pinned pool ID for startPrice "pool"
70
70
  * "debtPolicy": { ... }, // MPA/credit lending policy — docs/MPA_CREDIT_USAGE.md
71
71
  * "min_BTS_value": 0, // Minimum BTS value threshold for operations
@@ -144,6 +144,7 @@ declare function loadGeneralSettings(): {
144
144
  RETRY_BACKOFF_CAP_MS: number;
145
145
  DAEMON_PING_TIMEOUT_MS: number;
146
146
  CREDENTIAL_DAEMON_WATCHDOG_MS: number;
147
+ CREDENTIAL_DAEMON_WATCHDOG_FAILURE_THRESHOLD: number;
147
148
  RUN_LOOP_DEFAULT_MS: number;
148
149
  OPEN_ORDERS_SYNC_LOOP_ENABLED: boolean;
149
150
  CHECK_INTERVAL_MS: number;
@@ -156,6 +157,7 @@ declare function loadGeneralSettings(): {
156
157
  FILL_TOTALS_RETRY_MAX_MS: number;
157
158
  SPREAD_STALE_WARN_MS: number;
158
159
  SPREAD_STALE_ESCALATE_MS: number;
160
+ SPREAD_CORRECTION_SYNC_FRESH_MS: number;
159
161
  SPREAD_STALE_RESYNC_COOLDOWN_MS: number;
160
162
  BOUNDARY_HOLD_RESYNC_THRESHOLD: number;
161
163
  BOUNDARY_HOLD_RESYNC_COOLDOWN_MS: number;
@@ -378,11 +380,11 @@ declare function loadGeneralSettings(): {
378
380
  sell: string;
379
381
  buy: string;
380
382
  };
381
- activeOrders: {
383
+ coreOrders: {
382
384
  sell: number;
383
385
  buy: number;
384
386
  };
385
- reserveOrders: {
387
+ edgeOrders: {
386
388
  buy: number;
387
389
  sell: number;
388
390
  };
@@ -681,7 +683,7 @@ declare function isPoolRefClearInput(value: unknown): boolean;
681
683
  interface BotDraft extends UnknownRecord {
682
684
  accountId?: string;
683
685
  active?: boolean;
684
- activeOrders: {
686
+ coreOrders: {
685
687
  sell?: number;
686
688
  buy?: number;
687
689
  };
@@ -699,7 +701,7 @@ interface BotDraft extends UnknownRecord {
699
701
  name?: string;
700
702
  poolRef?: string | null;
701
703
  preferredAccount?: string;
702
- reserveOrders?: {
704
+ edgeOrders?: {
703
705
  sell?: number;
704
706
  buy?: number;
705
707
  };
@@ -64,8 +64,8 @@
64
64
  * "targetSpreadPercent": 2,
65
65
  * "weightDistribution": { "sell": 1, "buy": 1 },
66
66
  * "botFunds": { "sell": "100%", "buy": "100%" },
67
- * "activeOrders": { "sell": 20, "buy": 20 },
68
- * "reserveOrders": { "buy": 0, "sell": 0 }, // Edge reserves: extra live orders (buy: floor, sell: ceiling)
67
+ * "coreOrders": { "sell": 20, "buy": 20 },
68
+ * "edgeOrders": { "buy": 0, "sell": 0 }, // Edge orders: extra live orders (buy: floor, sell: ceiling)
69
69
  * "poolRef": null, // Optional pinned pool ID for startPrice "pool"
70
70
  * "debtPolicy": { ... }, // MPA/credit lending policy — docs/MPA_CREDIT_USAGE.md
71
71
  * "min_BTS_value": 0, // Minimum BTS value threshold for operations
@@ -414,22 +414,7 @@ async function askWeightDistributionValue(promptText, defaultValue, showLegend)
414
414
  if (showLegend) {
415
415
  console.log(` ${COLORS.cyan}-1=SuperValley${COLORS.reset} ←→ ${COLORS.blue}0=Valley${COLORS.reset} ←→ ${COLORS.gray}0.5=Neutral${COLORS.reset} ←→ ${COLORS.bold}${COLORS.orange}1=Mountain${COLORS.reset} ←→ ${COLORS.redStrong}2=SuperMountain${COLORS.reset}`);
416
416
  }
417
- const suffix = defaultValue !== undefined && defaultValue !== null ? ` [${defaultValue}]` : '';
418
- const raw = (await readInput(`${promptText}${suffix}: `)).trim();
419
- if (raw === '\x1b')
420
- return '\x1b';
421
- if (raw === '')
422
- return defaultValue;
423
- const parsed = Number(raw);
424
- if (Number.isNaN(parsed)) {
425
- console.log('Please enter a valid number.');
426
- return askWeightDistributionValue(promptText, defaultValue, showLegend);
427
- }
428
- if (parsed < MIN_WEIGHT || parsed > MAX_WEIGHT) {
429
- console.log(`Weight distribution must be between ${MIN_WEIGHT} and ${MAX_WEIGHT}.`);
430
- return askWeightDistributionValue(promptText, defaultValue, showLegend);
431
- }
432
- return parsed;
417
+ return askNumeric(promptText, defaultValue, (parsed) => parsed < MIN_WEIGHT || parsed > MAX_WEIGHT ? `Weight distribution must be between ${MIN_WEIGHT} and ${MAX_WEIGHT}.` : null);
433
418
  }
434
419
  /**
435
420
  * Prompts the user for a weight distribution value with a legend.
@@ -723,6 +708,24 @@ async function askNumeric(promptText, defaultValue, validate) {
723
708
  }
724
709
  return parsed;
725
710
  }
711
+ async function askTypedInput(options) {
712
+ options.onBeforePrompt?.();
713
+ const { promptText, defaultValue } = options;
714
+ const shown = defaultValue !== undefined && defaultValue !== null
715
+ ? ` [${options.formatDefault ? options.formatDefault(defaultValue) : String(defaultValue)}]`
716
+ : '';
717
+ const raw = (await readInput(`${promptText}${shown}: `, options.colorize ? { colorize: options.colorize } : {})).trim();
718
+ if (raw === '\x1b')
719
+ return '\x1b';
720
+ if (raw === '')
721
+ return defaultValue;
722
+ const result = options.parse(raw);
723
+ if ('error' in result) {
724
+ console.log(result.error);
725
+ return askTypedInput(options);
726
+ }
727
+ return result.value;
728
+ }
726
729
  /**
727
730
  * Prompts the user for a number within specified bounds.
728
731
  * @param {string} promptText - The prompt text to display.
@@ -837,34 +840,28 @@ function validateMultiplierInput(promptText, raw) {
837
840
  * @returns {Promise<number|string>} The value or '\x1b' if ESC.
838
841
  */
839
842
  async function askNumberOrMultiplier(promptText, defaultValue) {
840
- // Pre-entry legend for Range bounds (mirrors weight mountain legend)
841
- if (/^(minPrice|maxPrice)/i.test(promptText))
842
- printRangeQualityLegend();
843
- const suffix = defaultValue !== undefined && defaultValue !== null ? ` [${colorPriceRangeValue(defaultValue)}]` : '';
844
- const raw = (await readInput(`${promptText}${suffix}: `, { colorize: (input) => colorRangeValueByQuality(input) })).trim();
845
- if (raw === '\x1b')
846
- return '\x1b';
847
- if (raw === '')
848
- return defaultValue;
849
- if (isMultiplierString(raw)) {
850
- const result = validateMultiplierInput(promptText, raw);
851
- if ('error' in result) {
852
- console.log(result.error);
853
- return askNumberOrMultiplier(promptText, defaultValue);
854
- }
855
- return result.value;
856
- }
857
- const parsed = Number(raw);
858
- if (Number.isNaN(parsed)) {
859
- console.log('Please enter a valid number or multiplier (e.g. 5x).');
860
- return askNumberOrMultiplier(promptText, defaultValue);
861
- }
862
- // Validate that number is > 0 (for price inputs)
863
- if (parsed <= 0) {
864
- console.log(`Invalid ${promptText}: ${parsed}. Must be > 0 (positive number)`);
865
- return askNumberOrMultiplier(promptText, defaultValue);
866
- }
867
- return parsed;
843
+ return askTypedInput({
844
+ promptText,
845
+ defaultValue,
846
+ // Pre-entry legend for Range bounds (mirrors weight mountain legend)
847
+ onBeforePrompt: () => { if (/^(minPrice|maxPrice)/i.test(promptText))
848
+ printRangeQualityLegend(); },
849
+ formatDefault: colorPriceRangeValue,
850
+ colorize: colorRangeValueByQuality,
851
+ parse: (raw) => {
852
+ if (isMultiplierString(raw)) {
853
+ const result = validateMultiplierInput(promptText, raw);
854
+ return 'error' in result ? result : { value: result.value };
855
+ }
856
+ const parsed = Number(raw);
857
+ if (Number.isNaN(parsed))
858
+ return { error: 'Please enter a valid number or multiplier (e.g. 5x).' };
859
+ // Validate that number is > 0 (for price inputs)
860
+ if (parsed <= 0)
861
+ return { error: `Invalid ${promptText}: ${parsed}. Must be > 0 (positive number)` };
862
+ return { value: parsed };
863
+ },
864
+ });
868
865
  }
869
866
  /**
870
867
  * Prompts the user for the maximum price, ensuring it's greater than minimum price.
@@ -874,43 +871,36 @@ async function askNumberOrMultiplier(promptText, defaultValue) {
874
871
  * @returns {Promise<number|string>} The value or '\x1b' if ESC.
875
872
  */
876
873
  async function askMaxPrice(promptText, defaultValue, minPrice) {
877
- printRangeQualityLegend();
878
- const suffix = defaultValue !== undefined && defaultValue !== null ? ` [${colorPriceRangeValue(defaultValue)}]` : '';
879
- const raw = (await readInput(`${promptText}${suffix}: `, { colorize: (input) => colorRangeValueByQuality(input) })).trim();
880
- if (raw === '\x1b')
881
- return '\x1b';
882
- if (raw === '')
883
- return defaultValue;
884
- if (isMultiplierString(raw)) {
885
- const result = validateMultiplierInput(promptText, raw);
886
- if ('error' in result) {
887
- console.log(result.error);
888
- return askMaxPrice(promptText, defaultValue, minPrice);
889
- }
890
- return result.value;
891
- }
892
- const parsed = Number(raw);
893
- if (Number.isNaN(parsed)) {
894
- console.log('Please enter a valid number or multiplier (e.g. 5x).');
895
- return askMaxPrice(promptText, defaultValue, minPrice);
896
- }
897
- // Validate that number is > 0 (for price inputs)
898
- if (parsed <= 0) {
899
- console.log(`Invalid ${promptText}: ${parsed}. Must be > 0 (positive number)`);
900
- return askMaxPrice(promptText, defaultValue, minPrice);
901
- }
902
- // Validate that maxPrice > minPrice. Only comparable when minPrice is an
903
- // absolute value: a relative min ("2x") needs the grid center to resolve,
904
- // so it can't be checked here — the runtime bound validation covers it
905
- // (previously parseFloat("2x") == 2 wrongly rejected any absolute price <= 2).
906
- if (!isMultiplierString(minPrice)) {
907
- const minPriceValue = typeof minPrice === 'string' ? parseFloat(minPrice) : minPrice;
908
- if (minPriceValue != null && parsed <= minPriceValue) {
909
- console.log(`Invalid ${promptText}: ${parsed}. Must be > minPrice (${minPriceValue})`);
910
- return askMaxPrice(promptText, defaultValue, minPrice);
911
- }
912
- }
913
- return parsed;
874
+ return askTypedInput({
875
+ promptText,
876
+ defaultValue,
877
+ onBeforePrompt: printRangeQualityLegend,
878
+ formatDefault: colorPriceRangeValue,
879
+ colorize: colorRangeValueByQuality,
880
+ parse: (raw) => {
881
+ if (isMultiplierString(raw)) {
882
+ const result = validateMultiplierInput(promptText, raw);
883
+ return 'error' in result ? result : { value: result.value };
884
+ }
885
+ const parsed = Number(raw);
886
+ if (Number.isNaN(parsed))
887
+ return { error: 'Please enter a valid number or multiplier (e.g. 5x).' };
888
+ // Validate that number is > 0 (for price inputs)
889
+ if (parsed <= 0)
890
+ return { error: `Invalid ${promptText}: ${parsed}. Must be > 0 (positive number)` };
891
+ // Validate that maxPrice > minPrice. Only comparable when minPrice is an
892
+ // absolute value: a relative min ("2x") needs the grid center to resolve,
893
+ // so it can't be checked here — the runtime bound validation covers it
894
+ // (previously parseFloat("2x") == 2 wrongly rejected any absolute price <= 2).
895
+ if (!isMultiplierString(minPrice)) {
896
+ const minPriceValue = typeof minPrice === 'string' ? parseFloat(minPrice) : minPrice;
897
+ if (minPriceValue != null && parsed <= minPriceValue) {
898
+ return { error: `Invalid ${promptText}: ${parsed}. Must be > minPrice (${minPriceValue})` };
899
+ }
900
+ }
901
+ return { value: parsed };
902
+ },
903
+ });
914
904
  }
915
905
  /**
916
906
  * Normalizes a percentage string input.
@@ -935,21 +925,21 @@ function normalizePercentageInput(value) {
935
925
  * @returns {Promise<number|string>} The value or '\x1b' if ESC.
936
926
  */
937
927
  async function askNumberOrPercentage(promptText, defaultValue) {
938
- const suffix = defaultValue !== undefined && defaultValue !== null ? ` [${colorPercentageInput(defaultValue)}]` : '';
939
- const raw = (await readInput(`${promptText}${suffix}: `, { colorize: (input) => colorPercentageInput(input) })).trim();
940
- if (raw === '\x1b')
941
- return '\x1b';
942
- if (raw === '')
943
- return defaultValue;
944
- const percent = normalizePercentageInput(raw);
945
- if (percent !== null)
946
- return percent;
947
- const parsed = Number(raw);
948
- if (Number.isNaN(parsed)) {
949
- console.log('Please enter a valid number or percentage (e.g. 100, 50%).');
950
- return askNumberOrPercentage(promptText, defaultValue);
951
- }
952
- return parsed;
928
+ return askTypedInput({
929
+ promptText,
930
+ defaultValue,
931
+ formatDefault: colorPercentageInput,
932
+ colorize: colorPercentageInput,
933
+ parse: (raw) => {
934
+ const percent = normalizePercentageInput(raw);
935
+ if (percent !== null)
936
+ return { value: percent };
937
+ const parsed = Number(raw);
938
+ if (Number.isNaN(parsed))
939
+ return { error: 'Please enter a valid number or percentage (e.g. 100, 50%).' };
940
+ return { value: parsed };
941
+ },
942
+ });
953
943
  }
954
944
  /**
955
945
  * Parses a raw boolean answer.
@@ -999,31 +989,22 @@ async function askBoolean(promptText, defaultValue) {
999
989
  * @returns {Promise<number|string>} The start price or '\x1b' if ESC.
1000
990
  */
1001
991
  async function askStartPrice(promptText, defaultValue) {
1002
- while (true) {
1003
- const suffix = defaultValue !== undefined && defaultValue !== null ? ` [${colorStartPriceValue(defaultValue)}]` : '';
1004
- const raw = (await readInput(`${promptText}${suffix}: `, {
1005
- colorize: (input) => colorStartPriceValue(input)
1006
- })).trim();
1007
- if (raw === '\x1b')
1008
- return '\x1b';
1009
- if (!raw) {
1010
- if (defaultValue !== undefined && defaultValue !== null) {
1011
- return defaultValue;
1012
- }
1013
- return undefined;
1014
- }
1015
- const lower = raw.toLowerCase();
1016
- if (lower === 'pool')
1017
- return lower;
1018
- if (lower === 'book')
1019
- return 'book';
1020
- // Accept numeric values (including decimals)
1021
- const num = Number(raw);
1022
- if (!Number.isNaN(num) && Number.isFinite(num)) {
1023
- return num;
1024
- }
1025
- console.log('Please enter "pool", "book", or a numeric value.');
1026
- }
992
+ return askTypedInput({
993
+ promptText,
994
+ defaultValue,
995
+ formatDefault: colorStartPriceValue,
996
+ colorize: colorStartPriceValue,
997
+ parse: (raw) => {
998
+ const lower = raw.toLowerCase();
999
+ if (lower === 'pool' || lower === 'book')
1000
+ return { value: lower };
1001
+ // Accept numeric values (including decimals)
1002
+ const num = Number(raw);
1003
+ if (!Number.isNaN(num) && Number.isFinite(num))
1004
+ return { value: num };
1005
+ return { error: 'Please enter "pool", "book", or a numeric value.' };
1006
+ },
1007
+ });
1027
1008
  }
1028
1009
  /**
1029
1010
  * Spellings that clear a `poolRef` pin, leaving the runtime to auto-select
@@ -1293,7 +1274,7 @@ async function promptBotData(base = {}, index = 0, baseIndex = index) {
1293
1274
  console.log(`${COLORS.yellowBold}2) Identity:${COLORS.reset} ${COLORS.orange}Name:${COLORS.reset} ${data.name || '?'}, ${COLORS.orange}Account:${COLORS.reset} ${data.preferredAccount || '?'} | ${COLORS.orange}Active:${COLORS.reset} ${colorBooleanFlag(data.active, true)}, ${COLORS.orange}DryRun:${COLORS.reset} ${colorBooleanFlag(data.dryRun, false)}`);
1294
1275
  console.log(`${COLORS.yellowBold}3) Price:${COLORS.reset} ${COLORS.orange}Range:${COLORS.reset} [${colorPriceRangeValue(data.minPrice)} - ${colorPriceRangeValue(data.maxPrice)}] | ${COLORS.orange}Start:${COLORS.reset} ${colorStartPriceValue(data.startPrice)}, ${COLORS.orange}Pool:${COLORS.reset} ${formatPoolRefLabel(data)} | ${COLORS.orange}GridPrice:${COLORS.reset} ${colorGridPriceValue(data.gridPrice)}`);
1295
1276
  console.log(`${COLORS.yellowBold}4) Grid:${COLORS.reset} ${COLORS.orange}Weights:${COLORS.reset} (S:${data.weightDistribution.sell}, B:${data.weightDistribution.buy}) | ${COLORS.orange}Increment:${COLORS.reset} ${data.incrementPercent}%, ${COLORS.orange}Spread:${COLORS.reset} ${data.targetSpreadPercent}%`);
1296
- console.log(`${COLORS.yellowBold}5) Inventory:${COLORS.reset} ${COLORS.orange}Sell:${COLORS.reset} ${colorPercentageInput(data.botFunds.sell)}, ${COLORS.orange}Buy:${COLORS.reset} ${colorPercentageInput(data.botFunds.buy)} | ${COLORS.orange}MarketOrder:${COLORS.reset} (S:${data.activeOrders.sell}, B:${data.activeOrders.buy}) | ${COLORS.orange}EdgeOrder:${COLORS.reset} (S:${data.reserveOrders?.sell ?? 0}, B:${data.reserveOrders?.buy ?? 0})`);
1277
+ console.log(`${COLORS.yellowBold}5) Inventory:${COLORS.reset} ${COLORS.orange}Sell:${COLORS.reset} ${colorPercentageInput(data.botFunds.sell)}, ${COLORS.orange}Buy:${COLORS.reset} ${colorPercentageInput(data.botFunds.buy)} | ${COLORS.orange}CoreOrder:${COLORS.reset} (S:${data.coreOrders.sell}, B:${data.coreOrders.buy}) | ${COLORS.orange}EdgeOrder:${COLORS.reset} (S:${data.edgeOrders?.sell ?? 0}, B:${data.edgeOrders?.buy ?? 0})`);
1297
1278
  {
1298
1279
  const flags = adapterFlags();
1299
1280
  const inert = !isAmaGridPriceDraft() && (flags.ama || flags.dynamicWeight || flags.asymmetricBounds);
@@ -1437,23 +1418,23 @@ async function promptBotData(base = {}, index = 0, baseIndex = index) {
1437
1418
  const fBuy = await askNumberOrPercentage('botFunds buy amount', data.botFunds.buy);
1438
1419
  if (fBuy === undefined || fBuy === '\x1b')
1439
1420
  break;
1440
- const oSell = await askIntegerInRange('activeOrders sell count', data.activeOrders.sell, 1, 100);
1421
+ const oSell = await askIntegerInRange('coreOrders sell count', data.coreOrders.sell, 1, 100);
1441
1422
  if (typeof oSell !== 'number')
1442
1423
  break;
1443
- const oBuy = await askIntegerInRange('activeOrders buy count', data.activeOrders.buy, 1, 100);
1424
+ const oBuy = await askIntegerInRange('coreOrders buy count', data.coreOrders.buy, 1, 100);
1444
1425
  if (typeof oBuy !== 'number')
1445
1426
  break;
1446
- const rBuy = await askIntegerInRange('reserveOrders buy floor count (0 disables)', data.reserveOrders?.buy ?? 0, 0, 100);
1427
+ const rBuy = await askIntegerInRange('edgeOrders buy floor count (0 disables)', data.edgeOrders?.buy ?? 0, 0, 100);
1447
1428
  if (typeof rBuy !== 'number')
1448
1429
  break;
1449
- const rSell = await askIntegerInRange('reserveOrders sell ceiling count (0 disables)', data.reserveOrders?.sell ?? 0, 0, 100);
1430
+ const rSell = await askIntegerInRange('edgeOrders sell ceiling count (0 disables)', data.edgeOrders?.sell ?? 0, 0, 100);
1450
1431
  if (typeof rSell !== 'number')
1451
1432
  break;
1452
1433
  data.botFunds.sell = fSell;
1453
1434
  data.botFunds.buy = fBuy;
1454
- data.activeOrders.sell = oSell;
1455
- data.activeOrders.buy = oBuy;
1456
- data.reserveOrders = { buy: rBuy, sell: rSell };
1435
+ data.coreOrders.sell = oSell;
1436
+ data.coreOrders.buy = oBuy;
1437
+ data.edgeOrders = { buy: rBuy, sell: rSell };
1457
1438
  showMenu = true;
1458
1439
  break;
1459
1440
  case '6': {