dexbot 1.6.12 → 1.6.13

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 (170) hide show
  1. package/CHANGELOG.md +33 -1
  2. package/analysis/README.md +9 -11
  3. package/analysis/ama_fitting/README.md +5 -3
  4. package/claw/README.md +1 -0
  5. package/claw/docs/AI_BOT_LIBRARY_API.md +2 -0
  6. package/claw/modules/claw_bridge.ts +0 -3
  7. package/claw/modules/claw_skill_md.ts +1 -0
  8. package/claw/package.json +3 -3
  9. package/claw/runtimes/openclaw-plugin/openclaw.plugin.json +1 -1
  10. package/claw/runtimes/openclaw-plugin/package.json +1 -1
  11. package/claw/tsconfig.json +2 -2
  12. package/dist/analysis/ama_fitting/analyze_lambda_vs_slow.js +1 -14
  13. package/dist/analysis/ama_fitting/fetch_lp_candles.js +51 -41
  14. package/dist/analysis/ama_fitting/generate_unified_comparison_chart.d.ts +1 -24
  15. package/dist/analysis/ama_fitting/generate_unified_comparison_chart.js +36 -18
  16. package/dist/analysis/ama_fitting/optimizer_high_resolution.js +18 -66
  17. package/dist/analysis/analyze_args.d.ts +12 -0
  18. package/dist/analysis/analyze_args.js +20 -0
  19. package/dist/analysis/bot_fitting/backtest_ama_sweep.d.ts +1 -16
  20. package/dist/analysis/bot_fitting/backtest_ama_sweep.js +20 -101
  21. package/dist/analysis/bot_fitting/backtest_bot_fitting.js +26 -92
  22. package/dist/analysis/bot_fitting/backtest_lookback_drawdown.js +19 -34
  23. package/dist/analysis/bot_fitting/shared_utils.d.ts +71 -3
  24. package/dist/analysis/bot_fitting/shared_utils.js +124 -8
  25. package/dist/analysis/chart_ui.d.ts +30 -1
  26. package/dist/analysis/chart_ui.js +37 -1
  27. package/dist/analysis/fills_cache.d.ts +3 -23
  28. package/dist/analysis/fills_cache.js +3 -84
  29. package/dist/analysis/fills_source.d.ts +31 -1
  30. package/dist/analysis/fills_source.js +69 -1
  31. package/dist/analysis/grid_correction_check.d.ts +1 -23
  32. package/dist/analysis/grid_correction_check.js +15 -58
  33. package/dist/analysis/math_utils.d.ts +85 -1
  34. package/dist/analysis/math_utils.js +116 -1
  35. package/dist/analysis/price_sources.d.ts +22 -1
  36. package/dist/analysis/price_sources.js +23 -0
  37. package/dist/analysis/resolve_source.js +31 -10
  38. package/dist/analysis/trade_profitability.d.ts +6 -0
  39. package/dist/analysis/trade_profitability.js +23 -97
  40. package/dist/analysis/tradingview/analyze_tradingview.d.ts +1 -17
  41. package/dist/analysis/tradingview/analyze_tradingview.js +1 -1
  42. package/dist/analysis/tradingview/tradingview_uplot_chart_generator.js +2 -15
  43. package/dist/analysis/trend_detection/backtest_ama_slope_huber.d.ts +1 -101
  44. package/dist/analysis/trend_detection/backtest_ama_slope_huber.js +22 -80
  45. package/dist/analysis/trend_detection/dynamic_weight_chart_generator.js +11 -37
  46. package/dist/analysis/trend_detection/volatility_chart_generator.js +9 -10
  47. package/dist/analysis/worker_pool.d.ts +38 -0
  48. package/dist/analysis/worker_pool.js +67 -0
  49. package/dist/dexbot.js +67 -48
  50. package/dist/market_adapter/ama_signal_runner.js +21 -54
  51. package/dist/market_adapter/candle_utils.d.ts +7 -1
  52. package/dist/market_adapter/candle_utils.js +11 -1
  53. package/dist/market_adapter/cli_args.d.ts +22 -0
  54. package/dist/market_adapter/cli_args.js +30 -0
  55. package/dist/market_adapter/core/config_normalizers.js +11 -6
  56. package/dist/market_adapter/core/kibana_candles.d.ts +3 -1
  57. package/dist/market_adapter/core/kibana_candles.js +3 -2
  58. package/dist/market_adapter/core/market_adapter_service.d.ts +85 -85
  59. package/dist/market_adapter/core/market_adapter_service.js +93 -158
  60. package/dist/market_adapter/core/signals/hurst_analyzer.d.ts +1 -6
  61. package/dist/market_adapter/core/signals/hurst_analyzer.js +1 -1
  62. package/dist/market_adapter/core/signals/permutation_entropy_analyzer.d.ts +1 -11
  63. package/dist/market_adapter/core/signals/permutation_entropy_analyzer.js +1 -1
  64. package/dist/market_adapter/inputs/fetch_book_data.js +0 -1
  65. package/dist/market_adapter/inputs/fetch_cex_synthetic_data.js +63 -107
  66. package/dist/market_adapter/inputs/fetch_lp_data.d.ts +8 -1
  67. package/dist/market_adapter/inputs/fetch_lp_data.js +25 -7
  68. package/dist/market_adapter/inputs/kibana_feed_source.js +4 -26
  69. package/dist/market_adapter/inputs/window_cache.d.ts +4 -72
  70. package/dist/market_adapter/inputs/window_cache.js +52 -177
  71. package/dist/market_adapter/interval_utils.d.ts +11 -1
  72. package/dist/market_adapter/interval_utils.js +16 -1
  73. package/dist/market_adapter/lp_chart_runner.d.ts +3 -0
  74. package/dist/market_adapter/lp_chart_runner.js +37 -19
  75. package/dist/market_adapter/market_adapter.js +27 -72
  76. package/dist/market_adapter/utils/data_discovery.d.ts +45 -1
  77. package/dist/market_adapter/utils/data_discovery.js +220 -27
  78. package/dist/market_adapter/utils/month_shards.d.ts +84 -0
  79. package/dist/market_adapter/utils/month_shards.js +237 -0
  80. package/dist/modules/account_bots.d.ts +1 -0
  81. package/dist/modules/account_bots.js +102 -121
  82. package/dist/modules/account_orders.d.ts +13 -0
  83. package/dist/modules/account_orders.js +38 -44
  84. package/dist/modules/bitshares-native/chain_client.d.ts +1 -1
  85. package/dist/modules/bitshares-native/chain_client.js +14 -13
  86. package/dist/modules/bitshares-native/resolvers.js +22 -25
  87. package/dist/modules/bitshares-native/serial/types.js +22 -50
  88. package/dist/modules/bitshares-native/signing_client.d.ts +1 -1
  89. package/dist/modules/bot_defaults.d.ts +2 -1
  90. package/dist/modules/bot_settings.d.ts +1 -1
  91. package/dist/modules/broadcast_failure.d.ts +2 -1
  92. package/dist/modules/chain_orders.d.ts +1 -1
  93. package/dist/modules/chain_orders.js +51 -96
  94. package/dist/modules/cli_start_onboarding.d.ts +2 -1
  95. package/dist/modules/constants.d.ts +7 -1
  96. package/dist/modules/constants.js +20 -1
  97. package/dist/modules/cr_planner.d.ts +1 -1
  98. package/dist/modules/cr_planner.js +1 -5
  99. package/dist/modules/credit_pricing.d.ts +2 -1
  100. package/dist/modules/credit_pricing.js +36 -40
  101. package/dist/modules/credit_runtime.d.ts +7 -0
  102. package/dist/modules/credit_runtime.js +45 -73
  103. package/dist/modules/daemon_node_health.d.ts +4 -3
  104. package/dist/modules/dexbot_class.d.ts +28 -17
  105. package/dist/modules/dexbot_class.js +105 -58
  106. package/dist/modules/dexbot_cow_runtime.d.ts +0 -7
  107. package/dist/modules/dexbot_cow_runtime.js +54 -28
  108. package/dist/modules/dexbot_credential_client.d.ts +0 -7
  109. package/dist/modules/dexbot_credential_client.js +1 -2
  110. package/dist/modules/dexbot_fill_runtime.d.ts +1 -2
  111. package/dist/modules/dexbot_fill_runtime.js +5 -6
  112. package/dist/modules/dexbot_maintenance_runtime.d.ts +20 -3
  113. package/dist/modules/dexbot_maintenance_runtime.js +84 -69
  114. package/dist/modules/dexbot_startup_runtime.d.ts +0 -1
  115. package/dist/modules/dexbot_startup_runtime.js +13 -14
  116. package/dist/modules/general_settings.d.ts +1 -1
  117. package/dist/modules/graceful_shutdown.js +17 -11
  118. package/dist/modules/key_store.js +0 -1
  119. package/dist/modules/lazy_shim.d.ts +11 -0
  120. package/dist/modules/lazy_shim.js +16 -0
  121. package/dist/modules/node_connect_policy.d.ts +3 -2
  122. package/dist/modules/node_failure_ledger.d.ts +6 -5
  123. package/dist/modules/order/format.d.ts +12 -3
  124. package/dist/modules/order/format.js +15 -3
  125. package/dist/modules/order/genesis_policy.d.ts +3 -3
  126. package/dist/modules/order/genesis_policy.js +5 -2
  127. package/dist/modules/order/grid.d.ts +4 -2
  128. package/dist/modules/order/grid.js +91 -35
  129. package/dist/modules/order/index.d.ts +1 -0
  130. package/dist/modules/order/logger.d.ts +1 -8
  131. package/dist/modules/order/logger.js +0 -9
  132. package/dist/modules/order/manager.d.ts +9 -13
  133. package/dist/modules/order/manager.js +33 -50
  134. package/dist/modules/order/utils/order.js +39 -35
  135. package/dist/modules/order/utils/system.d.ts +9 -29
  136. package/dist/modules/order/utils/system.js +17 -2
  137. package/dist/modules/order/utils/validate.js +2 -2
  138. package/dist/modules/order/utils/withPoolRef.d.ts +2 -1
  139. package/dist/modules/paths.js +32 -34
  140. package/dist/modules/runtime_settings.d.ts +2 -4
  141. package/dist/modules/settings_merge.d.ts +2 -2
  142. package/dist/modules/socket_json_client.d.ts +2 -1
  143. package/dist/modules/types.d.ts +42 -27
  144. package/dist/modules/utils/errors.js +1 -3
  145. package/dist/modules/version_notice.d.ts +11 -10
  146. package/dist/pm2.d.ts +0 -1
  147. package/dist/pm2.js +56 -35
  148. package/dist/scripts/analyze-git.js +2 -15
  149. package/dist/scripts/chart_command.js +2 -2
  150. package/dist/scripts/check_any.d.ts +4 -0
  151. package/dist/scripts/check_any.js +53 -21
  152. package/dist/scripts/diagnose-pool-history.js +1 -6
  153. package/dist/scripts/run-tests.js +0 -1
  154. package/dist/scripts/sync-version.js +0 -10
  155. package/docs/BITSHARES_ONBOARDING.md +8 -12
  156. package/docs/COPY_ON_WRITE_MASTER_PLAN.md +1 -1
  157. package/docs/DEXBOT_COMPARISON.md +6 -6
  158. package/docs/EVOLUTION.md +9 -8
  159. package/docs/FUND_MOVEMENT_AND_ACCOUNTING.md +1 -1
  160. package/docs/README.md +1 -1
  161. package/docs/WORKFLOW.md +1 -0
  162. package/docs/architecture.md +19 -10
  163. package/market_adapter/README.md +6 -4
  164. package/package.json +6 -9
  165. package/scripts/README.md +43 -38
  166. package/tests/README.md +25 -10
  167. package/dist/scripts/diagnose-kibana-candles.d.ts +0 -3
  168. package/dist/scripts/diagnose-kibana-candles.js +0 -82
  169. package/scripts/git-viewer.sh +0 -489
  170. package/scripts/postinstall.js +0 -16
