dexbot 1.6.13 → 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 (93) hide show
  1. package/CHANGELOG.md +32 -0
  2. package/README.md +2 -2
  3. package/claw/docs/AI_BOT_LIBRARY_API.md +1 -1
  4. package/claw/docs/DEXBOT2_TUNING_CHEAT_SHEET.md +4 -4
  5. package/claw/modules/claw_catalog.ts +8 -4
  6. package/claw/modules/dexbot_profiles.ts +59 -15
  7. package/claw/modules/types.ts +2 -1
  8. package/claw/package.json +1 -1
  9. package/claw/runtimes/openclaw-plugin/openclaw.plugin.json +1 -1
  10. package/claw/runtimes/openclaw-plugin/package.json +1 -1
  11. package/claw/skills/margin-trading/SKILL.md +1 -1
  12. package/claw/skills/margin-trading/references/position-management.md +1 -1
  13. package/dist/analysis/tradingview/tradingview_uplot_chart_generator.js +25 -25
  14. package/dist/modules/account_bots.d.ts +7 -6
  15. package/dist/modules/account_bots.js +10 -10
  16. package/dist/modules/account_orders.d.ts +36 -4
  17. package/dist/modules/account_orders.js +76 -5
  18. package/dist/modules/bitshares-native/crypto/ecc_core.d.ts +1 -2
  19. package/dist/modules/bitshares-native/crypto/ecc_core.js +1 -1
  20. package/dist/modules/bitshares-native/serial/chain_constants.d.ts +1 -2
  21. package/dist/modules/bitshares-native/serial/chain_constants.js +1 -2
  22. package/dist/modules/bot_defaults.d.ts +16 -2
  23. package/dist/modules/bot_defaults.js +34 -8
  24. package/dist/modules/bot_settings.d.ts +4 -0
  25. package/dist/modules/bot_settings.js +55 -21
  26. package/dist/modules/config.js +6 -1
  27. package/dist/modules/constants.d.ts +7 -5
  28. package/dist/modules/constants.js +12 -5
  29. package/dist/modules/dexbot_class.d.ts +5 -0
  30. package/dist/modules/dexbot_class.js +8 -3
  31. package/dist/modules/dexbot_cow_runtime.d.ts +62 -174
  32. package/dist/modules/dexbot_cow_runtime.js +331 -46
  33. package/dist/modules/dexbot_credential_client.d.ts +1 -16
  34. package/dist/modules/dexbot_credential_client.js +1 -1
  35. package/dist/modules/dexbot_fill_runtime.d.ts +1 -1
  36. package/dist/modules/dexbot_fill_runtime.js +12 -1
  37. package/dist/modules/dexbot_maintenance_runtime.d.ts +18 -80
  38. package/dist/modules/dexbot_maintenance_runtime.js +57 -68
  39. package/dist/modules/dexbot_startup_runtime.js +12 -0
  40. package/dist/modules/dexbot_state_recovery.js +16 -0
  41. package/dist/modules/key_store.d.ts +0 -5
  42. package/dist/modules/key_store.js +1 -1
  43. package/dist/modules/order/accounting.js +11 -11
  44. package/dist/modules/order/export.js +2 -2
  45. package/dist/modules/order/format.d.ts +15 -1
  46. package/dist/modules/order/format.js +19 -1
  47. package/dist/modules/order/genesis_policy.d.ts +1 -1
  48. package/dist/modules/order/genesis_policy.js +1 -1
  49. package/dist/modules/order/grid.d.ts +23 -11
  50. package/dist/modules/order/grid.js +383 -51
  51. package/dist/modules/order/grid_reconcile.d.ts +1 -1
  52. package/dist/modules/order/grid_reconcile.js +5 -5
  53. package/dist/modules/order/grid_reconcile_internal.js +48 -40
  54. package/dist/modules/order/index.d.ts +34 -8
  55. package/dist/modules/order/logger.js +2 -2
  56. package/dist/modules/order/manager.d.ts +9 -2
  57. package/dist/modules/order/manager.js +58 -24
  58. package/dist/modules/order/strategy.d.ts +2 -2
  59. package/dist/modules/order/strategy.js +51 -21
  60. package/dist/modules/order/sync_engine.js +4 -0
  61. package/dist/modules/order/utils/math.d.ts +3 -3
  62. package/dist/modules/order/utils/math.js +38 -27
  63. package/dist/modules/order/utils/order.d.ts +58 -58
  64. package/dist/modules/order/utils/order.js +119 -102
  65. package/dist/modules/order/utils/system.d.ts +193 -6
  66. package/dist/modules/order/utils/system.js +392 -29
  67. package/dist/modules/order/utils/validate.js +26 -4
  68. package/dist/modules/runtime_settings.d.ts +1 -1
  69. package/dist/modules/runtime_settings.js +3 -3
  70. package/dist/modules/types.d.ts +48 -4
  71. package/dist/scripts/analyze-orders.d.ts +1 -1
  72. package/dist/scripts/analyze-orders.js +4 -4
  73. package/dist/scripts/divergence-calc.js +6 -6
  74. package/dist/scripts/validate_bots.d.ts +1 -1
  75. package/dist/scripts/validate_bots.js +3 -3
  76. package/dist/unlock.js +7 -2
  77. package/docs/COPY_ON_WRITE_MASTER_PLAN.md +1 -2
  78. package/docs/COW_INVARIANTS.md +6 -6
  79. package/docs/DEXBOT_COMPARISON.md +5 -5
  80. package/docs/EVOLUTION.md +8 -7
  81. package/docs/FUND_MOVEMENT_AND_ACCOUNTING.md +8 -6
  82. package/docs/GRID_PRICE_INVARIANT.md +3 -3
  83. package/docs/GRID_RECALCULATION.md +4 -1
  84. package/docs/GRID_RECONCILE.md +4 -4
  85. package/docs/LIFECYCLE.md +11 -11
  86. package/docs/LOGGING.md +14 -0
  87. package/docs/MPA_CREDIT_USAGE.md +1 -1
  88. package/docs/ORDER_ENGINE_POST_1.0_RETROSPECTIVE.md +12 -4
  89. package/docs/README.md +3 -3
  90. package/docs/architecture.md +6 -6
  91. package/docs/developer_guide.md +7 -2
  92. package/package.json +1 -1
  93. package/tests/README.md +1 -1
