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
@@ -30,7 +30,7 @@ import { ORDER_TYPES, ORDER_STATES, REBALANCE_STATES, TIMING, LOG_LEVEL, PIPELIN
30
30
  import { seedBotRuntimeConfig } from '../bot_defaults.js';
31
31
  import { getMinOrderSize, computeChainFundTotals, hasValidAccountTotals, resolveConfigValueWithRegistry, isExplicitZeroAllocation, floatToBlockchainInt, validateBoundaryCommit, resolveGapSlots, resolveGapBand, isSlotInRail } from './utils/math.js';
32
32
  import { validateOrder, validateGridForPersistence, validateWorkingGridFunds, checkFundDrift, reconcileGrid, optimizeRebalanceActions, projectTargetToWorkingGrid, buildStateUpdates, buildAbortedResult, buildSuccessResult, evaluateCommit } from './utils/validate.js';
33
- import { resolveSpreadOrderSide, parseSlotIndex, parseChainOrder, geometryTypeForSlotIndex, isOrderOnChain, resolveReserveCount, resolveLiveReserveEdgeAnchorPrice, compareReserveEdge, collectRefillSlotIds, recordOrderPlacement, isFreshlyPlacedOrder } from './utils/order.js';
33
+ import { resolveSpreadOrderSide, parseSlotIndex, parseChainOrder, geometryTypeForSlotIndex, isOrderOnChain, resolveEdgeCount, resolveLiveEdgeAnchorPrice, compareEdge, collectRefillSlotIds, recordOrderPlacement, isFreshlyPlacedOrder } from './utils/order.js';
34
34
  import { getErrorMessage, getErrorCode } from '../utils/errors.js';
35
35
  const { toFiniteNumber } = Format;
36
36
  function stalePlacementDropReason(action, planBoundary) {
@@ -99,7 +99,7 @@ class COWRebalanceEngine {
99
99
  this.assets = deps.assets;
100
100
  this.config = deps.config;
101
101
  }
102
- async execute({ masterGrid, gridVersion, boundaryIdx, funds, manager = null, fills = [], excludeIds = new Set(), gapSlots = null, evacStreaks = null, reserveEdgeAnchors = null }) {
102
+ async execute({ masterGrid, gridVersion, boundaryIdx, funds, manager = null, fills = [], excludeIds = new Set(), gapSlots = null, evacStreaks = null, edgeAnchors = null }) {
103
103
  const startTime = Date.now();
104
104
  const workingGrid = new WorkingGrid(masterGrid, { baseVersion: gridVersion });
105
105
  const strategyParams = {
@@ -219,6 +219,10 @@ class COWRebalanceEngine {
219
219
  // boundary-hold still judge the plan; no geometry is refused here.
220
220
  {
221
221
  const railSize = targetGrid?.size ?? 0;
222
+ // Null boundary is DELIBERATELY compared against numeric 0 here:
223
+ // the recovery plan's window is measured from rail start, and an
224
+ // off-rail truncation is exactly the telemetry this warn surfaces
225
+ // (see ANCHOR-007). It never gates the plan.
222
226
  const gap = Number(gapSlots) || 0;
223
227
  const sellStart = Number(targetBoundary) + gap + 1;
224
228
  if (Number.isFinite(sellStart) && railSize > 0 && sellStart >= railSize) {
@@ -230,13 +234,13 @@ class COWRebalanceEngine {
230
234
  // stamped UPDATEs above; stale-dropped placements are excluded — a
231
235
  // deferred placement justifies nothing). The executor holds the
232
236
  // committed boundary when a listed refill is guard-skipped.
233
- // Reserve-ladder CREATEs are excluded (collectRefillSlotIds): reserves
237
+ // Edge-ladder CREATEs are excluded (collectRefillSlotIds): edge orders
234
238
  // are static edge insurance and their fills never crawl, so a skipped
235
- // reserve must not pin geometry either.
239
+ // edge order must not pin geometry either.
236
240
  const refillSlotIds = collectRefillSlotIds(optimizedActions, {
237
241
  config: this.config,
238
242
  slots: masterGrid,
239
- edgeAnchors: reserveEdgeAnchors,
243
+ edgeAnchors: edgeAnchors,
240
244
  manager: this
241
245
  });
242
246
  projectTargetToWorkingGrid(workingGrid, targetGrid, { actions: optimizedActions });
@@ -322,10 +326,10 @@ class OrderManager {
322
326
  _accountingFailureSignal;
323
327
  _recoveryStateValue;
324
328
  _gridRegenStateValue;
325
- _ordersByTypeCache = null;
326
- _ordersByStateCache = null;
327
- _ordersByTypeCacheVersion = -1;
328
- _ordersByStateCacheVersion = -1;
329
+ _orderIdIndexes = {
330
+ type: { cache: null, version: -1 },
331
+ state: { cache: null, version: -1 },
332
+ };
329
333
  /**
330
334
  * Lazy-compute order-IDs grouped by type.
331
335
  *
@@ -340,48 +344,40 @@ class OrderManager {
340
344
  * next grid-version bump triggers a full rebuild from the real orders.
341
345
  */
342
346
  get _ordersByType() {
343
- if (this._ordersByTypeCache !== null && this._ordersByTypeCacheVersion === this._gridVersion) {
344
- return this._ordersByTypeCache;
345
- }
346
- const byType = {};
347
- for (const key of [ORDER_TYPES.BUY, ORDER_TYPES.SELL, ORDER_TYPES.SPREAD]) {
348
- byType[key] = new Set();
349
- }
350
- for (const [id, o] of this.orders) {
351
- if (byType[o.type])
352
- byType[o.type].add(id);
353
- }
354
- this._ordersByTypeCache = byType;
355
- this._ordersByTypeCacheVersion = this._gridVersion;
356
- return byType;
347
+ return this._getOrderIdIndex('type', [ORDER_TYPES.BUY, ORDER_TYPES.SELL, ORDER_TYPES.SPREAD]);
357
348
  }
358
349
  set _ordersByType(val) {
359
- this._ordersByTypeCache = val;
360
- this._ordersByTypeCacheVersion = this._gridVersion;
350
+ this._orderIdIndexes.type.cache = val;
351
+ this._orderIdIndexes.type.version = this._gridVersion;
361
352
  }
362
353
  /**
363
354
  * Lazy-compute order-IDs grouped by state. Same semantics as
364
355
  * _ordersByType — see getter doc for details.
365
356
  */
366
357
  get _ordersByState() {
367
- if (this._ordersByStateCache !== null && this._ordersByStateCacheVersion === this._gridVersion) {
368
- return this._ordersByStateCache;
369
- }
370
- const byState = {};
371
- for (const key of [ORDER_STATES.VIRTUAL, ORDER_STATES.ACTIVE, ORDER_STATES.PARTIAL]) {
372
- byState[key] = new Set();
373
- }
374
- for (const [id, o] of this.orders) {
375
- if (byState[o.state])
376
- byState[o.state].add(id);
377
- }
378
- this._ordersByStateCache = byState;
379
- this._ordersByStateCacheVersion = this._gridVersion;
380
- return byState;
358
+ return this._getOrderIdIndex('state', [ORDER_STATES.VIRTUAL, ORDER_STATES.ACTIVE, ORDER_STATES.PARTIAL]);
381
359
  }
382
360
  set _ordersByState(val) {
383
- this._ordersByStateCache = val;
384
- this._ordersByStateCacheVersion = this._gridVersion;
361
+ this._orderIdIndexes.state.cache = val;
362
+ this._orderIdIndexes.state.version = this._gridVersion;
363
+ }
364
+ /** Rebuild an order-id index for `field` over `keys`, memoized per `_gridVersion`. */
365
+ _getOrderIdIndex(field, keys) {
366
+ const slot = this._orderIdIndexes[field];
367
+ if (slot.cache !== null && slot.version === this._gridVersion) {
368
+ return slot.cache;
369
+ }
370
+ const index = {};
371
+ for (const key of keys)
372
+ index[key] = new Set();
373
+ for (const [id, o] of this.orders) {
374
+ const key = o[field];
375
+ if (index[key])
376
+ index[key].add(id);
377
+ }
378
+ slot.cache = index;
379
+ slot.version = this._gridVersion;
380
+ return index;
385
381
  }
386
382
  initialSpreadCount;
387
383
  currentSpreadCount;
@@ -438,10 +434,27 @@ class OrderManager {
438
434
  _lastFilledType;
439
435
  _lastFilledAt;
440
436
  lastFillPivotSource;
437
+ // Bot-scoped "last market fill" reference. Unlike the genesis-bound
438
+ // LAST-FILL-GUARD pivot (reset with the grid generation), this survives a
439
+ // grid regeneration/rejection and is used ONLY as a market anchor by
440
+ // spread correction (a real fill price must not be traded through).
441
+ // Written by setLastFillPivot on 'fill' provenance; restored at startup
442
+ // from the bot-scoped persisted row under a TTL.
443
+ _lastMarketFillPrice;
444
+ _lastMarketFillType;
445
+ _lastMarketFillAt;
446
+ // Externally-observed live market price (B/A), refreshed from the order
447
+ // book/ticker at a bounded cadence. The spread-correction crossing floor is
448
+ // the NEWER of this read and the fill anchor (an executed trade can be
449
+ // fresher market truth), so the floor tracks current market instead of a
450
+ // possibly days-old fill.
451
+ _liveMarketPrice;
452
+ _liveMarketPriceAt;
453
+ _liveMarketPriceAttemptedAt;
454
+ _lastSyncAt;
441
455
  _deferredRebalanceAt;
442
456
  _lastHeldPlanSignature;
443
457
  _heldPlanSuppressionCount;
444
- _onBroadcastRegionEnd;
445
458
  _onBroadcastRegionEndListeners;
446
459
  _lastBoundaryHoldResyncAt;
447
460
  _gapEvacStreaks;
@@ -572,6 +585,13 @@ class OrderManager {
572
585
  // 'fill' = armed by a real fill (persist-eligible), 'book' = armed by
573
586
  // the startup book seed (heuristic, in-memory only), null = unarmed.
574
587
  this.lastFillPivotSource = null;
588
+ this._lastMarketFillPrice = null;
589
+ this._lastMarketFillType = null;
590
+ this._lastMarketFillAt = 0;
591
+ this._liveMarketPrice = null;
592
+ this._liveMarketPriceAt = 0;
593
+ this._liveMarketPriceAttemptedAt = 0;
594
+ this._lastSyncAt = 0;
575
595
  this._deferredRebalanceAt = 0;
576
596
  this._lastHeldPlanSignature = null;
577
597
  this._heldPlanSuppressionCount = 0;
@@ -591,7 +611,12 @@ class OrderManager {
591
611
  gridLockContention: 0,
592
612
  spreadRoleConversionBlocked: 0,
593
613
  lastSyncDurationMs: 0,
594
- metricsStartTime: Date.now()
614
+ metricsStartTime: Date.now(),
615
+ refusedCommitCount: 0,
616
+ orphanFillCreditedCount: 0,
617
+ restampBuyAboveAnchorCount: 0,
618
+ boundaryDriftExceedsWindowCount: 0,
619
+ gapBandPlacementShadowCount: 0
595
620
  };
596
621
  this._bootstrapping = 1;
597
622
  this.logger?.log('[BOOTSTRAP] Started', 'debug');
@@ -804,19 +829,12 @@ class OrderManager {
804
829
  * without rescheduling, so this is the only wake-up for fills enqueued
805
830
  * during a region; the watchdog path must fire it too or a hung broadcast's
806
831
  * queued fills wait for the next fill event.
807
- * Fans out to the legacy single listener plus every registered listener
808
- * (see addBroadcastRegionEndListener): a second wirer must never silently
809
- * displace the fill-queue drain. Guarded so a listener error never escapes
810
- * into a finally/watchdog frame.
832
+ * Fans out to every listener registered via addBroadcastRegionEndListener:
833
+ * a second wirer must never silently displace the fill-queue drain.
834
+ * Guarded so a listener error never escapes into a finally/watchdog frame.
811
835
  * @returns {void}
812
836
  */
813
837
  _fireBroadcastRegionEnd() {
814
- try {
815
- (this._onBroadcastRegionEnd)?.();
816
- }
817
- catch (err) {
818
- this.logger?.log?.(`[BROADCAST] Region-end hook failed: ${getErrorMessage(err)}`, 'warn');
819
- }
820
838
  const listeners = this._onBroadcastRegionEndListeners;
821
839
  if (Array.isArray(listeners)) {
822
840
  for (const listener of listeners) {
@@ -830,9 +848,8 @@ class OrderManager {
830
848
  }
831
849
  }
832
850
  /**
833
- * Register an additional broadcast-region-end listener without displacing
834
- * the legacy single listener or previously registered ones. Duplicate
835
- * registrations of the same function reference are ignored.
851
+ * Register a broadcast-region-end listener. Duplicate registrations of the
852
+ * same function reference are ignored.
836
853
  * @param {() => void} listener
837
854
  * @returns {void}
838
855
  */
@@ -1547,9 +1564,9 @@ class OrderManager {
1547
1564
  * @returns {Array<import('./types').Order>}
1548
1565
  */
1549
1566
  getInitialOrdersToActivate() {
1550
- // Apply activeOrders limit from config
1551
- const sellCount = Math.max(0, toFiniteNumber(this.config.activeOrders?.sell, 1));
1552
- const buyCount = Math.max(0, toFiniteNumber(this.config.activeOrders?.buy, 1));
1567
+ // Apply coreOrders limit from config
1568
+ const sellCount = Math.max(0, toFiniteNumber(this.config.coreOrders?.sell, 1));
1569
+ const buyCount = Math.max(0, toFiniteNumber(this.config.coreOrders?.buy, 1));
1553
1570
  // Get minimum sizes for validation
1554
1571
  const minOrderSizeFactor = this.config?.gridLimits?.MIN_ORDER_SIZE_FACTOR;
1555
1572
  const minSellSize = getMinOrderSize(ORDER_TYPES.SELL, this.assets, minOrderSizeFactor);
@@ -1560,7 +1577,7 @@ class OrderManager {
1560
1577
  const minSellSizeInt = floatToBlockchainInt(minSellSize, sellPrecision);
1561
1578
  const minBuySizeInt = floatToBlockchainInt(minBuySize, buyPrecision);
1562
1579
  // Rail membership by geometry (shared isSlotInRail), mirroring the
1563
- // reconcile pickers (_pickVirtualSlotsToActivate / _pickEdgeReserveSlots).
1580
+ // reconcile pickers (_pickVirtualSlotsToActivate / _pickEdgeSlots).
1564
1581
  // A freshly generated grid's roles never need this, but the gate keeps
1565
1582
  // the startup placement path and the runtime activation path from
1566
1583
  // diverging: a slot whose stored type is stale relative to the current
@@ -1601,21 +1618,21 @@ class OrderManager {
1601
1618
  }
1602
1619
  // Reverse for placement order (lowest first)
1603
1620
  validBuys.sort((a, b) => a.price - b.price);
1604
- // Reserve ladder: edge-pinned orders activate alongside the window
1621
+ // Edge ladder: edge-pinned orders activate alongside the window
1605
1622
  // without consuming its budget. Buys pin at the floor (lowest first),
1606
1623
  // sells at the ceiling (highest first). Same min-size gate as the window.
1607
- const pickEdgeReserves = (orderType, count, windowed, precision, minSizeInt, ascending) => {
1624
+ const pickEdgeSlots = (orderType, count, windowed, precision, minSizeInt, ascending) => {
1608
1625
  const picked = [];
1609
1626
  if (count <= 0)
1610
1627
  return picked;
1611
1628
  const windowedIds = new Set(windowed.map((o) => o.id));
1612
1629
  // Both edges anchor at the live grid's own edge (ladder/rail extreme).
1613
- const edgeAnchor = resolveLiveReserveEdgeAnchorPrice(this, ascending ? 'buy' : 'sell');
1630
+ const edgeAnchor = resolveLiveEdgeAnchorPrice(this, ascending ? 'buy' : 'sell');
1614
1631
  const edge = ascending ? 'floor' : 'ceiling';
1615
1632
  const edgeFirst = this.getOrdersByTypeAndState(orderType, ORDER_STATES.VIRTUAL)
1616
1633
  .filter((o) => inRailFor(orderType, o))
1617
1634
  .filter((o) => parseSlotIndex(o.id) !== null)
1618
- .sort((a, b) => compareReserveEdge(a, b, edge, edgeAnchor));
1635
+ .sort((a, b) => compareEdge(a, b, edge, edgeAnchor));
1619
1636
  for (const o of edgeFirst) {
1620
1637
  if (picked.length >= count)
1621
1638
  break;
@@ -1629,9 +1646,9 @@ class OrderManager {
1629
1646
  picked.sort((a, b) => ascending ? a.price - b.price : b.price - a.price);
1630
1647
  return picked;
1631
1648
  };
1632
- const reserveBuys = pickEdgeReserves(ORDER_TYPES.BUY, resolveReserveCount(this.config, 'buy'), validBuys, buyPrecision, minBuySizeInt, true);
1633
- const reserveSells = pickEdgeReserves(ORDER_TYPES.SELL, resolveReserveCount(this.config, 'sell'), validSells, sellPrecision, minSellSizeInt, false);
1634
- return [...validSells, ...reserveSells, ...validBuys, ...reserveBuys];
1649
+ const edgeBuys = pickEdgeSlots(ORDER_TYPES.BUY, resolveEdgeCount(this.config, 'buy'), validBuys, buyPrecision, minBuySizeInt, true);
1650
+ const edgeSells = pickEdgeSlots(ORDER_TYPES.SELL, resolveEdgeCount(this.config, 'sell'), validSells, sellPrecision, minSellSizeInt, false);
1651
+ return [...validSells, ...edgeSells, ...validBuys, ...edgeBuys];
1635
1652
  }
1636
1653
  /**
1637
1654
  * Get orders matching the specified type and state.
@@ -2260,12 +2277,12 @@ class OrderManager {
2260
2277
  this._gapEvacStreaks = new Map();
2261
2278
  if (!(this._gapEvacCancelQueued instanceof Set))
2262
2279
  this._gapEvacCancelQueued = new Set();
2263
- // Live reserve edge anchors, resolved once and shared with the engine's
2264
- // refill wire so a reserve-ladder CREATE can never be classified as a
2265
- // hole refill (which would let a skipped reserve pin the boundary).
2266
- const reserveEdgeAnchors = {
2267
- buy: resolveLiveReserveEdgeAnchorPrice(this, 'buy'),
2268
- sell: resolveLiveReserveEdgeAnchorPrice(this, 'sell')
2280
+ // Live edge order anchors, resolved once and shared with the engine's
2281
+ // refill wire so an edge-ladder CREATE can never be classified as a
2282
+ // hole refill (which would let a skipped edge order pin the boundary).
2283
+ const edgeAnchors = {
2284
+ buy: resolveLiveEdgeAnchorPrice(this, 'buy'),
2285
+ sell: resolveLiveEdgeAnchorPrice(this, 'sell')
2269
2286
  };
2270
2287
  const result = await cowEngine.execute({
2271
2288
  masterGrid: this.orders,
@@ -2277,7 +2294,7 @@ class OrderManager {
2277
2294
  excludeIds,
2278
2295
  gapSlots: this._gapSlots,
2279
2296
  evacStreaks: this._gapEvacStreaks,
2280
- reserveEdgeAnchors
2297
+ edgeAnchors
2281
2298
  });
2282
2299
  // Phase 3 safety net: act on stuck in-band orders regardless of the
2283
2300
  // plan outcome — a plan that aborted for unrelated reasons must not
@@ -110,7 +110,7 @@ declare class StrategyEngine {
110
110
  * 1. Derive new boundary index based on fills (boundary crawl)
111
111
  * 2. Assign grid roles (BUY/SELL/SPREAD) based on boundary position
112
112
  * 3. Calculate budget allocation for each side
113
- * 4. Apply window discipline (activeOrders count limits)
113
+ * 4. Apply window discipline (coreOrders count limits)
114
114
  * 5. Calculate ideal order sizes based on budgets and weights
115
115
  * 6. Build target grid map representing desired state
116
116
  *
@@ -129,7 +129,7 @@ declare class StrategyEngine {
129
129
  * @param {Object} params.config - Bot configuration
130
130
  * - targetSpreadPercent {number}: Width of spread zone
131
131
  * - incrementPercent {number}: Price step between orders
132
- * - activeOrders {Object}: Target active order counts
132
+ * - coreOrders {Object}: Target active order counts
133
133
  * - weightDistribution {Object}: Size weighting for each side
134
134
  * @param {Object} params.accountAssets - Asset metadata (precision, IDs)
135
135
  * @param {Object} params.funds - Current fund state
@@ -49,7 +49,7 @@
49
49
  import { ORDER_TYPES, ORDER_STATES } from '../constants.js';
50
50
  import { calculateGapSlots } from './grid.js';
51
51
  import { isSlotInRail } from './utils/math.js';
52
- import { deriveTargetBoundary, getSideBudget, calculateBudgetedSizes, getActiveOrdersTotal, resolveReserveCount, resolveLiveReserveEdgeAnchorPrice, selectReserveEdgeSlots, isShiftEligibleFill } from './utils/order.js';
52
+ import { deriveTargetBoundary, getSideBudget, calculateBudgetedSizes, getCoreOrdersTotal, resolveEdgeCount, resolveLiveEdgeAnchorPrice, selectEdgeSlots, isShiftEligibleFill } from './utils/order.js';
53
53
  import { assignGridRoles } from './utils/order.js';
54
54
  import { convertToSpreadPlaceholder, toRailHolePlaceholder, geometryTypeForSlotIndex, parseSlotIndex, hasOnChainId, isOrderPlaced } from "./utils/order.js";
55
55
  class StrategyEngine {
@@ -188,7 +188,7 @@ class StrategyEngine {
188
188
  * 1. Derive new boundary index based on fills (boundary crawl)
189
189
  * 2. Assign grid roles (BUY/SELL/SPREAD) based on boundary position
190
190
  * 3. Calculate budget allocation for each side
191
- * 4. Apply window discipline (activeOrders count limits)
191
+ * 4. Apply window discipline (coreOrders count limits)
192
192
  * 5. Calculate ideal order sizes based on budgets and weights
193
193
  * 6. Build target grid map representing desired state
194
194
  *
@@ -207,7 +207,7 @@ class StrategyEngine {
207
207
  * @param {Object} params.config - Bot configuration
208
208
  * - targetSpreadPercent {number}: Width of spread zone
209
209
  * - incrementPercent {number}: Price step between orders
210
- * - activeOrders {Object}: Target active order counts
210
+ * - coreOrders {Object}: Target active order counts
211
211
  * - weightDistribution {Object}: Size weighting for each side
212
212
  * @param {Object} params.accountAssets - Asset metadata (precision, IDs)
213
213
  * @param {Object} params.funds - Current fund state
@@ -250,16 +250,16 @@ class StrategyEngine {
250
250
  const boundaryConfig = (!Number.isFinite(Number(config?.startPrice)) && Number.isFinite(genesisStart))
251
251
  ? { ...config, genesisStartPrice: genesisStart }
252
252
  : config;
253
- // Live reserve edge anchors (single source): the ladder extremes of the
254
- // grid actually being traded. Resolved once and shared by the reserve
253
+ // Live edge order anchors (single source): the ladder extremes of the
254
+ // grid actually being traded. Resolved once and shared by the edge
255
255
  // selection below and the no-crawl classification inside
256
256
  // deriveTargetBoundary, so placement and fill classification can never
257
- // disagree about which slots are reserves.
258
- const reserveEdgeAnchors = {
259
- buy: resolveLiveReserveEdgeAnchorPrice(this.manager, 'buy'),
260
- sell: resolveLiveReserveEdgeAnchorPrice(this.manager, 'sell'),
257
+ // disagree about which slots are edge orders.
258
+ const edgeAnchors = {
259
+ buy: resolveLiveEdgeAnchorPrice(this.manager, 'buy'),
260
+ sell: resolveLiveEdgeAnchorPrice(this.manager, 'sell'),
261
261
  };
262
- const { boundaryIdx: newBoundaryIdx, remainingBudget } = deriveTargetBoundary(fills, currentBoundaryIdx, allSlots, boundaryConfig, gapSlots, crossChunkBudget, this.manager._pendingFillCrawls, reserveEdgeAnchors);
262
+ const { boundaryIdx: newBoundaryIdx, remainingBudget } = deriveTargetBoundary(fills, currentBoundaryIdx, allSlots, boundaryConfig, gapSlots, crossChunkBudget, this.manager._pendingFillCrawls, edgeAnchors);
263
263
  if (crossChunkBudget != null) {
264
264
  this.manager._boundaryShiftBudget = remainingBudget;
265
265
  }
@@ -270,20 +270,50 @@ class StrategyEngine {
270
270
  this.manager.logger.log('[COW] calculateTargetGrid: boundary unrecoverable (no numeric center); skipping rotation plan', 'warn');
271
271
  return { targetGrid: new Map(), boundaryIdx: null };
272
272
  }
273
+ // P2 observability: a market/fill-derived boundary that jumps more than
274
+ // the active window in ONE plan is the "boundary detached from the
275
+ // market anchor" signal (the ANCHOR-DIVERGENCE condition, which lost its
276
+ // telemetry when the price projection was removed). A normal crawl is
277
+ // budget-bounded to at most half the active window, so this can only fire
278
+ // on an absolute recovery anchor or a geometry fault. Counted and
279
+ // rate-limited; never gates the plan.
280
+ try {
281
+ const activeWindow = Math.max(1, Number(config?.coreOrders?.buy) || 1, Number(config?.coreOrders?.sell) || 1);
282
+ // Null boundary is DELIBERATELY compared against numeric 0 here:
283
+ // the derived boundary is an absolute recovery anchor, and its
284
+ // distance from 0 is exactly the ANCHOR-DIVERGENCE signal this
285
+ // observability counter exists to surface (see P2 test).
286
+ const driftSlots = Math.abs(Number(newBoundaryIdx) - Number(currentBoundaryIdx));
287
+ if (Number.isFinite(driftSlots) && driftSlots > activeWindow) {
288
+ const metrics = this.manager._metrics;
289
+ if (metrics) {
290
+ metrics.boundaryDriftExceedsWindowCount = (metrics.boundaryDriftExceedsWindowCount || 0) + 1;
291
+ }
292
+ const now = Date.now();
293
+ const lastWarn = Number(this.manager._lastBoundaryDriftWarnAt) || 0;
294
+ if (now - lastWarn >= 5 * 60 * 1000) {
295
+ this.manager._lastBoundaryDriftWarnAt = now;
296
+ this.manager.logger.log(`[BOUNDARY-DRIFT] committed boundary ${currentBoundaryIdx} -> planned ${newBoundaryIdx} ` +
297
+ `(drift ${driftSlots} slots) exceeds active window ${activeWindow}; ` +
298
+ `boundary is detached from the market anchor (observability only)`, 'warn');
299
+ }
300
+ }
301
+ }
302
+ catch { /* observability only */ }
273
303
  // 2. Assign Roles (Buy/Sell/Spread)
274
304
  const updatedSlots = assignGridRoles(allSlots, newBoundaryIdx, gapSlots, ORDER_TYPES, ORDER_STATES, { assignOnChain: true });
275
305
  this.manager.logger.log(`[DEBUG] calculateTargetGrid: boundary=${newBoundaryIdx}, gap=${gapSlots}, allSlots=${updatedSlots.length}`, 'debug');
276
306
  updatedSlots.forEach((s) => this.manager.logger.log(` Slot ${s.id}: price=${s.price}, size=${s.size ?? 'n/a'}, type=${s.type}`, 'debug'));
277
307
  // 3. Calculate Ideal Sizes (Budgeting)
278
- const totalTarget = getActiveOrdersTotal(config);
308
+ const totalTarget = getCoreOrdersTotal(config);
279
309
  const budgetBuy = getSideBudget('buy', funds, config, totalTarget);
280
310
  const budgetSell = getSideBudget('sell', funds, config, totalTarget);
281
311
  // Filter slots into BUY/SELL
282
312
  const allBuySlots = updatedSlots.filter((o) => o.type === ORDER_TYPES.BUY);
283
313
  const allSellSlots = updatedSlots.filter((o) => o.type === ORDER_TYPES.SELL);
284
- // Apply Window Discipline (activeOrders count)
285
- const targetCountBuy = Math.max(1, (config.activeOrders?.buy ?? 1));
286
- const targetCountSell = Math.max(1, (config.activeOrders?.sell ?? 1));
314
+ // Apply Window Discipline (coreOrders count)
315
+ const targetCountBuy = Math.max(1, (config.coreOrders?.buy ?? 1));
316
+ const targetCountSell = Math.max(1, (config.coreOrders?.sell ?? 1));
287
317
  // The SPREAD GUARD (assignGridRoles) keeps a live on-chain order typed
288
318
  // BUY/SELL even when a boundary crawl moves its slot into the spread
289
319
  // band (to avoid the illegal SPREAD+ACTIVE state). Such a stray slot
@@ -330,17 +360,17 @@ class StrategyEngine {
330
360
  const fullSellSizes = calculateBudgetedSizes(allSellSortedForSizing, 'sell', budgetSell, config.weightDistribution?.sell, config.incrementPercent, accountAssets);
331
361
  const buySizeById = new Map(allBuySortedForSizing.map((slot, i) => [slot.id, fullBuySizes[i] || 0]));
332
362
  const sellSizeById = new Map(allSellSortedForSizing.map((slot, i) => [slot.id, fullSellSizes[i] || 0]));
333
- // Reserve ladder: edge-pinned insurance orders stay live alongside the
363
+ // Edge ladder: edge-pinned insurance orders stay live alongside the
334
364
  // window. Buys pin at the floor (lowest prices), sells at the ceiling
335
365
  // (highest prices). Discontiguous by design — the middle stays VIRTUAL.
336
- // Sizes come from the same full-rail curves; reserve fills never crawl
366
+ // Sizes come from the same full-rail curves; edge fills never crawl
337
367
  // (filtered in deriveTargetBoundary).
338
- // Both edges anchor at the live grid's own edge (reserveEdgeAnchors),
368
+ // Both edges anchor at the live grid's own edge (edgeAnchors),
339
369
  // which is the same pair deriveTargetBoundary classified against.
340
- const reserveBuySlots = selectReserveEdgeSlots(allBuySortedForSizing.filter((s) => inBuyRail(s)), resolveReserveCount(config, 'buy'), new Set(buySlots.map((s) => s.id)), 'floor', reserveEdgeAnchors.buy);
341
- const reserveSellSlots = selectReserveEdgeSlots(allSellSortedForSizing.filter((s) => inSellRail(s)), resolveReserveCount(config, 'sell'), new Set(sellSlots.map((s) => s.id)), 'ceiling', reserveEdgeAnchors.sell);
342
- const buySlotsAll = [...buySlots, ...reserveBuySlots];
343
- const sellSlotsAll = [...sellSlots, ...reserveSellSlots];
370
+ const edgeBuySlots = selectEdgeSlots(allBuySortedForSizing.filter((s) => inBuyRail(s)), resolveEdgeCount(config, 'buy'), new Set(buySlots.map((s) => s.id)), 'floor', edgeAnchors.buy);
371
+ const edgeSellSlots = selectEdgeSlots(allSellSortedForSizing.filter((s) => inSellRail(s)), resolveEdgeCount(config, 'sell'), new Set(sellSlots.map((s) => s.id)), 'ceiling', edgeAnchors.sell);
372
+ const buySlotsAll = [...buySlots, ...edgeBuySlots];
373
+ const sellSlotsAll = [...sellSlots, ...edgeSellSlots];
344
374
  const buySizes = buySlotsAll.map((slot) => buySizeById.get(slot.id) || 0);
345
375
  const sellSizes = sellSlotsAll.map((slot) => sellSizeById.get(slot.id) || 0);
346
376
  // Apply sizes to target grid map
@@ -651,6 +651,10 @@ class SyncEngine {
651
651
  ? (innerResult.unmatchedChainOrders ?? []).map((order) => ({ ...order }))
652
652
  : [];
653
653
  mgr._lastUnmatchedChainOrdersAt = unmatchedCount > 0 ? Date.now() : 0;
654
+ // Freshness stamp for the spread-correction bypass gate:
655
+ // only a completed open-orders sync makes the local anchor
656
+ // trustworthy enough to bypass the LAST-FILL-GUARD.
657
+ mgr._lastSyncAt = Date.now();
654
658
  mgr.logger?.log?.(`[SYNC] Synchronization complete: ${innerResult.filledOrders.length} filled, ` +
655
659
  `${innerResult.updatedOrders.length} updated, ` +
656
660
  `${innerResult.ordersNeedingCorrection.length} needing correction.`, 'info');
@@ -71,7 +71,7 @@
71
71
  *
72
72
  * ===============================================================================
73
73
  */
74
- import type { OrderManagerLike, AccountTotals, ManagerFunds, ActiveOrdersConfig, GridFeeParams, ManagedOrder, AssetPair, GridConfig, GridLimitsLike, WeightDistributionConfig } from '../../types.js';
74
+ import type { OrderManagerLike, AccountTotals, ManagerFunds, CoreOrdersConfig, GridFeeParams, ManagedOrder, AssetPair, GridConfig, GridLimitsLike, WeightDistributionConfig } from '../../types.js';
75
75
  interface FeeCacheEntry {
76
76
  limitOrderCreate: {
77
77
  bts: number;
@@ -413,10 +413,10 @@ declare function getAssetFeesSafe(assetSymbol: string, assetAmount?: number | nu
413
413
  * @param {Object} funds - Fund allocation object with virtual, btsFeesOwed properties
414
414
  * @param {string} assetA - First asset symbol
415
415
  * @param {string} assetB - Second asset symbol
416
- * @param {Object} [activeOrders=null] - Active order counts {buy, sell} for BTS reservation calculation
416
+ * @param {Object} [coreOrders=null] - Active order counts {buy, sell} for BTS reservation calculation
417
417
  * @returns {number} Available funds for the side (0 if side invalid or insufficient funds)
418
418
  */
419
- declare function calculateAvailableFundsValue(side: string, accountTotals: AccountTotals | null | undefined, funds: ManagerFunds, assetA: string | undefined, assetB: string | undefined, activeOrders?: ActiveOrdersConfig | null, configMinBtsValue?: number | null, feeParams?: GridFeeParams | null): number;
419
+ declare function calculateAvailableFundsValue(side: string, accountTotals: AccountTotals | null | undefined, funds: ManagerFunds, assetA: string | undefined, assetB: string | undefined, coreOrders?: CoreOrdersConfig | null, configMinBtsValue?: number | null, feeParams?: GridFeeParams | null): number;
420
420
  /**
421
421
  * Adjust an allocated budget for BTS fee reservation.
422
422
  * Uses computeBtsFeeImpact for proportional deduction; falls back to 0.5
@@ -429,10 +429,10 @@ function getAssetFeesSafe(assetSymbol, assetAmount = null, isMaker = true) {
429
429
  * @param {Object} funds - Fund allocation object with virtual, btsFeesOwed properties
430
430
  * @param {string} assetA - First asset symbol
431
431
  * @param {string} assetB - Second asset symbol
432
- * @param {Object} [activeOrders=null] - Active order counts {buy, sell} for BTS reservation calculation
432
+ * @param {Object} [coreOrders=null] - Active order counts {buy, sell} for BTS reservation calculation
433
433
  * @returns {number} Available funds for the side (0 if side invalid or insufficient funds)
434
434
  */
435
- function calculateAvailableFundsValue(side, accountTotals, funds, assetA, assetB, activeOrders = null, configMinBtsValue = null, feeParams = null) {
435
+ function calculateAvailableFundsValue(side, accountTotals, funds, assetA, assetB, coreOrders = null, configMinBtsValue = null, feeParams = null) {
436
436
  if (side !== 'buy' && side !== 'sell')
437
437
  return 0;
438
438
  const chainFree = toFiniteNumber(side === 'buy' ? accountTotals?.buyFree : accountTotals?.sellFree);
@@ -441,17 +441,17 @@ function calculateAvailableFundsValue(side, accountTotals, funds, assetA, assetB
441
441
  const btsSide = getBtsSide(assetA, assetB);
442
442
  const btsReservationMultiplier = feeParams?.BTS_RESERVATION_MULTIPLIER ?? FEE_PARAMETERS.BTS_RESERVATION_MULTIPLIER;
443
443
  let btsFeesReservation = 0;
444
- if (btsSide === side && activeOrders) {
445
- const targetBuy = Math.max(0, toFiniteNumber(activeOrders?.buy, 1));
446
- const targetSell = Math.max(0, toFiniteNumber(activeOrders?.sell, 1));
444
+ if (btsSide === side && coreOrders) {
445
+ const targetBuy = Math.max(0, toFiniteNumber(coreOrders?.buy, 1));
446
+ const targetSell = Math.max(0, toFiniteNumber(coreOrders?.sell, 1));
447
447
  const totalTargetOrders = targetBuy + targetSell;
448
448
  btsFeesReservation = calculateOrderCreationFees(assetA, assetB, totalTargetOrders, btsReservationMultiplier);
449
449
  }
450
450
  const currentFeesOwed = (btsSide === side) ? btsFeesOwed : 0;
451
451
  // Non-BTS pair: reserve proportional share for BTS fee budget
452
- if (!btsSide && activeOrders && funds?.btsBalance != null) {
453
- const targetBuy = Math.max(0, toFiniteNumber(activeOrders?.buy, 1));
454
- const targetSell = Math.max(0, toFiniteNumber(activeOrders?.sell, 1));
452
+ if (!btsSide && coreOrders && funds?.btsBalance != null) {
453
+ const targetBuy = Math.max(0, toFiniteNumber(coreOrders?.buy, 1));
454
+ const targetSell = Math.max(0, toFiniteNumber(coreOrders?.sell, 1));
455
455
  const totalTargetOrders = targetBuy + targetSell;
456
456
  const formulaBudget = calculateOrderCreationFees(assetA, assetB, totalTargetOrders, btsReservationMultiplier);
457
457
  const btsFree = toFiniteNumber(funds?.btsBalance?.free, 0);
@@ -1336,13 +1336,11 @@ function resolveGapSlots(manager) {
1336
1336
  */
1337
1337
  function resolveGapBand(manager) {
1338
1338
  const gapSlots = resolveGapSlots(manager);
1339
- // Explicit null/undefined guard: Number(null) === 0, which would silently
1340
- // treat "no boundary" as boundary 0 — a valid index that biases all slots
1341
- // to the SELL rail. Return null so callers can detect the unknown state.
1342
- if (manager.boundaryIdx == null) {
1343
- return { gapSlots, boundaryIdx: null, sellStartIdx: null };
1344
- }
1345
- const raw = Number(manager.boundaryIdx);
1339
+ // Absent-aware coercion: Number(null)/Number('') === 0 would silently treat
1340
+ // "no boundary" as boundary 0 — a valid index that biases all slots to the
1341
+ // SELL rail. toKnownNumber keeps null/undefined/'' as NaN so the unknown
1342
+ // state is detectable, while a genuine boundary 0 still returns 0.
1343
+ const raw = Format.toKnownNumber(manager.boundaryIdx);
1346
1344
  if (!Number.isFinite(raw)) {
1347
1345
  return { gapSlots, boundaryIdx: null, sellStartIdx: null };
1348
1346
  }
@@ -1401,7 +1399,15 @@ const BOUNDARY_REJECT_PLACED_IN_BAND = 'placed_order_in_band';
1401
1399
  * is a stable short code and `detail` carries indices/prices for logs.
1402
1400
  */
1403
1401
  function validateBoundaryCommit(proposedBoundary, orders, gapSlots, options = {}) {
1404
- if (proposedBoundary == null)
1402
+ // Absent-aware: null/undefined/'' means "no proposal" (ok), NOT boundary 0,
1403
+ // otherwise Number('') === 0 would self-legalize a fake boundary 0 commit.
1404
+ // Everything else non-numeric stays FAIL-CLOSED (corrupt/garbage, never
1405
+ // ok): this gate also backs validatePersistedBoundary — the disk-trust
1406
+ // boundary where a poison value must surface as a rejection (rebuild),
1407
+ // not silently pass as "no proposal". Callers pass number | null; the
1408
+ // '' branch only exists because '' would otherwise coerce to 0 via
1409
+ // Number() and read as a valid boundary index.
1410
+ if (proposedBoundary === '' || proposedBoundary == null)
1405
1411
  return { ok: true };
1406
1412
  const raw = Number(proposedBoundary);
1407
1413
  if (!Number.isFinite(raw) || !Number.isInteger(raw)) {
@@ -1605,17 +1611,25 @@ function countGapBandSpread(manager, orders, resolveIndex) {
1605
1611
  * sits provably outside the rail.
1606
1612
  */
1607
1613
  function isSlotInRail(boundaryIdx, gapSlots, orderType, slot) {
1608
- if (boundaryIdx == null || !Number.isFinite(Number(boundaryIdx)))
1614
+ // Absent-aware: ''/null/undefined is unknown geometry → fail open, never a
1615
+ // boundary of 0 (Number('') === 0 would otherwise exclude valid slots).
1616
+ const boundary = Format.toKnownNumber(boundaryIdx);
1617
+ if (!Number.isFinite(boundary))
1609
1618
  return true;
1610
1619
  const parsed = parseSlotIndex(slot?.id);
1611
1620
  if (parsed === null)
1612
1621
  return true;
1613
1622
  const idx = parsed;
1614
1623
  if (orderType === ORDER_TYPES.BUY)
1615
- return idx <= Number(boundaryIdx);
1624
+ return idx <= boundary;
1616
1625
  if (orderType !== ORDER_TYPES.SELL)
1617
1626
  return true;
1618
- const sellStartIdx = getSellStartIdx(boundaryIdx, gapSlots);
1627
+ // The SELL rail needs the gap width; unknown gap → cannot derive sellStart
1628
+ // → fail open (same contract as the unknown-boundary branch above).
1629
+ const gap = Format.toKnownNumber(gapSlots);
1630
+ if (!Number.isFinite(gap))
1631
+ return true;
1632
+ const sellStartIdx = getSellStartIdx(boundary, gap);
1619
1633
  if (!Number.isFinite(sellStartIdx))
1620
1634
  return true;
1621
1635
  return idx >= sellStartIdx;
@@ -1632,14 +1646,11 @@ function isSlotInRail(boundaryIdx, gapSlots, orderType, slot) {
1632
1646
  * @returns {boolean} True when the index is inside the gap band
1633
1647
  */
1634
1648
  function isSlotIndexInGapBand(idx, boundaryIdx, gapSlots) {
1635
- // Explicit null guard: Number(null) === 0 must never read as slot 0.
1636
- if (idx === null || idx === undefined || idx === '')
1637
- return false;
1638
- if (boundaryIdx === null || boundaryIdx === undefined || boundaryIdx === '')
1639
- return false;
1640
- const n = Number(idx);
1641
- const b = Number(boundaryIdx);
1642
- const g = Number(gapSlots);
1649
+ // Absent-aware: Number(null)/Number('') === 0 must never read as slot 0,
1650
+ // and an unknown gap width must not collapse the band (null → 0).
1651
+ const n = Format.toKnownNumber(idx);
1652
+ const b = Format.toKnownNumber(boundaryIdx);
1653
+ const g = Format.toKnownNumber(gapSlots);
1643
1654
  if (!Number.isFinite(n) || !Number.isFinite(b) || !Number.isFinite(g))
1644
1655
  return false;
1645
1656
  const sellStartIdx = getSellStartIdx(b, g);