@@ -72,7 +72,7 @@ export interface PoolEntry {
72
72
  reserves?: PoolReserve[];
73
73
  [key: string]: unknown;
74
74
  }
75
- export interface BitSharesDb {
75
+ interface BitSharesDb {
76
76
  lookup_asset_symbols?: (refs: string[]) => Promise<unknown[]>;
77
77
  get_assets?: (refs: string[]) => Promise<unknown[]>;
78
78
  get_objects?: (ids: string[]) => Promise<unknown[]>;
@@ -96,7 +96,7 @@ export interface BitSharesDb {
96
96
  call?: (method: string, args: unknown[]) => Promise<unknown>;
97
97
  [key: string]: unknown;
98
98
  }
99
- export interface BitSharesAssets {
99
+ interface BitSharesAssets {
100
100
  [symbol: string]: Promise<unknown> | unknown;
101
101
  }
102
102
  export interface BitSharesClient {
@@ -189,15 +189,6 @@ export declare function derivePriceWithBridges(BitShares: BitSharesClient, symA:
189
189
  rate: number;
190
190
  path: string;
191
191
  } | null>;
192
- export interface ExtendedAssetMeta extends AssetMeta {
193
- current_supply?: number | string | {
194
- amount?: number;
195
- value?: number;
196
- };
197
- dynamic_asset_data_id?: string;
198
- dynamicDataId?: string;
199
- dynamic_data_id?: string;
200
- }
201
192
  /**
202
193
  * Derive the value of a liquidity pool share token in a denomination asset.
203
194
  * Resolves the pool, fetches reserves and supply, then prices both pool assets
@@ -252,12 +243,6 @@ export declare function loadAmaCenterSnapshot(botKey: string): AmaCenterSnapshot
252
243
  * @returns {number|null} Grid center price in B/A format, or null if file absent/invalid
253
244
  */
254
245
  export declare function loadAmaCenterPrice(botKey: string): number | null;
255
- export interface AssetOptions {
256
- flags?: number | string;
257
- market_fee_percent?: number;
258
- taker_fee_percent?: number;
259
- max_market_fee?: number | string;
260
- }
261
246
  export interface FeeCacheEntryData {
262
247
  assetId?: string;
263
248
  symbol?: string;
@@ -290,18 +275,6 @@ export interface FeeCacheEntryData {
290
275
  };
291
276
  makerFeeDiscountPercent?: number;
292
277
  }
293
- export interface GlobalProps {
294
- parameters?: {
295
- current_fees?: {
296
- parameters?: Array<[number, {
297
- fee?: number | string;
298
- }]>;
299
- };
300
- extensions?: {
301
- maker_fee_discount_percent?: number;
302
- };
303
- };
304
- }
305
278
  /**
306
279
  * Initialize fee cache from blockchain.
307
280
  * Fetches BTS operation fees and asset market fees for all unique assets in config.
@@ -601,6 +574,13 @@ export declare function deepFreeze<T>(obj: T): T;
601
574
  * @returns {Map}
602
575
  */
603
576
  export declare function cloneMap<K, V>(map: Map<K, V>): Map<K, V>;
577
+ /**
578
+ * Fire-and-forget structural grid resync. Invokes the manager's handler and
579
+ * logs both a synchronous throw and an async rejection through the manager
580
+ * logger, so escalation sites share one error-handling footer. No-op when the
581
+ * manager has no handler.
582
+ */
583
+ export declare function fireStructuralResync(bot: BotLike, reason: string, details: Record<string, unknown>, errorLabel: string, level?: string): void;
604
584
  /**
605
585
  * Parses JSON content that may contain comments (/* or //).
606
586
  * Strips block comments then line comments before parsing.
@@ -57,7 +57,7 @@ import * as MathUtils from './math.js';
57
57
  import * as OrderUtils from './order.js';
58
58
  import Logger from '../../order/logger.js';
59
59
  import { runtime } from '../../runtime.js';
60
- import { getErrorMessage } from '../../utils/errors.js';
60
+ import { getErrorMessage, sleepMs } from '../../utils/errors.js';
61
61
  import { normalizeAssetRef } from '../../utils/asset_symbols.js';
62
62
  import { withTimeout } from './timeout.js';
63
63
  const { ensureDir, readJSON } = storage;
@@ -1558,7 +1558,7 @@ export function nowIso() {
1558
1558
  * @returns {Promise<void>}
1559
1559
  */
1560
1560
  export function sleep(ms) {
1561
- return new Promise((resolve) => setTimeout(resolve, ms));
1561
+ return sleepMs(ms);
1562
1562
  }
1563
1563
  /**
1564
1564
  * Read user input from stdin with optional masking.
@@ -1881,6 +1881,21 @@ export function deepFreeze(obj) {
1881
1881
  export function cloneMap(map) {
1882
1882
  return new Map(map);
1883
1883
  }
1884
+ /**
1885
+ * Fire-and-forget structural grid resync. Invokes the manager's handler and
1886
+ * logs both a synchronous throw and an async rejection through the manager
1887
+ * logger, so escalation sites share one error-handling footer. No-op when the
1888
+ * manager has no handler.
1889
+ */
1890
+ export function fireStructuralResync(bot, reason, details, errorLabel, level = 'error') {
1891
+ try {
1892
+ const res = bot.manager?.requestStructuralGridResync?.(reason, details);
1893
+ res?.catch?.((err) => bot.manager?.logger?.log?.(`${errorLabel}: ${getErrorMessage(err)}`, level));
1894
+ }
1895
+ catch (err) {
1896
+ bot.manager?.logger?.log?.(`${errorLabel}: ${getErrorMessage(err)}`, level);
1897
+ }
1898
+ }
1884
1899
  /**
1885
1900
  * Parses JSON content that may contain comments (/* or //).
1886
1901
  * Strips block comments then line comments before parsing.
@@ -34,7 +34,7 @@
34
34
  // SECTION 1: EXTERNAL DEPENDENCIES
35
35
  // ===============================================================================
36
36
  import * as Format from '../format.js';
37
- import { ORDER_STATES, ORDER_TYPES, COW_ACTIONS, GRID_LIMITS } from '../../constants.js';
37
+ import { ORDER_STATES, ORDER_TYPES, COW_ACTIONS, COW_ORIGINS, GRID_LIMITS } from '../../constants.js';
38
38
  import { floatToBlockchainInt, blockchainToFloat, getPrecisionSlack, getPrecisionByOrderType, getDoubleDustThreshold, getSellStartIdx, isSlotIndexInGapBand, isEvacuationRotationAllowed, clamp, priceSlotEqual } from './math.js';
39
39
  import { parseSlotIndex } from './slot.js';
40
40
  import { isOrderOnChain, isPhantomOrder, convertToSpreadPlaceholder, detectGapEvacuationCandidates, updateGapEvacuationStreaks, isNonBlockingUnmatchedOrder } from './order.js';
@@ -385,7 +385,7 @@ function stampGapEvacuationRotation(action, sourceMaster, destPrice, destSize, t
385
385
  const check = isEvacuationRotationAllowed(sourceMaster?.price, sourceMaster?.size, destPrice, destSize, type, stampPrecision);
386
386
  if (!check.allowed)
387
387
  return action;
388
- return { ...action, origin: 'gap-evacuation', evacBoundary: b, evacGapSlots: Math.floor(g) };
388
+ return { ...action, origin: COW_ORIGINS.GAP_EVACUATION, evacBoundary: b, evacGapSlots: Math.floor(g) };
389
389
  }
390
390
  /**
391
391
  * Reconcile target grid against master state
@@ -1,5 +1,5 @@
1
1
  import type { BitSharesClient } from './system.js';
2
- export interface PoolPriceOverrides {
2
+ interface PoolPriceOverrides {
3
3
  derivePoolPrice(symA: string, symB: string): Promise<number | null>;
4
4
  }
5
5
  export declare function withPoolRef(BitShares: BitSharesClient, poolRef: string | null | undefined): PoolPriceOverrides | null;
@@ -16,4 +16,5 @@ export declare function withPoolRef(BitShares: BitSharesClient, poolRef: string
16
16
  */
17
17
  export declare function resolveStartPriceMode(startPrice: unknown, fallback?: string): string;
18
18
  export declare function derivePriceWithPoolRef(BitShares: BitSharesClient, symA: string, symB: string, mode: string, poolRef: string | null | undefined): Promise<number | null>;
19
+ export {};
19
20
  //# sourceMappingURL=withPoolRef.d.ts.map
@@ -143,6 +143,27 @@ function resolveProfilesDir(projectRoot = PROJECT_ROOT) {
143
143
  return homeDir || repoDir;
144
144
  }
145
145
  const PROFILES_DIR = resolveProfilesDir();
146
+ /**
147
+ * Shared layout rule for bundled data dirs (market_adapter, claw, analysis):
148
+ * the source layout is used only when the profiles dir also resolves to the
149
+ * repo checkout (and, where required, the bundled dir exists); otherwise the
150
+ * root follows the relocated profiles dir. Env vars override both. `root()`
151
+ * resolves an env-overridable sub-root (e.g. `data`, `state`) under the chosen
152
+ * layout; `DIR` companions use `sourceDir`/`relocatedDir` directly.
153
+ */
154
+ function resolveBundledLayout(name, profilesDir, projectRoot, requireExisting = false) {
155
+ const sourceDir = path.join(projectRoot, name);
156
+ const relocatedDir = path.join(profilesDir, name);
157
+ const useSourceLayout = profilesDir === path.join(projectRoot, 'profiles')
158
+ && (!requireExisting || fs.existsSync(sourceDir));
159
+ const root = (envVar, sourceSub = '', relocatedSub = sourceSub) => {
160
+ const env = getEnvLive(envVar);
161
+ if (env)
162
+ return path.resolve(env);
163
+ return useSourceLayout ? path.join(sourceDir, sourceSub) : path.join(relocatedDir, relocatedSub);
164
+ };
165
+ return { sourceDir, relocatedDir, useSourceLayout, root };
166
+ }
146
167
  /**
147
168
  * Market adapter data/state dirs. State stays next to the code (source
148
169
  * layout) only when the profiles dir also resolves to the repo layout —
@@ -152,22 +173,11 @@ const PROFILES_DIR = resolveProfilesDir();
152
173
  * state across the repo and home. Env vars override both.
153
174
  */
154
175
  function resolveMarketAdapterDirs(profilesDir = PROFILES_DIR, projectRoot = PROJECT_ROOT) {
155
- const sourceDir = path.join(projectRoot, 'market_adapter');
156
- const useSourceLayout = profilesDir === path.join(projectRoot, 'profiles') && fs.existsSync(sourceDir);
157
- const dataEnv = getEnvLive('DEXBOT_MARKET_ADAPTER_DATA_DIR');
158
- const stateEnv = getEnvLive('DEXBOT_MARKET_ADAPTER_STATE_DIR');
159
- const dataRoot = dataEnv
160
- ? path.resolve(dataEnv)
161
- : useSourceLayout
162
- ? path.join(sourceDir, 'data')
163
- : path.join(profilesDir, 'market_adapter', 'data');
164
- const stateRoot = stateEnv
165
- ? path.resolve(stateEnv)
166
- : useSourceLayout
167
- ? path.join(sourceDir, 'state')
168
- : path.join(profilesDir, 'market_adapter', 'state');
176
+ const layout = resolveBundledLayout('market_adapter', profilesDir, projectRoot, true);
177
+ const dataRoot = layout.root('DEXBOT_MARKET_ADAPTER_DATA_DIR', 'data');
178
+ const stateRoot = layout.root('DEXBOT_MARKET_ADAPTER_STATE_DIR', 'state');
169
179
  return {
170
- DIR: useSourceLayout ? sourceDir : path.join(profilesDir, 'market_adapter'),
180
+ DIR: layout.useSourceLayout ? layout.sourceDir : layout.relocatedDir,
171
181
  DATA_DIR: dataRoot,
172
182
  LP_DATA_DIR: path.join(dataRoot, 'lp'),
173
183
  FEED_DATA_DIR: path.join(dataRoot, 'feed'),
@@ -188,22 +198,16 @@ const MARKET_ADAPTER = resolveMarketAdapterDirs(PROFILES_DIR, PROJECT_ROOT);
188
198
  * overrides the data root.
189
199
  */
190
200
  function resolveClawDirs(profilesDir = PROFILES_DIR, projectRoot = PROJECT_ROOT) {
191
- const sourceDir = path.join(projectRoot, 'claw');
192
- const useSourceLayout = profilesDir === path.join(projectRoot, 'profiles');
193
- const clawEnv = getEnvLive('DEXBOT_CLAW_DATA_DIR');
194
- const dataRoot = clawEnv
195
- ? path.resolve(clawEnv)
196
- : useSourceLayout
197
- ? path.join(sourceDir, 'data')
198
- : path.join(profilesDir, 'claw', 'data');
201
+ const layout = resolveBundledLayout('claw', profilesDir, projectRoot);
202
+ const dataRoot = layout.root('DEXBOT_CLAW_DATA_DIR', 'data');
199
203
  return {
200
- DIR: sourceDir,
204
+ DIR: layout.sourceDir,
201
205
  DATA_DIR: dataRoot,
202
206
  STATE_DIR: path.join(dataRoot, 'state'),
203
207
  POSITIONS_FILE: path.join(dataRoot, 'positions.json'),
204
208
  WATCHER_HEALTH_FILE: path.join(dataRoot, 'watcher-health.json'),
205
209
  MEMU_DIR: path.join(dataRoot, 'memu'),
206
- MEMU_RUNNER_SCRIPT: path.join(sourceDir, 'scripts', 'memu_runner.py'),
210
+ MEMU_RUNNER_SCRIPT: path.join(layout.sourceDir, 'scripts', 'memu_runner.py'),
207
211
  };
208
212
  }
209
213
  const CLAW = resolveClawDirs(PROFILES_DIR, PROJECT_ROOT);
@@ -216,14 +220,8 @@ const CLAW = resolveClawDirs(PROFILES_DIR, PROJECT_ROOT);
216
220
  * DEXBOT_ANALYSIS_DIR overrides the root.
217
221
  */
218
222
  function resolveAnalysisDirs(profilesDir = PROFILES_DIR, projectRoot = PROJECT_ROOT) {
219
- const sourceDir = path.join(projectRoot, 'analysis');
220
- const useSourceLayout = profilesDir === path.join(projectRoot, 'profiles') && fs.existsSync(sourceDir);
221
- const analysisEnv = getEnvLive('DEXBOT_ANALYSIS_DIR');
222
- const outRoot = analysisEnv
223
- ? path.resolve(analysisEnv)
224
- : useSourceLayout
225
- ? sourceDir
226
- : path.join(profilesDir, 'analysis');
223
+ const layout = resolveBundledLayout('analysis', profilesDir, projectRoot, true);
224
+ const outRoot = layout.root('DEXBOT_ANALYSIS_DIR');
227
225
  return {
228
226
  DIR: outRoot,
229
227
  CHARTS_DIR: path.join(outRoot, 'charts'),
@@ -232,7 +230,7 @@ function resolveAnalysisDirs(profilesDir = PROFILES_DIR, projectRoot = PROJECT_R
232
230
  CACHE_DIR: path.join(outRoot, 'cache'),
233
231
  // Vendored read-only assets always live with the code (repo checkout
234
232
  // or npm package), never under the relocated output root.
235
- ASSETS_DIR: path.join(sourceDir, 'uplot'),
233
+ ASSETS_DIR: path.join(layout.sourceDir, 'uplot'),
236
234
  };
237
235
  }
238
236
  const ANALYSIS = resolveAnalysisDirs(PROFILES_DIR, PROJECT_ROOT);
@@ -1,6 +1,6 @@
1
1
  import type { UnknownRecord } from './types.js';
2
2
  import { GRID_LIMITS, FEE_PARAMETERS, INCREMENT_BOUNDS, TIMING, LOGGING_CONFIG, FILL_PROCESSING, PIPELINE_TIMING, API_LIMITS, COW_PERFORMANCE } from './constants.js';
3
- export interface BotRuntimeSettings {
3
+ interface BotRuntimeSettings {
4
4
  gridLimits: typeof GRID_LIMITS;
5
5
  feeParams: typeof FEE_PARAMETERS;
6
6
  incrementBounds: typeof INCREMENT_BOUNDS;
@@ -14,9 +14,6 @@ export interface BotRuntimeSettings {
14
14
  config: typeof LOGGING_CONFIG;
15
15
  };
16
16
  }
17
- export type BotRuntimeSettingsOverrides = Partial<BotRuntimeSettings> & {
18
- poolSlippageTolerance?: number;
19
- };
20
17
  export declare const RUNTIME_SETTINGS_KEYS: readonly string[];
21
18
  /**
22
19
  * Bot-config keys safe to apply to a live bot without a grid rebuild or a
@@ -32,4 +29,5 @@ export declare const RUNTIME_SETTINGS_KEYS: readonly string[];
32
29
  */
33
30
  export declare const BOT_LIVE_CONFIG_KEYS: readonly string[];
34
31
  export declare function resolveBotRuntimeSettings(botConfig: UnknownRecord): BotRuntimeSettings;
32
+ export {};
35
33
  //# sourceMappingURL=runtime_settings.d.ts.map
@@ -38,7 +38,7 @@ declare function deepMerge(target: UnknownRecord, source: UnknownRecord): Unknow
38
38
  * `selection` are typed because callers read/write those sub-fields directly;
39
39
  * the index signature keeps unmapped passthrough keys reachable.
40
40
  */
41
- export interface NodesHealthCheckView {
41
+ interface NodesHealthCheckView {
42
42
  enabled?: boolean;
43
43
  intervalMs?: number;
44
44
  timeoutMs?: number;
@@ -46,7 +46,7 @@ export interface NodesHealthCheckView {
46
46
  blacklistThreshold?: number;
47
47
  [key: string]: unknown;
48
48
  }
49
- export interface NodesSelectionView {
49
+ interface NodesSelectionView {
50
50
  strategy?: string;
51
51
  preferredNode?: string | null;
52
52
  [key: string]: unknown;
@@ -1,5 +1,5 @@
1
1
  export type SocketJsonFailureKind = 'timeout' | 'connection' | 'closed' | 'invalid';
2
- export interface SocketJsonRequestOptions {
2
+ interface SocketJsonRequestOptions {
3
3
  socketPath: string;
4
4
  timeoutMs: number;
5
5
  /** Write the request to the connected socket (one JSON line). */
@@ -13,4 +13,5 @@ export interface SocketJsonRequestOptions {
13
13
  handleResponse: (parsed: unknown, resolve: (value: unknown) => void, reject: (err: unknown) => void) => void;
14
14
  }
15
15
  export declare function sendSocketJsonRequest(options: SocketJsonRequestOptions): Promise<unknown>;
16
+ export {};
16
17
  //# sourceMappingURL=socket_json_client.d.ts.map
@@ -8,15 +8,33 @@
8
8
  */
9
9
  export type OrderType = 'sell' | 'buy' | 'spread';
10
10
  export type OrderState = 'virtual' | 'active' | 'partial';
11
+ /**
12
+ * Why a spread correction placed no effective order. Carried from
13
+ * checkSpreadCondition to the maintenance loop so the funds/open-orders refresh
14
+ * is requested only when it can repair the cause, and so the log states the
15
+ * truth instead of always blaming free funds.
16
+ *
17
+ * no-free-funds — determineOrderSideByFunds found no fundable side.
18
+ * unfunded — candidates existed but free funds funded none.
19
+ * no-candidates — no spread-tightening slot exists in the LOCAL snapshot.
20
+ * This can be genuine structural geometry, or a stale
21
+ * local order state (a missed fill leaves an ACTIVE slot
22
+ * occupying the window edge, hiding the tightening slot
23
+ * behind it). Only a chain sync can tell the two apart,
24
+ * so it arms the refresh too; the out-of-spread staleness
25
+ * watchdog remains the backstop if the sync heals nothing.
26
+ * batch-not-executed— a plan was prepared but the COW batch did not run.
27
+ * apply-error — the broadcast threw.
28
+ */
29
+ export type SpreadCorrectionStall = 'no-free-funds' | 'unfunded' | 'no-candidates' | 'batch-not-executed' | 'apply-error';
11
30
  /**
12
31
  * Dict with unknown values. The canonical replacement for
13
32
  * `Record<string, any>`; callers must narrow a value before using it.
14
33
  */
15
34
  export type UnknownRecord = Record<string, unknown>;
16
35
  /** A value that survives JSON round-tripping. */
17
- export type JsonPrimitive = string | number | boolean | null;
18
- export type JsonValue = JsonPrimitive | JsonObject | JsonValue[];
19
- export type JsonArray = JsonValue[];
36
+ type JsonPrimitive = string | number | boolean | null;
37
+ type JsonValue = JsonPrimitive | JsonObject | JsonValue[];
20
38
  export interface JsonObject {
21
39
  [key: string]: JsonValue;
22
40
  }
@@ -48,12 +66,12 @@ export interface Deferred<T> {
48
66
  /** Runtime narrowing guard for `UnknownRecord` at I/O boundaries. */
49
67
  export declare function isUnknownRecord(value: unknown): value is UnknownRecord;
50
68
  /** Graphene `asset_amount` (e.g. `{ amount: 12345, asset_id: '1.3.0' }`). */
51
- export interface ChainAssetAmount {
69
+ interface ChainAssetAmount {
52
70
  amount: number | string;
53
71
  asset_id: string;
54
72
  }
55
73
  /** Graphene `price` (sell_price.base / sell_price.quote). */
56
- export interface ChainPrice {
74
+ interface ChainPrice {
57
75
  base: ChainAssetAmount;
58
76
  quote: ChainAssetAmount;
59
77
  }
@@ -205,6 +223,7 @@ export interface BotLike {
205
223
  _blockchainFetchInFlight: number;
206
224
  _blockchainFetchIntervalMin: number;
207
225
  _spreadFundsExhausted: boolean;
226
+ _spreadCorrectionStall: SpreadCorrectionStall | null;
208
227
  _skipEmptyReadConfirmDelay: boolean;
209
228
  _testPollIntervalMs?: number;
210
229
  _appliedBotConfigEntry: unknown;
@@ -301,7 +320,7 @@ export interface BotLike {
301
320
  updateOrdersOnChainBatch(rebalanceResult: unknown): unknown;
302
321
  updateOrdersOnChainPlan(...args: unknown[]): unknown;
303
322
  }
304
- export interface OrderBase {
323
+ interface OrderBase {
305
324
  id: string;
306
325
  price: number;
307
326
  type: OrderType;
@@ -322,16 +341,16 @@ export interface OrderBase {
322
341
  idealSize?: number;
323
342
  sideHint?: string;
324
343
  }
325
- export interface VirtualOrder extends OrderBase {
344
+ interface VirtualOrder extends OrderBase {
326
345
  state: 'virtual';
327
346
  orderId: null | '';
328
347
  }
329
- export interface ActiveOrder extends OrderBase {
348
+ interface ActiveOrder extends OrderBase {
330
349
  state: 'active';
331
350
  orderId: string;
332
351
  size: number;
333
352
  }
334
- export interface PartialOrder extends OrderBase {
353
+ interface PartialOrder extends OrderBase {
335
354
  state: 'partial';
336
355
  orderId: string;
337
356
  size: number;
@@ -363,12 +382,12 @@ export interface AccountTotals {
363
382
  [key: string]: unknown;
364
383
  }
365
384
  /** Per-side fund amounts. */
366
- export interface SideFunds {
385
+ interface SideFunds {
367
386
  buy: number;
368
387
  sell: number;
369
388
  }
370
389
  /** Chain/grid split of a fund category. */
371
- export interface ChainGridFunds {
390
+ interface ChainGridFunds {
372
391
  chain: SideFunds;
373
392
  grid: SideFunds;
374
393
  }
@@ -392,7 +411,7 @@ export interface ManagerFunds {
392
411
  [key: string]: unknown;
393
412
  }
394
413
  /** `manager.persistGrid()` result — validation outcome plus skip flags. */
395
- export interface PersistGridResult extends UnknownRecord {
414
+ interface PersistGridResult extends UnknownRecord {
396
415
  isValid: boolean;
397
416
  skipped?: boolean;
398
417
  suspended?: boolean;
@@ -451,15 +470,8 @@ export interface FillBatchResult extends UnknownRecord {
451
470
  aborted?: boolean;
452
471
  deferred?: boolean;
453
472
  }
454
- /** Result of `_cancelDustOrders`. */
455
- export interface DustCancelResult extends UnknownRecord {
456
- batchResult?: {
457
- aborted?: boolean;
458
- [key: string]: unknown;
459
- };
460
- }
461
473
  /** Result of `manager.checkGridHealth()`. */
462
- export interface GridHealthResult extends UnknownRecord {
474
+ interface GridHealthResult extends UnknownRecord {
463
475
  buyDustOrders?: unknown[];
464
476
  sellDustOrders?: unknown[];
465
477
  }
@@ -499,7 +511,7 @@ export interface IncomingFill extends UnknownRecord {
499
511
  id?: string;
500
512
  }
501
513
  /** Aggregate chain-funds summary produced by `computeChainFundTotals`. */
502
- export interface ChainFundsTotals {
514
+ interface ChainFundsTotals {
503
515
  chainFreeBuy: number;
504
516
  chainFreeSell: number;
505
517
  committedChainBuy: number;
@@ -630,7 +642,7 @@ export interface GridFeeParams extends UnknownRecord {
630
642
  POOL_SLIPPAGE_TOLERANCE?: number;
631
643
  }
632
644
  /** `config.timing` knobs. */
633
- export interface TimingConfig extends UnknownRecord {
645
+ interface TimingConfig extends UnknownRecord {
634
646
  SAFETY_NET_SYNC_TIMEOUT_MS?: number;
635
647
  CREDIT_DEAL_EXPIRY_THRESHOLD_HOURS?: number;
636
648
  CREDIT_REBORROW_MAX_ATTEMPTS?: number;
@@ -639,7 +651,7 @@ export interface TimingConfig extends UnknownRecord {
639
651
  BTS_ACQUIRE_COOLDOWN_MIN?: number;
640
652
  }
641
653
  /** `config.fillProcessing` knobs read by the fill consumer. */
642
- export interface FillProcessingConfig extends UnknownRecord {
654
+ interface FillProcessingConfig extends UnknownRecord {
643
655
  CONSUMER_BACKOFF_INITIAL_MS?: number;
644
656
  CONSUMER_BACKOFF_MAX_MS?: number;
645
657
  MAX_CONSECUTIVE_CONSUMER_FAILURES?: number;
@@ -657,16 +669,16 @@ export interface ManagerLock {
657
669
  heldForMs(): number;
658
670
  }
659
671
  /** `refreshAccountTotalsIfStale()` freshness gate. */
660
- export interface AccountTotalsGate {
672
+ interface AccountTotalsGate {
661
673
  ok: boolean;
662
674
  [key: string]: unknown;
663
675
  }
664
676
  /** Accountant surface the sync engine calls directly. */
665
677
  /** Result of `accountant.processFillAccounting()`. */
666
- export interface FillAccountingResult extends UnknownRecord {
678
+ interface FillAccountingResult extends UnknownRecord {
667
679
  status: string;
668
680
  }
669
- export interface AccountantLike {
681
+ interface AccountantLike {
670
682
  processFillAccounting(fillOp: unknown, fillKey: string, options?: UnknownRecord): Promise<boolean>;
671
683
  adjustTotalBalance(orderType: string, delta: number, operation: string): Promise<unknown>;
672
684
  addToChainFree(orderType: string, size: number, operation: string): Promise<unknown>;
@@ -865,7 +877,7 @@ export interface ManagerLogger {
865
877
  flush?(): Promise<void>;
866
878
  }
867
879
  /** Mutable recovery-state record (all fields optional to allow partial writes). */
868
- export interface ManagerRecoveryState {
880
+ interface ManagerRecoveryState {
869
881
  phase?: string;
870
882
  attemptCount?: number;
871
883
  lastAttemptAt?: number;
@@ -1085,6 +1097,8 @@ export interface OrderManagerLike {
1085
1097
  syncFromFillHistoryBatch(fills: unknown, options?: UnknownRecord): Promise<FillHistorySyncResult>;
1086
1098
  checkSpreadCondition(...args: unknown[]): Promise<{
1087
1099
  ordersPlaced?: number;
1100
+ partialsMoved?: number;
1101
+ stall?: SpreadCorrectionStall;
1088
1102
  [key: string]: unknown;
1089
1103
  }>;
1090
1104
  _fetchAccountBalancesAndSetTotals(...args: unknown[]): Promise<unknown>;
@@ -1108,4 +1122,5 @@ export interface OrderManagerLike {
1108
1122
  }): Promise<PersistGridResult>;
1109
1123
  calculateCurrentSpread(): number;
1110
1124
  }
1125
+ export {};
1111
1126
  //# sourceMappingURL=types.d.ts.map
@@ -42,9 +42,7 @@ export function getErrorName(err) {
42
42
  * interval, credit-deal settle delay, deferred-fill retry backoff).
43
43
  */
44
44
  export function resolveSeamMs(value, fallback) {
45
- return value != null && Number.isFinite(Number(value)) && Number(value) >= 0
46
- ? Number(value)
47
- : fallback;
45
+ return resolveSeamMsOrNull(value) ?? fallback;
48
46
  }
49
47
  /**
50
48
  * Like {@link resolveSeamMs}, but returns `null` instead of a fallback so the
@@ -63,14 +63,14 @@
63
63
  * dir (never in the package dir — npm reinstalls wipe that).
64
64
  */
65
65
  /** How the running copy was installed — selects the hint text. */
66
- export type InstallKind = 'npm-global' | 'git' | 'other';
66
+ type InstallKind = 'npm-global' | 'git' | 'other';
67
67
  /**
68
68
  * The pending one-time announcement: what the operator is told when a newer
69
69
  * release exists and has not been displayed yet. It carries DATA only — the
70
70
  * wording and colour are rendered by `printVersionStatus`, so there is exactly
71
71
  * one place that decides how a version verdict looks.
72
72
  */
73
- export interface VersionNotice {
73
+ interface VersionNotice {
74
74
  currentVersion: string;
75
75
  latestVersion: string;
76
76
  installKind: InstallKind;
@@ -79,8 +79,8 @@ export interface VersionNotice {
79
79
  cacheFile: string;
80
80
  }
81
81
  /** Green when current, orange when a newer release exists, gray when unknown. */
82
- export type VersionState = 'up-to-date' | 'update-available' | 'unknown';
83
- export interface VersionStatus {
82
+ type VersionState = 'up-to-date' | 'update-available' | 'unknown';
83
+ interface VersionStatus {
84
84
  /** Installed version — `Config.VERSION` unless overridden. */
85
85
  currentVersion: string;
86
86
  /** Latest version observed this run, or from the throttle cache. Null when
@@ -106,7 +106,7 @@ export interface VersionStatus {
106
106
  * that latches it. */
107
107
  notice: VersionNotice | null;
108
108
  }
109
- export interface VersionNoticeOptions {
109
+ interface VersionNoticeOptions {
110
110
  /** Override the installed version (defaults to `Config.VERSION`). */
111
111
  currentVersion?: string;
112
112
  /** Override the cache location (tests). */
@@ -149,18 +149,18 @@ export declare function compareVersions(a: string, b: string): number;
149
149
  /** Classify the running install without spawning anything. */
150
150
  export declare function detectInstallKind(projectRoot?: string): InstallKind;
151
151
  /** Minimal structural view of a fetch response used by the probe. */
152
- export interface FetchResponseLike {
152
+ interface FetchResponseLike {
153
153
  ok?: boolean;
154
154
  status?: number;
155
155
  json(): Promise<unknown>;
156
156
  }
157
- export type FetchImpl = (url: string, init: {
157
+ type FetchImpl = (url: string, init: {
158
158
  method?: string;
159
159
  headers?: Record<string, string>;
160
160
  signal?: AbortSignal;
161
161
  }) => Promise<FetchResponseLike | null | undefined>;
162
162
  /** One place the published version can be read from. */
163
- export interface VersionSource {
163
+ interface VersionSource {
164
164
  id: string;
165
165
  url: string;
166
166
  /** Pull the version out of the source's JSON shape. Returns null when the
@@ -296,7 +296,7 @@ export declare function flushVersionStatusOrHeader(pending: Promise<VersionStatu
296
296
  * same contract as `flushVersionStatusOrHeader`.
297
297
  */
298
298
  export declare function printVersionStatusWhenReady(pending: Promise<VersionStatus | null>): void;
299
- export interface StagedVersionNoticeOptions extends VersionNoticeOptions {
299
+ interface StagedVersionNoticeOptions extends VersionNoticeOptions {
300
300
  /** Wait at the top of the command before the caller prints anything else.
301
301
  * Default `UPDATER.NOTICE_STAGE_GRACE_MS` (1s). */
302
302
  graceMs?: number;
@@ -304,7 +304,7 @@ export interface StagedVersionNoticeOptions extends VersionNoticeOptions {
304
304
  * `UPDATER.NOTICE_STATUS_TIMEOUT_MS`. */
305
305
  finalMs?: number;
306
306
  }
307
- export interface StagedVersionWait {
307
+ interface StagedVersionWait {
308
308
  /** The status if it lands within `graceMs`, else null. Await this at the
309
309
  * top of a report; the value is only interesting for its TIMING. */
310
310
  quick: Promise<VersionStatus | null>;
@@ -319,4 +319,5 @@ export interface StagedVersionWait {
319
319
  * carries the whole escalation.
320
320
  */
321
321
  export declare function startStagedVersionStatus(options?: StagedVersionNoticeOptions): StagedVersionWait;
322
+ export {};
322
323
  //# sourceMappingURL=version_notice.d.ts.map
package/dist/pm2.d.ts CHANGED
@@ -46,7 +46,6 @@ declare function generateEcosystemConfig({ botNameFilter, clawOnly, exitOnError
46
46
  }): Pm2App[];
47
47
  declare function ensureCredentialDaemonPM2({ forceRefresh, headless, passwordFile }?: {
48
48
  forceRefresh?: boolean;
49
- logReuse?: boolean;
50
49
  headless?: boolean;
51
50
  passwordFile?: string | null;
52
51
  }): Promise<boolean>;