@@ -12,32 +12,6 @@ interface HeldChainOrder {
12
12
  }
13
13
  import { usesAmaGridPrice } from './grid_price_source.js';
14
14
  declare const 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;
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,30 @@ 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;
96
70
  /**
97
71
  * Mirror a spread-check stall into the flags the targeted-sync gate reads.
98
72
  *
@@ -126,11 +100,6 @@ declare function maybeRunTargetedDriftReconciliation(bot: BotLike, context: stri
126
100
  * @returns {unknown} Snapshot with exists flag, fingerprint, active bots list, and adapter requirement
127
101
  */
128
102
  declare function loadBotsConfigSnapshot(): any;
129
- /**
130
- * Stop and delete the market adapter process from PM2.
131
- * @returns {Promise<void>}
132
- */
133
- declare function stopMarketAdapterPm2(): Promise<void>;
134
103
  /**
135
104
  * Synchronize market adapter state based on periodic config checks.
136
105
  * Starts or stops the market adapter based on whether any active bot uses AMA grid pricing.
@@ -412,22 +381,6 @@ declare function cancelDustOrders(bot: BotLike, { buy: buyDust, sell: sellDust }
412
381
  declare function runGridMaintenance(bot: BotLike, context?: string, options?: {
413
382
  skipIdle?: boolean;
414
383
  }): Promise<void>;
415
- /**
416
- * Check if the bot's BTS balance is below the minimum threshold and trigger acquisition.
417
- * Only applies to non-BTS pairs. Uses hysteresis: triggers at 1× min_BTS_value,
418
- * fills to BTS_ACQUIRE_TARGET_MULTIPLIER × min_BTS_value.
419
- * @param {import('./dexbot_class.js').DEXBot} bot
420
- * @returns {Promise<void>}
421
- */
422
- declare function checkBtsBalanceAndAcquire(bot: BotLike): Promise<void>;
423
- /**
424
- * Acquire BTS by swapping one of the trading pair assets through an AMM pool.
425
- * Tries both assets for a BTS pool, picks the best (lowest price impact).
426
- * @param {import('./dexbot_class.js').DEXBot} bot
427
- * @param {number} deficit - Amount of BTS needed (float)
428
- * @returns {Promise<void>}
429
- */
430
- declare function acquireBts(bot: BotLike, deficit: number): Promise<void>;
431
384
  /**
432
385
  * Run a single dust health check cycle.
433
386
  * @param {import('./dexbot_class.js').DEXBot} bot
@@ -482,6 +435,7 @@ declare function markGridActivity(bot: BotLike, reason?: string): void;
482
435
  * @returns {Object}
483
436
  */
