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
@@ -16,13 +16,6 @@ interface CredentialClientOptions {
16
16
  botHmacSecret?: string | null;
17
17
  batchId?: string | null;
18
18
  nodeUrl?: string;
19
- /**
20
- * Accepted for interface compatibility only. The daemon cycles its own
21
- * node list internally, and an uncertain broadcast must never be re-sent
22
- * (a landed tx would be duplicated), so the client no longer cycles
23
- * through fallbacks. Callers may keep passing this field; it is ignored.
24
- */
25
- fallbackNodes?: string[];
26
19
  /**
27
20
  * Fired with the node the daemon reports as in play when a broadcast ends
28
21
  * uncertain (BROADCAST_DEADLINE / outer timeout). The daemon echoes the
@@ -32,12 +25,6 @@ interface CredentialClientOptions {
32
25
  */
33
26
  onNodeFailed?: (nodeUrl: string) => void;
34
27
  }
35
- interface CredentialDaemonMeta {
36
- uncertainOnTimeout?: boolean;
37
- operations?: unknown[] | null;
38
- accountName?: string | null;
39
- batchId?: string | null;
40
- }
41
28
  export interface CredentialDaemonResponse {
42
29
  success?: boolean;
43
30
  error?: string;
@@ -52,14 +39,6 @@ export interface CredentialDaemonResponse {
52
39
  /** Node reported by the daemon as in play at the failure (typed replies). */
53
40
  nodeUrl?: string | null;
54
41
  }
55
- interface RequestPayload {
56
- type: string;
57
- accountName: string;
58
- operations: unknown[];
59
- sessionId?: string | null;
60
- hmac?: string;
61
- nodeUrl?: string;
62
- }
63
42
  declare const DEFAULT_SOCKET_PATH: string;
64
43
  declare const DEFAULT_READY_FILE: string;
65
44
  declare const DEFAULT_BROADCAST_TIMEOUT_MS: number;
@@ -87,9 +66,8 @@ declare class BroadcastUncertainError extends Error {
87
66
  timeoutMs: number | null;
88
67
  constructor(message: string, details?: BroadcastUncertainErrorDetails);
89
68
  }
90
- declare function sendCredentialDaemonRequest(socketPath: string, payload: RequestPayload, timeoutMs: number, meta?: CredentialDaemonMeta): Promise<CredentialDaemonResponse>;
91
69
  declare function isCredentialDaemonReady(options?: CredentialClientOptions): boolean;
92
70
  declare function waitForCredentialDaemon(timeoutMs?: number, options?: CredentialClientOptions): Promise<void>;
93
71
  declare function executeOperationsViaCredentialDaemon(accountName: string, operations: unknown[], options?: CredentialClientOptions): Promise<CredentialDaemonResponse>;
94
- export { DEFAULT_READY_FILE, DEFAULT_SOCKET_PATH, DEFAULT_BROADCAST_TIMEOUT_MS, sendCredentialDaemonRequest, executeOperationsViaCredentialDaemon, isCredentialDaemonReady, waitForCredentialDaemon, BroadcastUncertainError };
72
+ export { DEFAULT_READY_FILE, DEFAULT_SOCKET_PATH, DEFAULT_BROADCAST_TIMEOUT_MS, executeOperationsViaCredentialDaemon, isCredentialDaemonReady, waitForCredentialDaemon, BroadcastUncertainError };
95
73
  //# sourceMappingURL=dexbot_credential_client.d.ts.map
@@ -134,8 +134,7 @@ async function executeOperationsViaCredentialDaemon(accountName, operations, opt
134
134
  // (connect/send errors); an uncertain broadcast (RPC timeout, dropped
135
135
  // connection, 25s inner BROADCAST_DEADLINE) is never re-signed, and
136
136
  // re-sending the ops here is unsafe: an uncertain broadcast may have
137
- // landed, duplicating on-chain orders. `fallbackNodes` is kept for
138
- // interface compatibility but never cycled — the recovery layers (COW
137
+ // landed, duplicating on-chain orders. The recovery layers (COW
139
138
  // retry verification, startup adoption, broadcast reconciliation)
140
139
  // verify chain inclusion before any re-broadcast. onNodeFailed fires for
141
140
  // the node the daemon reports as actually in play (the daemon echoes it in
@@ -220,5 +219,5 @@ async function executeOperationsViaCredentialDaemon(accountName, operations, opt
220
219
  throw err;
221
220
  }
222
221
  }
223
- export { DEFAULT_READY_FILE, DEFAULT_SOCKET_PATH, DEFAULT_BROADCAST_TIMEOUT_MS, sendCredentialDaemonRequest, executeOperationsViaCredentialDaemon, isCredentialDaemonReady, waitForCredentialDaemon, BroadcastUncertainError };
222
+ export { DEFAULT_READY_FILE, DEFAULT_SOCKET_PATH, DEFAULT_BROADCAST_TIMEOUT_MS, executeOperationsViaCredentialDaemon, isCredentialDaemonReady, waitForCredentialDaemon, BroadcastUncertainError };
224
223
  //# sourceMappingURL=dexbot_credential_client.js.map
@@ -1,4 +1,3 @@
1
- /** Fill processing runtime - handles order fill events and replay-safe accounting */
2
1
  import * as chainOrders from './chain_orders.js';
3
2
  import type { BotLike, ManagerLogger, IncomingFill } from './types.js';
4
3
  type ChainOrdersLike = typeof chainOrders;
@@ -8,7 +7,7 @@ export interface FillOpLike {
8
7
  }
9
8
  type MissingKeyMessageFn = (op: FillOpLike, fill: unknown) => string;
10
9
  type FallbackKeyMessageFn = (op: FillOpLike, fill: unknown, fillKey: string) => string;
11
- export type ReplayMessageFn = (op: FillOpLike, fill: unknown, fillKey: string) => string;
10
+ type ReplayMessageFn = (op: FillOpLike, fill: unknown, fillKey: string) => string;
12
11
  type FillErrorFn = (op: FillOpLike, fill: unknown, err: unknown) => string;
13
12
  interface SweepOrphanFillOptions {
14
13
  context: string;
@@ -115,7 +114,7 @@ declare function applyReplaySafeFillAccounting(bot: BotLike, fill: unknown, fill
115
114
  usedFallbackKey?: undefined;
116
115
  }>;
117
116
  /** Shared options for the replay-safe accounting wrappers. */
118
- interface ReplaySafeFillAccountingOptions {
117
+ export interface ReplaySafeFillAccountingOptions {
119
118
  context?: string;
120
119
  logger?: Partial<ManagerLogger>;
121
120
  replayMessage?: ReplayMessageFn;
@@ -1,6 +1,5 @@
1
1
  /** Fill processing runtime - handles order fill events and replay-safe accounting */
2
- import { createRequire } from 'node:module';
3
- const require = createRequire(import.meta.url);
2
+ import { lazyShim } from './lazy_shim.js';
4
3
  import * as chainOrders from './chain_orders.js';
5
4
  import { PROCESSED_FILL_PERSISTENCE_MODES } from './order/processed_fill_store.js';
6
5
  import { NATIVE_CLIENT, FILL_PROCESSING, TIMING, MAINTENANCE, ORDER_TYPES } from './constants.js';
@@ -8,10 +7,10 @@ import { getErrorMessage, resolveSeamMsOrNull, getErrorField } from './utils/err
8
7
  import { isOrderDoesNotExistError } from './dexbot_maintenance_runtime.js';
9
8
  import { slotIndexForPrice, isChainPriceOutOfGrid, isSlotInRail } from './order/utils/math.js';
10
9
  import { ORDER_STATES } from './constants.js';
11
- function buildFillKey(...args) { return require('./order/utils/order').buildFillKey(...args); }
12
- function correctAllPriceMismatches(...args) { return require('./order/utils/order').correctAllPriceMismatches(...args); }
13
- function parseChainOrder(...args) { return require('./order/utils/order').parseChainOrder(...args); }
14
- function retryPersistenceIfNeeded(...args) { return require('./order/utils/system').retryPersistenceIfNeeded(...args); }
10
+ const buildFillKey = lazyShim('./order/utils/order', 'buildFillKey');
11
+ const correctAllPriceMismatches = lazyShim('./order/utils/order', 'correctAllPriceMismatches');
12
+ const parseChainOrder = lazyShim('./order/utils/order', 'parseChainOrder');
13
+ const retryPersistenceIfNeeded = lazyShim('./order/utils/system', 'retryPersistenceIfNeeded');
15
14
  const { readOpenOrdersGuarded } = chainOrders;
16
15
  /**
17
16
  * Whether an unknown fill's order plausibly belongs to THIS bot's grid and
@@ -332,7 +331,7 @@ async function applyReplaySafeTrackedFillAccounting(bot, fill, fillOp, options =
332
331
  */
333
332
  async function applyReplaySafeOrphanFillAccounting(bot, fill, fillOp, options = {}) {
334
333
  const { context, logger, replayMessage, persistenceMode } = resolveReplaySafeFillOptions(bot, options);
335
- return applyReplaySafeFillAccounting(bot, fill, fillOp, {
334
+ const result = await applyReplaySafeFillAccounting(bot, fill, fillOp, {
336
335
  logger,
337
336
  missingKeyMessage: (op) => `[${context}] Missing fill history id and orphan fallback key for ${op.order_id}; deferring to open-orders sync`,
338
337
  fallbackKeyMessage: (op) => `[${context}] Missing fill history id for orphan fill ${op.order_id}; using degraded orphan replay key for proceeds-only accounting`,
@@ -341,6 +340,17 @@ async function applyReplaySafeOrphanFillAccounting(bot, fill, fillOp, options =
341
340
  persistenceMode,
342
341
  allowOrphanFallbackKey: true
343
342
  });
343
+ // P2 observability: this wrapper is orphan-fill-only (processSweepOrphanFill),
344
+ // so an `applied` result is exactly one set of proceeds credited outside
345
+ // slot accounting. `duplicate`/`error`/`missing_key` are not credits and
346
+ // would make the metric useless as a "funds left the grid" signal.
347
+ try {
348
+ if (result?.status === 'applied' && bot?._metrics) {
349
+ bot._metrics.orphanFillCreditedCount = (bot._metrics.orphanFillCreditedCount || 0) + 1;
350
+ }
351
+ }
352
+ catch { /* metrics are best-effort */ }
353
+ return result;
344
354
  }
345
355
  /**
346
356
  * Create a fill callback handler for blockchain subscription events.
@@ -1,4 +1,4 @@
1
- import type { BotLike, OrderManagerLike, ManagedOrder } from './types.js';
1
+ import type { BotLike, OrderManagerLike, ManagedOrder, SpreadCorrectionStall } from './types.js';
2
2
  /** Loose JSON-object view used across the maintenance runtime. */
3
3
  type JsonObj = Record<string, unknown>;
4
4
  /** A stranded/held chain order as seen by the deferred-hold helpers. */
@@ -11,33 +11,7 @@ interface HeldChainOrder {
11
11
  [key: string]: unknown;
12
12
  }
13
13
  import { usesAmaGridPrice } from './grid_price_source.js';
14
- declare function isWrapperAdapterOwner(...args: unknown[]): any;
15
- /**
16
- * Check if a bot configuration uses an AMA grid price source.
17
- *
18
- * Canonical implementation lives in ./grid_price_source.js (browser-safe,
19
- * shared with the market adapter service) — re-exported here so existing
20
- * Node-side consumers keep their import path.
21
- */
22
- /**
23
- * Find a bot entry in the bots config snapshot that matches a runtime config.
24
- * Matches by botKey or name.
25
- * @param {unknown} snapshot - Bots configuration snapshot
26
- * @param {Object} config - Runtime bot configuration
27
- * @returns {Object|null} Matched bot entry or null
28
- */
29
- declare function findSnapshotBotForRuntimeConfig(snapshot: {
30
- activeBots?: BotLike[];
31
- }, config: JsonObj): BotLike | null;
32
- /**
33
- * Check if a runtime bot configuration requires the market adapter.
34
- * @param {unknown} snapshot - Bots configuration snapshot
35
- * @param {Object} config - Runtime bot configuration
36
- * @returns {boolean} True if the bot uses AMA grid pricing
37
- */
38
- declare function runtimeConfigNeedsMarketAdapter(snapshot: {
39
- activeBots?: BotLike[];
40
- }, config: JsonObj): boolean;
14
+ declare const isWrapperAdapterOwner: (...args: unknown[]) => any;
41
15
  /**
42
16
  * Build the full-entry fingerprint for one bot (stable across key order and
43
17
  * comment/whitespace edits, since those never reach the parsed entry).
@@ -69,30 +43,46 @@ declare function buildBotConfigFingerprint(entry: unknown): string;
69
43
  */
70
44
  declare function checkAndApplyBotConfigChanges(bot: BotLike, context?: string, preloadedSnapshot?: JsonObj | null): Promise<unknown>;
71
45
  /**
72
- * Count live on-chain reserve orders for one side (issue #27 follow-up).
46
+ * Count live on-chain edge orders for one side (issue #27 follow-up).
73
47
  *
74
- * The window shortfall check above compares live window+reserves against
75
- * window+reserves, so a pre-existing window surplus masks a reserve deficit
76
- * (e.g. target 6+2=8 vs 12 live after reserveOrders 0→2: no shortfall, no
77
- * sync, zero reserve placements). Reserves get their own independent reason
78
- * below — the mirror of the masking case getTargetActiveOrders handles.
48
+ * The window shortfall check above compares live window+edges against
49
+ * window+edges, so a pre-existing window surplus masks an edge deficit
50
+ * (e.g. target 6+2=8 vs 12 live after edgeOrders 0→2: no shortfall, no
51
+ * sync, zero edge placements). Edge orders get their own independent reason
52
+ * below — the mirror of the masking case getTargetCoreOrders handles.
79
53
  *
80
- * Classification reuses the single source of truth (reserveEdgeIdSet +
81
- * resolveLiveReserveEdgeAnchorPrice, same anchor the placement pickers use)
54
+ * Classification reuses the single source of truth (edgeOrderIdSet +
55
+ * resolveLiveEdgeAnchorPrice, same anchor the placement pickers use)
82
56
  * over the full master grid, intersected with live ACTIVE/PARTIAL orderIds
83
57
  * (same live definition as countLiveGridOrders). The edge pick excludes the
84
58
  * window (liveWindowIdSet — the same exclusion every placement picker
85
59
  * applies): window + edge are additive in targets/fees/hold-back, but
86
60
  * without the exclusion a window that reaches the grid edge (keep-low
87
61
  * window = bottom slots = floor edge) makes the edge pick land on window
88
- * members and the count reads N/N with zero dedicated reserves, so the
62
+ * members and the count reads N/N with zero dedicated edge orders, so the
89
63
  * deficit never fires (issue #27 follow-up).
90
64
  * @param {unknown} manager - OrderManager
91
- * @param {unknown} config - Bot configuration (reserve count source)
65
+ * @param {unknown} config - Bot configuration (edge count source)
92
66
  * @param {unknown} type - ORDER_TYPES.BUY or ORDER_TYPES.SELL
93
- * @returns {number|null} Live reserve count, or null when unclassifiable
67
+ * @returns {number|null} Live edge count, or null when unclassifiable
94
68
  */
95
- declare function countLiveReserveOrders(manager: OrderManagerLike, config: JsonObj, type: unknown): number | null;
69
+ declare function countLiveEdgeOrders(manager: OrderManagerLike, config: JsonObj, type: unknown): number | null;
70
+ /**
71
+ * Mirror a spread-check stall into the flags the targeted-sync gate reads.
72
+ *
73
+ * ANY stall — fund, batch, or structural — arms the refresh. When the
74
+ * correction cannot act on the local snapshot, that snapshot may simply be
75
+ * stale relative to the chain: a missed fill leaves an ACTIVE slot occupying
76
+ * the window edge, so `isSlotAvailable` hides every tightening slot and the
77
+ * check reports 'no-candidates' even though real geometry exists. A refresh is
78
+ * the only way to tell a genuinely structural stall from a stale one, so we
79
+ * sync rather than wait for the out-of-spread staleness watchdog to re-center.
80
+ * The stall cause is kept alongside the flag so the log states the truth.
81
+ * Exported for tests.
82
+ * @param {BotLike} bot
83
+ * @param {SpreadCorrectionStall|null|undefined} stall
84
+ */
85
+ export declare function mirrorSpreadStall(bot: BotLike, stall: SpreadCorrectionStall | null | undefined): void;
96
86
  declare function getTargetedSyncReason(bot: BotLike): {
97
87
  reason: string;
98
88
  targetBuy: any;
@@ -110,11 +100,6 @@ declare function maybeRunTargetedDriftReconciliation(bot: BotLike, context: stri
110
100
  * @returns {unknown} Snapshot with exists flag, fingerprint, active bots list, and adapter requirement
111
101
  */
112
102
  declare function loadBotsConfigSnapshot(): any;
113
- /**
114
- * Stop and delete the market adapter process from PM2.
115
- * @returns {Promise<void>}
116
- */
117
- declare function stopMarketAdapterPm2(): Promise<void>;
118
103
  /**
119
104
  * Synchronize market adapter state based on periodic config checks.
120
105
  * Starts or stops the market adapter based on whether any active bot uses AMA grid pricing.
@@ -396,22 +381,6 @@ declare function cancelDustOrders(bot: BotLike, { buy: buyDust, sell: sellDust }
396
381
  declare function runGridMaintenance(bot: BotLike, context?: string, options?: {
397
382
  skipIdle?: boolean;
398
383
  }): Promise<void>;
399
- /**
400
- * Check if the bot's BTS balance is below the minimum threshold and trigger acquisition.
401
- * Only applies to non-BTS pairs. Uses hysteresis: triggers at 1× min_BTS_value,
402
- * fills to BTS_ACQUIRE_TARGET_MULTIPLIER × min_BTS_value.
403
- * @param {import('./dexbot_class.js').DEXBot} bot
404
- * @returns {Promise<void>}
405
- */
406
- declare function checkBtsBalanceAndAcquire(bot: BotLike): Promise<void>;
407
- /**
408
- * Acquire BTS by swapping one of the trading pair assets through an AMM pool.
409
- * Tries both assets for a BTS pool, picks the best (lowest price impact).
410
- * @param {import('./dexbot_class.js').DEXBot} bot
411
- * @param {number} deficit - Amount of BTS needed (float)
412
- * @returns {Promise<void>}
413
- */
414
- declare function acquireBts(bot: BotLike, deficit: number): Promise<void>;
415
384
  /**
416
385
  * Run a single dust health check cycle.
417
386
  * @param {import('./dexbot_class.js').DEXBot} bot
@@ -466,6 +435,7 @@ declare function markGridActivity(bot: BotLike, reason?: string): void;
466
435
  * @returns {Object}
467
436
  */
468
437
  declare function getMetrics(bot: BotLike): {
438
+ boundaryDriftExceedsWindowCount: number;
469
439
  queueDepth: number;
470
440
  fillProcessingLockActive: boolean;
471
441
  divergenceLockActive: boolean;
@@ -482,6 +452,10 @@ declare function getMetrics(bot: BotLike): {
482
452
  maxQueueDepth: number;
483
453
  gridLockContention: number;
484
454
  fundRecalcCount: number;
455
+ refusedCommitCount: number;
456
+ orphanFillCreditedCount: number;
457
+ restampBuyAboveAnchorCount: number;
458
+ gapBandPlacementShadowCount: number;
485
459
  };
486
460
  /**
487
461
  * Read open orders from chain, sync with local state, and process any fills found.
@@ -506,15 +480,10 @@ declare function syncOpenOrdersAndProcessFills(bot: BotLike, tag: string): Promi
506
480
  hasUnmatched: number;
507
481
  openOrders: import("./types.js").ChainOrder[];
508
482
  }>;
509
- export { loadBotsConfigSnapshot, isWrapperAdapterOwner, checkAndApplyBotConfigChanges, buildBotConfigFingerprint, refreshDynamicWeightDistribution, performGridResync, updateBotGridResetMetadata, handlePendingTriggerReset, setupTriggerFileDetection, performPeriodicGridChecks, isOpenOrdersSyncLoopEnabled, startOpenOrdersSyncLoop, stopOpenOrdersSyncLoop, setupBlockchainFetchInterval, stopBlockchainFetchInterval, setupBotsConfigPollInterval, stopBotsConfigPollInterval, executeMaintenanceLogic, getTargetedSyncReason, maybeRunTargetedDriftReconciliation, countLiveReserveOrders, cancelDustOrders, isOrderDoesNotExistError, runGridMaintenance, releaseMarketAdapterRuntime, syncMarketAdapterOnPeriodicConfigCheck, usesAmaGridPrice, runDustHealthCheck, setupDustHealthCheckInterval, requestGridReset, wireStructuralGridResyncRequest, getPipelineSignals, markGridActivity, getMetrics, syncOpenOrdersAndProcessFills, shouldDeferMaintenanceForBroadcast, checkGridLockHoldDuration };
483
+ export { loadBotsConfigSnapshot, isWrapperAdapterOwner, checkAndApplyBotConfigChanges, buildBotConfigFingerprint, refreshDynamicWeightDistribution, performGridResync, updateBotGridResetMetadata, handlePendingTriggerReset, setupTriggerFileDetection, performPeriodicGridChecks, isOpenOrdersSyncLoopEnabled, startOpenOrdersSyncLoop, stopOpenOrdersSyncLoop, setupBlockchainFetchInterval, stopBlockchainFetchInterval, setupBotsConfigPollInterval, stopBotsConfigPollInterval, executeMaintenanceLogic, getTargetedSyncReason, maybeRunTargetedDriftReconciliation, countLiveEdgeOrders, cancelDustOrders, isOrderDoesNotExistError, runGridMaintenance, releaseMarketAdapterRuntime, syncMarketAdapterOnPeriodicConfigCheck, usesAmaGridPrice, runDustHealthCheck, setupDustHealthCheckInterval, requestGridReset, wireStructuralGridResyncRequest, getPipelineSignals, markGridActivity, getMetrics, syncOpenOrdersAndProcessFills, shouldDeferMaintenanceForBroadcast, checkGridLockHoldDuration };
510
484
  declare const _default: {
511
- loadBotsConfigSnapshot: typeof loadBotsConfigSnapshot;
512
- isWrapperAdapterOwner: typeof isWrapperAdapterOwner;
513
- checkAndApplyBotConfigChanges: typeof checkAndApplyBotConfigChanges;
514
- buildBotConfigFingerprint: typeof buildBotConfigFingerprint;
515
485
  refreshDynamicWeightDistribution: typeof refreshDynamicWeightDistribution;
516
486
  performGridResync: typeof performGridResync;
517
- updateBotGridResetMetadata: typeof updateBotGridResetMetadata;
518
487
  handlePendingTriggerReset: typeof handlePendingTriggerReset;
519
488
  setupTriggerFileDetection: typeof setupTriggerFileDetection;
520
489
  performPeriodicGridChecks: typeof performPeriodicGridChecks;
@@ -526,21 +495,9 @@ declare const _default: {
526
495
  setupBotsConfigPollInterval: typeof setupBotsConfigPollInterval;
527
496
  stopBotsConfigPollInterval: typeof stopBotsConfigPollInterval;
528
497
  executeMaintenanceLogic: typeof executeMaintenanceLogic;
529
- getTargetedSyncReason: typeof getTargetedSyncReason;
530
- countLiveReserveOrders: typeof countLiveReserveOrders;
531
- maybeRunTargetedDriftReconciliation: typeof maybeRunTargetedDriftReconciliation;
532
498
  cancelDustOrders: typeof cancelDustOrders;
533
- isOrderDoesNotExistError: typeof isOrderDoesNotExistError;
534
499
  runGridMaintenance: typeof runGridMaintenance;
535
- trackOutOfSpreadStaleness: typeof trackOutOfSpreadStaleness;
536
- stopMarketAdapterPm2: typeof stopMarketAdapterPm2;
537
500
  releaseMarketAdapterRuntime: typeof releaseMarketAdapterRuntime;
538
- syncMarketAdapterOnPeriodicConfigCheck: typeof syncMarketAdapterOnPeriodicConfigCheck;
539
- findSnapshotBotForRuntimeConfig: typeof findSnapshotBotForRuntimeConfig;
540
- runtimeConfigNeedsMarketAdapter: typeof runtimeConfigNeedsMarketAdapter;
541
- usesAmaGridPrice: typeof usesAmaGridPrice;
542
- checkBtsBalanceAndAcquire: typeof checkBtsBalanceAndAcquire;
543
- acquireBts: typeof acquireBts;
544
501
  runDustHealthCheck: typeof runDustHealthCheck;
545
502
  setupDustHealthCheckInterval: typeof setupDustHealthCheckInterval;
546
503
  requestGridReset: typeof requestGridReset;
@@ -549,8 +506,6 @@ declare const _default: {
549
506
  markGridActivity: typeof markGridActivity;
550
507
  getMetrics: typeof getMetrics;
551
508
  syncOpenOrdersAndProcessFills: typeof syncOpenOrdersAndProcessFills;
552
- shouldDeferMaintenanceForBroadcast: typeof shouldDeferMaintenanceForBroadcast;
553
- checkGridLockHoldDuration: typeof checkGridLockHoldDuration;
554
509
  _internalDeferredHold: {
555
510
  logDeferredHoldSummary: typeof logDeferredHoldSummary;
556
511
  describeDeferredHolds: typeof describeDeferredHolds;