484
437
  declare function getMetrics(bot: BotLike): {
438
+ boundaryDriftExceedsWindowCount: number;
485
439
  queueDepth: number;
486
440
  fillProcessingLockActive: boolean;
487
441
  divergenceLockActive: boolean;
@@ -498,6 +452,10 @@ declare function getMetrics(bot: BotLike): {
498
452
  maxQueueDepth: number;
499
453
  gridLockContention: number;
500
454
  fundRecalcCount: number;
455
+ refusedCommitCount: number;
456
+ orphanFillCreditedCount: number;
457
+ restampBuyAboveAnchorCount: number;
458
+ gapBandPlacementShadowCount: number;
501
459
  };
502
460
  /**
503
461
  * Read open orders from chain, sync with local state, and process any fills found.
@@ -522,15 +480,10 @@ declare function syncOpenOrdersAndProcessFills(bot: BotLike, tag: string): Promi
522
480
  hasUnmatched: number;
523
481
  openOrders: import("./types.js").ChainOrder[];
524
482
  }>;
525
- 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 };
526
484
  declare const _default: {
527
- loadBotsConfigSnapshot: typeof loadBotsConfigSnapshot;
528
- isWrapperAdapterOwner: (...args: unknown[]) => any;
529
- checkAndApplyBotConfigChanges: typeof checkAndApplyBotConfigChanges;
530
- buildBotConfigFingerprint: typeof buildBotConfigFingerprint;
531
485
  refreshDynamicWeightDistribution: typeof refreshDynamicWeightDistribution;
532
486
  performGridResync: typeof performGridResync;
533
- updateBotGridResetMetadata: typeof updateBotGridResetMetadata;
534
487
  handlePendingTriggerReset: typeof handlePendingTriggerReset;
535
488
  setupTriggerFileDetection: typeof setupTriggerFileDetection;
536
489
  performPeriodicGridChecks: typeof performPeriodicGridChecks;
@@ -542,22 +495,9 @@ declare const _default: {
542
495
  setupBotsConfigPollInterval: typeof setupBotsConfigPollInterval;
543
496
  stopBotsConfigPollInterval: typeof stopBotsConfigPollInterval;
544
497
  executeMaintenanceLogic: typeof executeMaintenanceLogic;
545
- getTargetedSyncReason: typeof getTargetedSyncReason;
546
- mirrorSpreadStall: typeof mirrorSpreadStall;
547
- countLiveReserveOrders: typeof countLiveReserveOrders;
548
- maybeRunTargetedDriftReconciliation: typeof maybeRunTargetedDriftReconciliation;
549
498
  cancelDustOrders: typeof cancelDustOrders;
550
- isOrderDoesNotExistError: typeof isOrderDoesNotExistError;
551
499
  runGridMaintenance: typeof runGridMaintenance;
552
- trackOutOfSpreadStaleness: typeof trackOutOfSpreadStaleness;
553
- stopMarketAdapterPm2: typeof stopMarketAdapterPm2;
554
500
  releaseMarketAdapterRuntime: typeof releaseMarketAdapterRuntime;
555
- syncMarketAdapterOnPeriodicConfigCheck: typeof syncMarketAdapterOnPeriodicConfigCheck;
556
- findSnapshotBotForRuntimeConfig: typeof findSnapshotBotForRuntimeConfig;
557
- runtimeConfigNeedsMarketAdapter: typeof runtimeConfigNeedsMarketAdapter;
558
- usesAmaGridPrice: typeof usesAmaGridPrice;
559
- checkBtsBalanceAndAcquire: typeof checkBtsBalanceAndAcquire;
560
- acquireBts: typeof acquireBts;
561
501
  runDustHealthCheck: typeof runDustHealthCheck;
562
502
  setupDustHealthCheckInterval: typeof setupDustHealthCheckInterval;
563
503
  requestGridReset: typeof requestGridReset;
@@ -566,8 +506,6 @@ declare const _default: {
566
506
  markGridActivity: typeof markGridActivity;
567
507
  getMetrics: typeof getMetrics;
568
508
  syncOpenOrdersAndProcessFills: typeof syncOpenOrdersAndProcessFills;
569
- shouldDeferMaintenanceForBroadcast: typeof shouldDeferMaintenanceForBroadcast;
570
- checkGridLockHoldDuration: typeof checkGridLockHoldDuration;
571
509
  _internalDeferredHold: {
572
510
  logDeferredHoldSummary: typeof logDeferredHoldSummary;
573
511
  describeDeferredHolds: typeof describeDeferredHolds;
@@ -14,6 +14,7 @@ import * as chainOrders from './chain_orders.js';
14
14
  import * as grid from './order/grid.js';
15
15
  import { ORDER_STATES, ORDER_TYPES, TIMING, BTS_PRECISION, NATIVE_CLIENT } from './constants.js';
16
16
  import { BOT_LIVE_CONFIG_KEYS } from './runtime_settings.js';
17
+ import { migrateLegacyOrderKeys } from './bot_defaults.js';
17
18
  import { acquireIfNotHeld } from './order/async_lock.js';
18
19
  const { readOpenOrdersGuarded } = chainOrders;
19
20
  import { PATHS } from './paths.js';
@@ -59,15 +60,15 @@ const updateDynamicGridSnapshotSync = lazyShim('../market_adapter/utils/dynamic_
59
60
  // would be circular; at call time both modules are fully loaded.
60
61
  const scheduleFillConsumerRestartFn = lazyShim('./dexbot_fill_runtime', 'scheduleFillConsumerRestart');
61
62
  const reconcileGridOrders = lazyShim('./order/grid_reconcile', 'reconcileGridOrders');
62
- const resolveReserveCount = lazyShim('./order/utils/order', 'resolveReserveCount');
63
- const reserveEdgeIdSet = lazyShim('./order/utils/order', 'reserveEdgeIdSet');
63
+ const resolveEdgeCount = lazyShim('./order/utils/order', 'resolveEdgeCount');
64
+ const edgeOrderIdSet = lazyShim('./order/utils/order', 'edgeOrderIdSet');
64
65
  const liveWindowIdSet = lazyShim('./order/utils/order', 'liveWindowIdSet');
65
- const resolveLiveReserveEdgeAnchorPrice = lazyShim('./order/utils/order', 'resolveLiveReserveEdgeAnchorPrice');
66
+ const resolveLiveEdgeAnchorPrice = lazyShim('./order/utils/order', 'resolveLiveEdgeAnchorPrice');
66
67
  const formatUnmatchedChainOrder = lazyShim('./order/utils/order', 'formatUnmatchedChainOrder');
67
68
  const isNonBlockingUnmatchedOrder = lazyShim('./order/utils/order', 'isNonBlockingUnmatchedOrder');
68
69
  const isStrandedHoldOrder = lazyShim('./order/utils/order', 'isStrandedHoldOrder');
69
70
  const getSideBudget = lazyShim('./order/utils/order', 'getSideBudget');
70
- function getActiveOrdersTotal(config) { return require('./order/utils/order').getActiveOrdersTotal(config); }
71
+ function getCoreOrdersTotal(config) { return require('./order/utils/order').getCoreOrdersTotal(config); }
71
72
  const correctAllPriceMismatches = lazyShim('./order/utils/order', 'correctAllPriceMismatches');
72
73
  const isOrderOnChain = lazyShim('./order/utils/order', 'isOrderOnChain');
73
74
  const parseChainOrder = lazyShim('./order/utils/order', 'parseChainOrder');
@@ -207,7 +208,10 @@ function normalizeBotEntryForFingerprint(entry) {
207
208
  continue;
208
209
  out[key] = e[key];
209
210
  }
210
- return out;
211
+ // Canonicalize legacy order-count keys so the fingerprint and the merged
212
+ // entry agree with the allowlist (`coreOrders`/`edgeOrders`) even when the
213
+ // on-disk bots.json still carries `activeOrders`/`reserveOrders`.
214
+ return migrateLegacyOrderKeys(out);
211
215
  }
212
216
  /**
213
217
  * Build the full-entry fingerprint for one bot (stable across key order and
@@ -253,7 +257,7 @@ function mergeBotConfigKeysIntoRuntime(bot, entry, keys) {
253
257
  const applied = [];
254
258
  if (!bot?.config || !entry || typeof entry !== 'object')
255
259
  return applied;
256
- const e = entry;
260
+ const e = migrateLegacyOrderKeys({ ...entry });
257
261
  for (const key of keys) {
258
262
  // A deleted key applies as null (mirrors the former ?? null diff
259
263
  // semantics) so the running config can never keep a stale value.
@@ -284,7 +288,7 @@ function mergeBotConfigKeysIntoRuntime(bot, entry, keys) {
284
288
  function replaceBotConfigFromEntryPreservingRuntime(bot, updatedBot, contextLabel) {
285
289
  const oldKey = bot.config.botKey;
286
290
  const oldIndex = bot.config.botIndex;
287
- const u = updatedBot;
291
+ const u = migrateLegacyOrderKeys({ ...updatedBot });
288
292
  // Preserve runtime-only properties set by the constructor
289
293
  // (timing, gridLimits, feeParams, etc.) that are not present
290
294
  // in the raw profile from bots.json.
@@ -546,50 +550,50 @@ function countLiveGridOrders(manager, type) {
546
550
  const active = manager.getOrdersByTypeAndState?.(type, ORDER_STATES.ACTIVE) || [];
547
551
  const partial = manager.getOrdersByTypeAndState?.(type, ORDER_STATES.PARTIAL) || [];
548
552
  // Slot-N gated: fork-kept shelf/manual orders (non-slot-N ids, e.g.
549
- // deep-*) sit outside window accounting — same gate as reserve
553
+ // deep-*) sit outside window accounting — same gate as edge
550
554
  // classification and startup cancel candidates (issue #27 follow-up).
551
- // Without this, a live shelf inflates the live window+reserves count and
552
- // masks a real window/reserve shortfall, so targeted sync never fires.
555
+ // Without this, a live shelf inflates the live window+edges count and
556
+ // masks a real window/edge shortfall, so targeted sync never fires.
553
557
  // No-op on grids that only mint slot-N ids.
554
558
  return active.concat(partial).filter((o) => o?.orderId && parseSlotIndex(o?.id) !== null).length;
555
559
  }
556
- function getTargetActiveOrders(config, side) {
557
- const configured = Number(config?.activeOrders?.[side]);
558
- // Reserve ladder rests live on-chain: countLiveGridOrders sees window +
559
- // edge orders, so the shortfall target must include reserves too —
560
- // otherwise live reserves mask window shortfalls and a filled/cancelled
561
- // reserve order never triggers targeted reconciliation.
562
- const reserves = resolveReserveCount(config, side);
563
- return Math.max(0, Number.isFinite(configured) ? configured : 1) + reserves;
560
+ function getTargetCoreOrders(config, side) {
561
+ const configured = Number(config?.coreOrders?.[side]);
562
+ // Edge ladder rests live on-chain: countLiveGridOrders sees window +
563
+ // edge orders, so the shortfall target must include edge orders too —
564
+ // otherwise live edge orders mask window shortfalls and a filled/cancelled
565
+ // edge order never triggers targeted reconciliation.
566
+ const edgeCount = resolveEdgeCount(config, side);
567
+ return Math.max(0, Number.isFinite(configured) ? configured : 1) + edgeCount;
564
568
  }
565
569
  /**
566
- * Count live on-chain reserve orders for one side (issue #27 follow-up).
570
+ * Count live on-chain edge orders for one side (issue #27 follow-up).
567
571
  *
568
- * The window shortfall check above compares live window+reserves against
569
- * window+reserves, so a pre-existing window surplus masks a reserve deficit
570
- * (e.g. target 6+2=8 vs 12 live after reserveOrders 0→2: no shortfall, no
571
- * sync, zero reserve placements). Reserves get their own independent reason
572
- * below — the mirror of the masking case getTargetActiveOrders handles.
572
+ * The window shortfall check above compares live window+edges against
573
+ * window+edges, so a pre-existing window surplus masks an edge deficit
574
+ * (e.g. target 6+2=8 vs 12 live after edgeOrders 0→2: no shortfall, no
575
+ * sync, zero edge placements). Edge orders get their own independent reason
576
+ * below — the mirror of the masking case getTargetCoreOrders handles.
573
577
  *
574
- * Classification reuses the single source of truth (reserveEdgeIdSet +
575
- * resolveLiveReserveEdgeAnchorPrice, same anchor the placement pickers use)
578
+ * Classification reuses the single source of truth (edgeOrderIdSet +
579
+ * resolveLiveEdgeAnchorPrice, same anchor the placement pickers use)
576
580
  * over the full master grid, intersected with live ACTIVE/PARTIAL orderIds
577
581
  * (same live definition as countLiveGridOrders). The edge pick excludes the
578
582
  * window (liveWindowIdSet — the same exclusion every placement picker
579
583
  * applies): window + edge are additive in targets/fees/hold-back, but
580
584
  * without the exclusion a window that reaches the grid edge (keep-low
581
585
  * window = bottom slots = floor edge) makes the edge pick land on window
582
- * members and the count reads N/N with zero dedicated reserves, so the
586
+ * members and the count reads N/N with zero dedicated edge orders, so the
583
587
  * deficit never fires (issue #27 follow-up).
584
588
  * @param {unknown} manager - OrderManager
585
- * @param {unknown} config - Bot configuration (reserve count source)
589
+ * @param {unknown} config - Bot configuration (edge count source)
586
590
  * @param {unknown} type - ORDER_TYPES.BUY or ORDER_TYPES.SELL
587
- * @returns {number|null} Live reserve count, or null when unclassifiable
591
+ * @returns {number|null} Live edge count, or null when unclassifiable
588
592
  */
589
- function countLiveReserveOrders(manager, config, type) {
593
+ function countLiveEdgeOrders(manager, config, type) {
590
594
  try {
591
595
  const side = type === ORDER_TYPES.SELL ? 'sell' : 'buy';
592
- const required = resolveReserveCount(config, side);
596
+ const required = resolveEdgeCount(config, side);
593
597
  if (!(required > 0))
594
598
  return 0;
595
599
  if (!manager)
@@ -602,13 +606,13 @@ function countLiveReserveOrders(manager, config, type) {
602
606
  const allSlots = Array.from(manager.orders.values());
603
607
  if (allSlots.length === 0)
604
608
  return null;
605
- const anchor = resolveLiveReserveEdgeAnchorPrice(manager, side);
609
+ const anchor = resolveLiveEdgeAnchorPrice(manager, side);
606
610
  // Fail open on unknown window geometry (null): without a boundary the
607
- // pickers cannot place reserves either, so keep the previous
611
+ // pickers cannot place edge orders either, so keep the previous
608
612
  // (exclusion-free) classification instead of guessing.
609
613
  const windowIds = liveWindowIdSet(manager, type);
610
- const reserveIds = reserveEdgeIdSet(allSlots, config, type, anchor, windowIds);
611
- if (!reserveIds || reserveIds.size === 0)
614
+ const edgeIds = edgeOrderIdSet(allSlots, config, type, anchor, windowIds);
615
+ if (!edgeIds || edgeIds.size === 0)
612
616
  return 0;
613
617
  const liveIds = new Set();
614
618
  if (typeof manager.getOrdersByTypeAndState === 'function') {
@@ -626,7 +630,7 @@ function countLiveReserveOrders(manager, config, type) {
626
630
  }
627
631
  }
628
632
  let live = 0;
629
- for (const id of reserveIds) {
633
+ for (const id of edgeIds) {
630
634
  if (liveIds.has(String(id)))
631
635
  live++;
632
636
  }
@@ -644,7 +648,7 @@ function _hasBudgetForSide(manager, config, side) {
644
648
  const allocated = side === 'buy' ? (funds.allocatedBuy || 0) : (funds.allocatedSell || 0);
645
649
  if (allocated <= 0)
646
650
  return false;
647
- const totalTarget = getActiveOrdersTotal(config);
651
+ const totalTarget = getCoreOrdersTotal(config);
648
652
  const budget = getSideBudget(side, funds, config, totalTarget);
649
653
  return budget > 0;
650
654
  }
@@ -674,8 +678,8 @@ export function mirrorSpreadStall(bot, stall) {
674
678
  function getTargetedSyncReason(bot) {
675
679
  if (!bot.manager || bot.config?.dryRun)
676
680
  return null;
677
- const targetBuy = getTargetActiveOrders(bot.config, 'buy');
678
- const targetSell = getTargetActiveOrders(bot.config, 'sell');
681
+ const targetBuy = getTargetCoreOrders(bot.config, 'buy');
682
+ const targetSell = getTargetCoreOrders(bot.config, 'sell');
679
683
  const liveBuy = countLiveGridOrders(bot.manager, ORDER_TYPES.BUY);
680
684
  const liveSell = countLiveGridOrders(bot.manager, ORDER_TYPES.SELL);
681
685
  const shortfalls = [];
@@ -689,18 +693,18 @@ function getTargetedSyncReason(bot) {
689
693
  shortfalls.push(`sell ${liveSell}/${targetSell}`);
690
694
  }
691
695
  }
692
- // Reserve deficit is independent of window surplus: a bot carrying extra
693
- // rail/stranded orders can sit above target while its reserve edge is
694
- // empty (live-applied reserveOrders 0→N, filled/cancelled reserve).
696
+ // Edge deficit is independent of window surplus: a bot carrying extra
697
+ // rail/stranded orders can sit above target while its edge order is
698
+ // empty (live-applied edgeOrders 0→N, filled/cancelled edge order).
695
699
  // Without this, placement waits for fills or the 4h fetch (issue #27).
696
700
  for (const [type, side] of [[ORDER_TYPES.BUY, 'buy'], [ORDER_TYPES.SELL, 'sell']]) {
697
- const required = resolveReserveCount(bot.config, side);
701
+ const required = resolveEdgeCount(bot.config, side);
698
702
  if (!(required > 0))
699
703
  continue;
700
- const liveReserves = countLiveReserveOrders(bot.manager, bot.config, type);
701
- if (liveReserves !== null && liveReserves < required) {
704
+ const liveEdges = countLiveEdgeOrders(bot.manager, bot.config, type);
705
+ if (liveEdges !== null && liveEdges < required) {
702
706
  if (_hasBudgetForSide(bot.manager, bot.config, side)) {
703
- shortfalls.push(`${side} reserves ${liveReserves}/${required}`);
707
+ shortfalls.push(`${side} edges ${liveEdges}/${required}`);
704
708
  }
705
709
  }
706
710
  }
@@ -2758,7 +2762,7 @@ async function checkBtsBalanceAndAcquire(bot) {
2758
2762
  return;
2759
2763
  if (!bot.manager || !bot.manager.btsBalance)
2760
2764
  return;
2761
- const totalTarget = getActiveOrdersTotal(bot.config);
2765
+ const totalTarget = getCoreOrdersTotal(bot.config);
2762
2766
  const btsReservationMultiplier = bot.config?.feeParams?.BTS_RESERVATION_MULTIPLIER;
2763
2767
  const minBtsVal = calculateOrderCreationFees(bot.config.assetA, bot.config.assetB, totalTarget, btsReservationMultiplier);
2764
2768
  if (minBtsVal <= 0)
@@ -3171,6 +3175,11 @@ function getMetrics(bot) {
3171
3175
  const heldUnmatched = unmatched.filter((u) => isNonBlockingUnmatchedOrder(u));
3172
3176
  return {
3173
3177
  ...bot._metrics,
3178
+ // The boundary-drift counter is written by the strategy engine on the
3179
+ // MANAGER's metrics object (calculateTargetGrid has no bot reference),
3180
+ // so overlay it here — otherwise the P2 signal is counted but never
3181
+ // surfaced by getMetrics().
3182
+ boundaryDriftExceedsWindowCount: bot.manager?._metrics?.boundaryDriftExceedsWindowCount ?? bot._metrics.boundaryDriftExceedsWindowCount,
3174
3183
  queueDepth: bot._incomingFillQueue.length,
3175
3184
  fillProcessingLockActive: bot.manager?._fillProcessingLock?.isLocked() || false,
3176
3185
  divergenceLockActive: bot.manager?._divergenceLock?.isLocked() || false,
@@ -3254,15 +3263,10 @@ async function syncOpenOrdersAndProcessFillsImpl(bot, tag) {
3254
3263
  return { syncResult: null, aborted: true, hasUnmatched: -1, openOrders: null };
3255
3264
  }
3256
3265
  }
3257
- 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 };
3266
+ 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 };
3258
3267
  export default {
3259
- loadBotsConfigSnapshot,
3260
- isWrapperAdapterOwner,
3261
- checkAndApplyBotConfigChanges,
3262
- buildBotConfigFingerprint,
3263
3268
  refreshDynamicWeightDistribution,
3264
3269
  performGridResync,
3265
- updateBotGridResetMetadata,
3266
3270
  handlePendingTriggerReset,
3267
3271
  setupTriggerFileDetection,
3268
3272
  performPeriodicGridChecks,
@@ -3274,22 +3278,9 @@ export default {
3274
3278
  setupBotsConfigPollInterval,
3275
3279
  stopBotsConfigPollInterval,
3276
3280
  executeMaintenanceLogic,
3277
- getTargetedSyncReason,
3278
- mirrorSpreadStall,
3279
- countLiveReserveOrders,
3280
- maybeRunTargetedDriftReconciliation,
3281
3281
  cancelDustOrders,
3282
- isOrderDoesNotExistError,
3283
3282
  runGridMaintenance,
3284
- trackOutOfSpreadStaleness,
3285
- stopMarketAdapterPm2,
3286
3283
  releaseMarketAdapterRuntime,
3287
- syncMarketAdapterOnPeriodicConfigCheck,
3288
- findSnapshotBotForRuntimeConfig,
3289
- runtimeConfigNeedsMarketAdapter,
3290
- usesAmaGridPrice,
3291
- checkBtsBalanceAndAcquire,
3292
- acquireBts,
3293
3284
  runDustHealthCheck,
3294
3285
  setupDustHealthCheckInterval,
3295
3286
  requestGridReset,
@@ -3298,8 +3289,6 @@ export default {
3298
3289
  markGridActivity,
3299
3290
  getMetrics,
3300
3291
  syncOpenOrdersAndProcessFills,
3301
- shouldDeferMaintenanceForBroadcast,
3302
- checkGridLockHoldDuration,
3303
3292
  _internalDeferredHold: { logDeferredHoldSummary, describeDeferredHolds, considerDeferredHoldEscalation },
3304
3293
  };
3305
3294
  //# sourceMappingURL=dexbot_maintenance_runtime.js.map
@@ -13,6 +13,7 @@ import { BitShares, onReconnect as registerReconnectHook } from './bitshares_cli
13
13
  import orderModule from './order/index.js';
14
14
  import { getErrorMessage } from './utils/errors.js';
15
15
  import { processSweepOrphanFill } from './dexbot_fill_runtime.js';
16
+ import { restoreLastMarketFill } from './order/utils/system.js';
16
17
  import { ON_MISSING_GENESIS, recordMissingGenesisFault, resolvePersistedGenesis } from './order/genesis_policy.js';
17
18
  const { OrderManager, grid: Grid } = orderModule;
18
19
  const initializeFeeCache = lazyShim('./order/utils/system', 'initializeFeeCache');
@@ -209,6 +210,17 @@ async function startPostBootstrapSubsystems(bot) {
209
210
  async function finishStartupSequence(bot, startupState) {
210
211
  let { persistedGrid, persistedBtsFeesOwed, persistedBoundaryIdx, persistedBtsBalance, persistedRecentFillKeys, persistedGenesis, persistedGapEvacStreaks, } = startupState;
211
212
  try {
213
+ // Bot-scoped last-market-fill reference: restore BEFORE any chain
214
+ // touching/placement work so spread correction (including the
215
+ // post-reset path below) always has the last real trade price it must
216
+ // not cross. Independent of the boundary/genesis restore, so a
217
+ // regenerated grid still gets the anchor the genesis-bound pivot lost.
218
+ try {
219
+ restoreLastMarketFill(bot.manager, bot.manager?.accountOrders?.loadLastMarketFill?.() ?? null);
220
+ }
221
+ catch (marketRefErr) {
222
+ bot._warn(`[SPREAD-CORRECTION] Last-market-fill restore failed (${getErrorMessage(marketRefErr)}); spread correction runs without a market anchor`);
223
+ }
212
224
  if (typeof bot._fillsUnsubscribe === 'function') {
213
225
  await bot._fillsUnsubscribe().catch(() => { });
214
226
  }
@@ -591,6 +591,22 @@ async function rejectCorruptedGridSnapshot(bot, context) {
591
591
  `drift sell=${Number(driftCheck.driftSell ?? 0).toFixed(2)} buy=${Number(driftCheck.driftBuy ?? 0).toFixed(2)}. ` +
592
592
  `Deleting corrupted snapshot.`);
593
593
  if (bot.accountOrders && typeof bot.accountOrders.clearGrid === 'function') {
594
+ // Keep a timestamped copy before the destructive clear. Drift is not
595
+ // always corruption (genuine unadopted orphans, re-anchoring), so the
596
+ // pre-reject grid/boundary/pivot/crawls are the only forensics and the
597
+ // only path to manual recovery. AccountOrders owns the path/storage
598
+ // knowledge. Best-effort: the clear proceeds either way.
599
+ try {
600
+ const backupPath = typeof bot.accountOrders.backupSnapshot === 'function'
601
+ ? await bot.accountOrders.backupSnapshot('rejected-drift')
602
+ : null;
603
+ if (backupPath) {
604
+ bot._warn(`${tag} Kept pre-reject snapshot copy at ${backupPath}`);
605
+ }
606
+ }
607
+ catch (backupErr) {
608
+ bot._warn(`${tag} Failed to keep pre-reject snapshot copy: ${getErrorMessage(backupErr)}`);
609
+ }
594
610
  try {
595
611
  await bot.accountOrders.clearGrid();
596
612
  bot._warn(`${tag} Corrupted grid snapshot deleted.`);
@@ -13,11 +13,6 @@ export interface KeyStore {
13
13
  isDaemonSigningKey(key: unknown): boolean;
14
14
  executeOperations(accountName: string, operations: ChainOrderOperation[], signingKey: unknown, extraOptions?: Record<string, unknown>): Promise<SigningResult>;
15
15
  }
16
- export declare class DaemonKeyStore implements KeyStore {
17
- resolveSigningKey(accountName: string, vaultSecret?: unknown, chainClient?: unknown): Promise<unknown>;
18
- isDaemonSigningKey(key: unknown): boolean;
19
- executeOperations(accountName: string, operations: ChainOrderOperation[], signingKey: unknown, extraOptions?: Record<string, unknown>): Promise<SigningResult>;
20
- }
21
16
  export declare function setKeyStore(impl: KeyStore | null): void;
22
17
  export declare function resetKeyStore(): void;
23
18
  export declare function getKeyStore(): KeyStore;
@@ -69,7 +69,7 @@ async function broadcastViaChainOrders(accountName, operations, signingKey) {
69
69
  await broadcastTxWithClassification(tx, accountName, operations);
70
70
  return { success: true };
71
71
  }
72
- export class DaemonKeyStore {
72
+ class DaemonKeyStore {
73
73
  async resolveSigningKey(accountName, vaultSecret, chainClient) {
74
74
  if (vaultSecret) {
75
75
  return chainKeys.resolvePrivateKey(accountName, vaultSecret, chainClient);
@@ -74,7 +74,7 @@ import { createRequire } from 'node:module';
74
74
  const require = createRequire(import.meta.url);
75
75
  import { ORDER_TYPES, ORDER_STATES, PIPELINE_TIMING, TIMING, FEE_PARAMETERS, GRID_LIMITS } from '../constants.js';
76
76
  import { resolveAccountRef } from './utils/system.js';
77
- import { resolveSpreadOrderSide, parseSlotIndex, parseChainOrder, applyChainSizeToGridOrder, convertToSpreadPlaceholder, resolveReserveCount } from './utils/order.js';
77
+ import { resolveSpreadOrderSide, parseSlotIndex, parseChainOrder, applyChainSizeToGridOrder, convertToSpreadPlaceholder, resolveEdgeCount } from './utils/order.js';
78
78
  import { isSlotInRail, floatToBlockchainInt } from './utils/math.js';
79
79
  import * as Format from './format.js';
80
80
  import * as fundRegistry from '../fund_registry.js';
@@ -429,19 +429,19 @@ class Accountant {
429
429
  mgr.funds.total.grid = { buy: gridBuy + virtualBuy, sell: gridSell + virtualSell };
430
430
  // STEP 6: Calculate available funds (what we can spend right now)
431
431
  // Uses utils::calculateAvailableFundsValue which deducts committe amounts
432
- // Reserve ladder rides on the side counts for fee reservation: reserves
432
+ // Edge ladder rides on the side counts for fee reservation: edge orders
433
433
  // rest live on-chain and pay creation fees like window orders.
434
- const reserveBuy = resolveReserveCount(mgr.config, 'buy');
435
- const reserveSell = resolveReserveCount(mgr.config, 'sell');
436
- const feeActiveOrders = mgr.config.activeOrders && typeof mgr.config.activeOrders === 'object'
434
+ const edgeBuy = resolveEdgeCount(mgr.config, 'buy');
435
+ const edgeSell = resolveEdgeCount(mgr.config, 'sell');
436
+ const feeCoreOrders = mgr.config.coreOrders && typeof mgr.config.coreOrders === 'object'
437
437
  ? {
438
- ...mgr.config.activeOrders,
439
- buy: Math.max(0, Number(mgr.config.activeOrders.buy) || 0) + reserveBuy,
440
- sell: Math.max(0, Number(mgr.config.activeOrders.sell) || 0) + reserveSell,
438
+ ...mgr.config.coreOrders,
439
+ buy: Math.max(0, Number(mgr.config.coreOrders.buy) || 0) + edgeBuy,
440
+ sell: Math.max(0, Number(mgr.config.coreOrders.sell) || 0) + edgeSell,
441
441
  }
442
- : mgr.config.activeOrders;
443
- mgr.funds.available.buy = calculateAvailableFundsValue('buy', mgr.accountTotals, mgr.funds, mgr.config.assetA, mgr.config.assetB, feeActiveOrders, mgr.config.min_BTS_value, mgr.config?.feeParams ?? null);
444
- mgr.funds.available.sell = calculateAvailableFundsValue('sell', mgr.accountTotals, mgr.funds, mgr.config.assetA, mgr.config.assetB, feeActiveOrders, mgr.config.min_BTS_value, mgr.config?.feeParams ?? null);
442
+ : mgr.config.coreOrders;
443
+ mgr.funds.available.buy = calculateAvailableFundsValue('buy', mgr.accountTotals, mgr.funds, mgr.config.assetA, mgr.config.assetB, feeCoreOrders, mgr.config.min_BTS_value, mgr.config?.feeParams ?? null);
444
+ mgr.funds.available.sell = calculateAvailableFundsValue('sell', mgr.accountTotals, mgr.funds, mgr.config.assetA, mgr.config.assetB, feeCoreOrders, mgr.config.min_BTS_value, mgr.config?.feeParams ?? null);
445
445
  // Ensure percentage-based allocations are applied to the newly calculated totals
446
446
  if (typeof mgr.applyBotFundsAllocation === 'function') {
447
447
  mgr.applyBotFundsAllocation();
@@ -477,8 +477,8 @@ async function writeSettingsJSON(botConfig, botName, outputPath) {
477
477
  max_price: botConfig.maxPrice || DEFAULT_CONFIG.maxPrice,
478
478
  increment_percent: botConfig.incrementPercent || DEFAULT_CONFIG.incrementPercent,
479
479
  target_spread_percent: botConfig.targetSpreadPercent || DEFAULT_CONFIG.targetSpreadPercent,
480
- active_orders: botConfig.activeOrders || DEFAULT_CONFIG.activeOrders,
481
- reserve_orders: botConfig.reserveOrders ?? DEFAULT_CONFIG.reserveOrders,
480
+ core_orders: botConfig.coreOrders || DEFAULT_CONFIG.coreOrders,
481
+ edge_orders: botConfig.edgeOrders ?? DEFAULT_CONFIG.edgeOrders,
482
482
  bot_funds: botConfig.botFunds || DEFAULT_CONFIG.botFunds,
483
483
  weight_distribution: botConfig.weightDistribution || DEFAULT_CONFIG.weightDistribution,
484
484
  dry_run: botConfig.dryRun || false,
@@ -165,6 +165,20 @@ declare function toFiniteNumber(value: unknown, defaultValue: number | null): nu
165
165
  * non-numeric strings all yield `null`.
166
166
  */
167
167
  declare function positiveOrNull(value: unknown): number | null;
168
+ /**
169
+ * Convert a value to a finite number but treat an explicitly absent value
170
+ * (`null`/`undefined`/`''`) as unknown (`NaN`) instead of `0`.
171
+ *
172
+ * `Number(null) === 0` and `Number('') === 0` are finite, so a plain `Number()`
173
+ * coercion reads "no value" as the valid value 0 — the trap that made an
174
+ * unknown boundary read as slot 0, an unknown gap width collapse the band, and
175
+ * an unknown fill timestamp read as epoch. Use this for any geometry/index/
176
+ * count field where 0 is legitimate and absence must stay detectable.
177
+ *
178
+ * A genuine `0` (number, `'0'`, `false`) still converts to `0`. Pair with
179
+ * `Number.isFinite` at the call site where absent must fail closed.
180
+ */
181
+ declare function toKnownNumber(value: unknown): number;
168
182
  /**
169
183
  * Safely format a numeric value with specified decimals and fallback.
170
184
  *
@@ -174,5 +188,5 @@ declare function positiveOrNull(value: unknown): number | null;
174
188
  * @returns {string} Formatted value or fallback string
175
189
  */
176
190
  declare function safeFormat(value: unknown, decimals: number, fallback?: string): string;
177
- export { formatAmount8, formatAmount, formatAmountByPrecision, formatSizeByOrderType, formatPrice, formatPrice6, formatPrice4, formatCurrency, formatFundsValue, formatPercent2, formatPercent, formatMetric2, isValidNumber, toFiniteNumber, positiveOrNull, safeFormat };
191
+ export { formatAmount8, formatAmount, formatAmountByPrecision, formatSizeByOrderType, formatPrice, formatPrice6, formatPrice4, formatCurrency, formatFundsValue, formatPercent2, formatPercent, formatMetric2, isValidNumber, toFiniteNumber, toKnownNumber, positiveOrNull, safeFormat };
178
192
  //# sourceMappingURL=format.d.ts.map