dexbot 1.6.17 → 1.7.0

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 (156) hide show
  1. package/CHANGELOG.md +58 -0
  2. package/README.md +24 -18
  3. package/analysis/README.md +105 -12
  4. package/analysis/ama_fitting/README.md +2 -2
  5. package/analysis/bot_fitting/README.md +3 -3
  6. package/claw/package.json +1 -1
  7. package/claw/runtimes/openclaw-plugin/openclaw.plugin.json +1 -1
  8. package/claw/runtimes/openclaw-plugin/package.json +1 -1
  9. package/dist/analysis/analyze_args.d.ts +2 -1
  10. package/dist/analysis/analyze_dynamic_weight.js +2 -1
  11. package/dist/analysis/analyze_kalman.js +3 -2
  12. package/dist/analysis/analyze_liquidity.d.ts +17 -0
  13. package/dist/analysis/analyze_liquidity.js +325 -0
  14. package/dist/analysis/analyze_regime.js +3 -2
  15. package/dist/analysis/analyze_regime_windows.js +3 -2
  16. package/dist/analysis/analyze_volatility.js +3 -2
  17. package/dist/analysis/fills_source.d.ts +1 -8
  18. package/dist/analysis/fills_source.js +1 -1
  19. package/dist/analysis/grid_correction_check.d.ts +9 -6
  20. package/dist/analysis/grid_correction_check.js +56 -64
  21. package/dist/analysis/liquidity/liquidity_chain.d.ts +66 -0
  22. package/dist/analysis/liquidity/liquidity_chain.js +178 -0
  23. package/dist/analysis/liquidity/liquidity_chart_generator.d.ts +19 -0
  24. package/dist/analysis/liquidity/liquidity_chart_generator.js +523 -0
  25. package/dist/analysis/liquidity/liquidity_depth_model.d.ts +141 -0
  26. package/dist/analysis/liquidity/liquidity_depth_model.js +230 -0
  27. package/dist/analysis/liquidity/liquidity_view.d.ts +38 -0
  28. package/dist/analysis/liquidity/liquidity_view.js +55 -0
  29. package/dist/analysis/math_utils.d.ts +1 -1
  30. package/dist/analysis/trade_profitability.d.ts +1 -1
  31. package/dist/analysis/trade_profitability.js +2 -1
  32. package/dist/analysis/tradingview/analyze_tradingview.js +2 -1
  33. package/dist/analysis/tradingview/tradingview_uplot_chart_generator.js +3 -3
  34. package/dist/analysis/trend_detection/huber_scale_variants.d.ts +4 -3
  35. package/dist/dexbot.js +74 -169
  36. package/dist/market_adapter/cli_args.d.ts +6 -1
  37. package/dist/market_adapter/cli_args.js +16 -2
  38. package/dist/market_adapter/core/kibana_candles.d.ts +5 -1
  39. package/dist/market_adapter/core/kibana_candles.js +3 -1
  40. package/dist/market_adapter/core/strategies/regime_gate.d.ts +7 -1
  41. package/dist/market_adapter/core/strategies/regime_gate.js +3 -1
  42. package/dist/market_adapter/inputs/cex_candle_parsing.d.ts +7 -2
  43. package/dist/market_adapter/inputs/cex_candle_parsing.js +3 -1
  44. package/dist/market_adapter/inputs/fetch_book_data.d.ts +7 -1
  45. package/dist/market_adapter/inputs/fetch_book_data.js +3 -1
  46. package/dist/market_adapter/inputs/fetch_cex_synthetic_data.js +2 -11
  47. package/dist/market_adapter/inputs/fetch_lp_data.d.ts +26 -1
  48. package/dist/market_adapter/inputs/fetch_lp_data.js +62 -52
  49. package/dist/market_adapter/inputs/kibana_feed_source.d.ts +14 -2
  50. package/dist/market_adapter/inputs/kibana_feed_source.js +14 -1
  51. package/dist/market_adapter/inputs/window_cache.d.ts +14 -3
  52. package/dist/market_adapter/inputs/window_cache.js +14 -1
  53. package/dist/market_adapter/lp_chart_runner.d.ts +12 -9
  54. package/dist/market_adapter/lp_chart_runner.js +3 -1
  55. package/dist/market_adapter/lp_chart_strategy_loader.d.ts +5 -1
  56. package/dist/market_adapter/lp_chart_strategy_loader.js +3 -1
  57. package/dist/market_adapter/market_adapter.d.ts +10 -2
  58. package/dist/market_adapter/market_adapter.js +10 -11
  59. package/dist/market_adapter/utils/chain.d.ts +2 -3
  60. package/dist/market_adapter/utils/file_json_cache.d.ts +5 -1
  61. package/dist/market_adapter/utils/file_json_cache.js +3 -1
  62. package/dist/market_adapter/utils/file_lock.js +1 -1
  63. package/dist/market_adapter/utils/native_history.d.ts +7 -3
  64. package/dist/market_adapter/utils/native_history.js +3 -1
  65. package/dist/market_adapter/utils/pair_orientation.d.ts +2 -2
  66. package/dist/modules/asset_lookup.d.ts +25 -0
  67. package/dist/modules/asset_lookup.js +75 -0
  68. package/dist/modules/bots_file_lock.d.ts +2 -2
  69. package/dist/modules/bots_file_lock.js +2 -2
  70. package/dist/modules/chain_scan.d.ts +64 -0
  71. package/dist/modules/chain_scan.js +80 -0
  72. package/dist/modules/cli_colors.d.ts +5 -0
  73. package/dist/modules/cli_colors.js +7 -0
  74. package/dist/modules/cli_progress.d.ts +51 -0
  75. package/dist/modules/cli_progress.js +113 -0
  76. package/dist/modules/constants.js +6 -3
  77. package/dist/modules/dexbot_class.d.ts +8 -0
  78. package/dist/modules/dexbot_class.js +10 -0
  79. package/dist/modules/dexbot_cow_runtime.d.ts +62 -1
  80. package/dist/modules/dexbot_cow_runtime.js +475 -47
  81. package/dist/modules/dexbot_credential_client.d.ts +5 -0
  82. package/dist/modules/dexbot_fill_runtime.js +20 -0
  83. package/dist/modules/dexbot_maintenance_runtime.js +71 -9
  84. package/dist/modules/dexbot_startup_runtime.js +7 -1
  85. package/dist/modules/graceful_shutdown.d.ts +2 -2
  86. package/dist/modules/graceful_shutdown.js +2 -2
  87. package/dist/modules/launcher/runtime_entry.d.ts +21 -1
  88. package/dist/modules/launcher/runtime_entry.js +36 -1
  89. package/dist/modules/launcher/runtime_mode.d.ts +4 -3
  90. package/dist/modules/liquidity_pool_ref.d.ts +32 -0
  91. package/dist/modules/liquidity_pool_ref.js +116 -0
  92. package/dist/modules/node_manager.d.ts +1 -1
  93. package/dist/modules/node_manager.js +1 -1
  94. package/dist/modules/order/accounting.js +2 -1
  95. package/dist/modules/order/export.d.ts +2 -2
  96. package/dist/modules/order/export.js +2 -2
  97. package/dist/modules/order/grid.d.ts +19 -14
  98. package/dist/modules/order/grid.js +269 -61
  99. package/dist/modules/order/grid_reconcile.js +27 -2
  100. package/dist/modules/order/grid_reconcile_internal.js +94 -15
  101. package/dist/modules/order/index.d.ts +24 -4
  102. package/dist/modules/order/manager.d.ts +12 -0
  103. package/dist/modules/order/manager.js +44 -11
  104. package/dist/modules/order/strategy.js +22 -2
  105. package/dist/modules/order/sync_engine.d.ts +32 -1
  106. package/dist/modules/order/sync_engine.js +209 -26
  107. package/dist/modules/order/utils/math.d.ts +26 -10
  108. package/dist/modules/order/utils/math.js +54 -14
  109. package/dist/modules/order/utils/order.d.ts +158 -11
  110. package/dist/modules/order/utils/order.js +434 -21
  111. package/dist/modules/order/utils/system.d.ts +136 -30
  112. package/dist/modules/order/utils/system.js +465 -63
  113. package/dist/modules/order/utils/validate.d.ts +1 -0
  114. package/dist/modules/order/utils/validate.js +37 -3
  115. package/dist/modules/storage/index.d.ts +3 -2
  116. package/dist/modules/storage/index.js +3 -2
  117. package/dist/modules/types.d.ts +14 -0
  118. package/dist/modules/utils/asset_symbols.d.ts +13 -2
  119. package/dist/modules/utils/asset_symbols.js +21 -2
  120. package/dist/scripts/analysis_runner.d.ts +10 -0
  121. package/dist/scripts/analysis_runner.js +33 -0
  122. package/dist/scripts/analyze-orders.js +2 -1
  123. package/dist/scripts/asset.d.ts +26 -0
  124. package/dist/scripts/asset.js +165 -0
  125. package/dist/scripts/bts_distribution.d.ts +1 -0
  126. package/dist/scripts/bts_distribution.js +194 -142
  127. package/dist/scripts/chart_command.d.ts +1 -1
  128. package/dist/scripts/chart_command.js +60 -86
  129. package/dist/scripts/chart_targets.d.ts +18 -0
  130. package/dist/scripts/chart_targets.js +52 -0
  131. package/dist/scripts/dw.js +1 -1
  132. package/dist/scripts/liquid.d.ts +24 -0
  133. package/dist/scripts/liquid.js +134 -0
  134. package/dist/scripts/rich_list.js +12 -16
  135. package/dist/scripts/token_distribution.d.ts +2 -0
  136. package/dist/scripts/token_distribution.js +132 -108
  137. package/dist/scripts/tv.js +1 -1
  138. package/dist/scripts/verify-browser-bundle.js +18 -0
  139. package/docs/COPY_ON_WRITE_MASTER_PLAN.md +1 -1
  140. package/docs/COW_INVARIANTS.md +21 -11
  141. package/docs/DEXBOT_COMPARISON.md +6 -6
  142. package/docs/EVOLUTION.md +10 -8
  143. package/docs/FUND_MOVEMENT_AND_ACCOUNTING.md +11 -11
  144. package/docs/GRID_PRICE_INVARIANT.md +28 -5
  145. package/docs/GRID_RECONCILE.md +25 -5
  146. package/docs/LIFECYCLE.md +11 -11
  147. package/docs/LOGGING.md +37 -2
  148. package/docs/ORDER_ENGINE_POST_1.0_RETROSPECTIVE.md +124 -36
  149. package/docs/README.md +1 -1
  150. package/docs/WORKFLOW.md +3 -1
  151. package/docs/architecture.md +115 -13
  152. package/docs/developer_guide.md +12 -0
  153. package/market_adapter/README.md +9 -4
  154. package/modules/README.md +23 -15
  155. package/package.json +6 -3
  156. package/scripts/README.md +23 -7
@@ -139,7 +139,7 @@ const { BitShares } = client;
139
139
  import { NATIVE_CLIENT } from '../constants.js';
140
140
  const { toFiniteNumber } = Format;
141
141
  import { blockchainToFloat, floatToBlockchainInt, getAssetFees, getBtsSide, slotIndexForPrice, isChainPriceOutOfGrid, isSlotInRail, priceForSlot, priceSlotEqual, pricesOnSameLevel } from './utils/math.js';
142
- import { parseChainOrder, applyChainSizeToGridOrder, convertToSpreadPlaceholder, virtualizeOrder, buildFillKey, isOrderPlaced, hasOnChainId, isOrderVirtual, resolveSpreadOrderSide, duplicateOrphanLogInfo, _stampCorrectionProvenance, _filterUnmatchedChainOrders } from './utils/order.js';
142
+ import { parseChainOrder, geometryTypeForSlotIndex, applyChainSizeToGridOrder, convertToSpreadPlaceholder, virtualizeOrder, buildFillKey, isOrderPlaced, hasOnChainId, isOrderVirtual, resolveSpreadOrderSide, duplicateOrphanLogInfo, _stampCorrectionProvenance, _filterUnmatchedChainOrders, attributeUnmatchedFillToGrid, reviveVirtualSlotFromChain, resolveExecutionPrice } from './utils/order.js';
143
143
  import { parseSlotIndex } from './utils/slot.js';
144
144
  import { resolveProcessedFillPersistenceMode } from './processed_fill_store.js';
145
145
  import { hasGenesisLadder } from './genesis_policy.js';
@@ -468,7 +468,15 @@ async function adoptChainOrderIntoSlot(mgr, slot, chainOrder, chainOrderId, rawC
468
468
  matchedGridOrderIds.delete(bestMatch.id);
469
469
  return false;
470
470
  }
471
- filledOrders.push({ ...bestMatch });
471
+ filledOrders.push({
472
+ ...bestMatch,
473
+ // Pass-2 adoption of an already-gone order: the parsed chain
474
+ // price is the only trade fact available (bestMatch.price is
475
+ // the slot identity and may be stale).
476
+ ...(Number.isFinite(Number(chainOrder.price)) && Number(chainOrder.price) > 0
477
+ ? { price: Number(chainOrder.price) }
478
+ : {})
479
+ });
472
480
  updatedOrders.push(spreadOrder);
473
481
  chainOrderIdsOnGrid.add(chainOrderId);
474
482
  try {
@@ -964,6 +972,23 @@ class SyncEngine {
964
972
  continue;
965
973
  let updatedOrder = { ...gridOrder };
966
974
  chainOrderIdsOnGrid.add(gridOrder.orderId);
975
+ // REVIVE BEFORE ANYTHING ELSE: this slot is not placed but its
976
+ // chain order is still live. Leaving it VIRTUAL is the "dark
977
+ // level" state — invisible to window accounting
978
+ // (_countActiveOnGrid needs ACTIVE/PARTIAL) while its order is
979
+ // still counted in chainCount, so the reconcile reads a
980
+ // shortfall it can never repair and the planner sees a free
981
+ // level that already holds an order. The revive is master-only
982
+ // (no broadcast) and refuses when the chain order does not rest
983
+ // at this slot's level, so a rotation source whose cancel has
984
+ // not landed is NOT resurrected.
985
+ if (!isOrderPlaced(gridOrder)) {
986
+ const revived = await reviveVirtualSlotFromChain(mgr, gridOrder, chainOrder, rawChainOrders.get(gridOrder.orderId), 'sync-pass1-revive', { skipAccounting });
987
+ if (revived) {
988
+ updatedOrders.push(revived);
989
+ continue;
990
+ }
991
+ }
967
992
  // Store raw blockchain data in grid slot for later update calculation.
968
993
  // Tag the snapshot with `fetchedAt` so the drift check in
969
994
  // syncFromFillHistory can distinguish a fresh chain read from a
@@ -999,14 +1024,62 @@ class SyncEngine {
999
1024
  const precision = gridOrder.type === ORDER_TYPES.SELL ? assetAPrecision : assetBPrecision;
1000
1025
  const isPriceEqual = chainPriceOnSameLevel(chainOrder.price, gridOrder.price, mgr._genesis, precision, mgr.assets, toFiniteNumber(chainOrder.size), gridOrder.size, gridOrder.type, mgr.config?.incrementPercent);
1001
1026
  if (!isPriceEqual) {
1002
- queueCorrection({
1003
- gridOrder: { ...gridOrder },
1004
- chainOrderId: gridOrder.orderId,
1005
- expectedPrice: gridOrder.price,
1006
- actualPrice: chainOrder.price,
1007
- size: chainOrder.size,
1008
- type: gridOrder.type
1009
- });
1027
+ // GAP-EVACUATION PRECEDENCE: classify the order's REAL
1028
+ // chain price against the live band before queueing a
1029
+ // plain price correction. An order whose live price maps
1030
+ // inside the gap band must be cancelled, not "corrected"
1031
+ // back to a stale slot price (the correction would leave
1032
+ // it resting inside the spread). A refused-commit
1033
+ // adoption can leave the local slot id in-rail while the
1034
+ // order actually trades in-band.
1035
+ let inBand = false;
1036
+ try {
1037
+ if (Array.isArray(mgr._genesis?.priceLevels) && mgr._genesis.priceLevels.length > 0) {
1038
+ const liveIdx = Number(slotIndexForPrice(chainOrder.price, mgr._genesis));
1039
+ inBand = Number.isFinite(liveIdx) && liveIdx >= 0
1040
+ && geometryTypeForSlotIndex(liveIdx, mgr.boundaryIdx, mgr._gapSlots) === ORDER_TYPES.SPREAD;
1041
+ }
1042
+ }
1043
+ catch {
1044
+ inBand = false;
1045
+ }
1046
+ if (inBand) {
1047
+ // Drop an opposite-kind queued entry for the same
1048
+ // chain order so the cancel and a price update cannot
1049
+ // both drain.
1050
+ if (Array.isArray(mgr.ordersNeedingPriceCorrection)) {
1051
+ for (let i = mgr.ordersNeedingPriceCorrection.length - 1; i >= 0; i--) {
1052
+ const queued = mgr.ordersNeedingPriceCorrection[i];
1053
+ if (queued?.chainOrderId === gridOrder.orderId && queued.isSurplus !== true) {
1054
+ mgr.ordersNeedingPriceCorrection.splice(i, 1);
1055
+ }
1056
+ }
1057
+ }
1058
+ queueCorrection({
1059
+ gridOrder: { ...gridOrder },
1060
+ chainOrderId: gridOrder.orderId,
1061
+ expectedPrice: gridOrder.price,
1062
+ actualPrice: chainOrder.price,
1063
+ size: chainOrder.size,
1064
+ type: chainOrder.type,
1065
+ isSurplus: true,
1066
+ gapEvacuation: true,
1067
+ boundaryIdx: mgr.boundaryIdx
1068
+ });
1069
+ mgr.logger?.log?.(`[SYNC] Gap-evacuation queued for ${gridOrder.orderId} (slot ${gridOrder.id}): ` +
1070
+ `live price ${Format.formatPrice6(Number(chainOrder.price))} maps inside the gap band ` +
1071
+ `(boundary ${mgr.boundaryIdx}, gap ${mgr._gapSlots}) — cancelling instead of re-pricing`, 'warn');
1072
+ }
1073
+ else {
1074
+ queueCorrection({
1075
+ gridOrder: { ...gridOrder },
1076
+ chainOrderId: gridOrder.orderId,
1077
+ expectedPrice: gridOrder.price,
1078
+ actualPrice: chainOrder.price,
1079
+ size: chainOrder.size,
1080
+ type: gridOrder.type
1081
+ });
1082
+ }
1010
1083
  }
1011
1084
  }
1012
1085
  // Chain side determines which precision applies to for_sale.
@@ -1126,12 +1199,21 @@ class SyncEngine {
1126
1199
  // processing (deriveTargetBoundary) derives boundary
1127
1200
  // movement from fill.type, and a SPREAD type would
1128
1201
  // silently drop the shift for this completed order.
1129
- filledOrders.push({ ...gridOrder, type: chainOrder.type });
1202
+ filledOrders.push({ ...gridOrder, type: chainOrder.type, price: toFiniteNumber(chainOrder.price, gridOrder.price) });
1130
1203
  updatedOrders.push(spreadOrder);
1131
1204
  }
1132
1205
  }
1133
1206
  }
1134
- else if (gridOrder.state === ORDER_STATES.ACTIVE || gridOrder.state === ORDER_STATES.PARTIAL) {
1207
+ else if (gridOrder.state === ORDER_STATES.ACTIVE || gridOrder.state === ORDER_STATES.PARTIAL || hasOnChainId(gridOrder)) {
1208
+ // Also entered for a NON-placed slot that still carries an
1209
+ // orderId (virtualised while its order was live). Two outcomes
1210
+ // below, decided by `wasPlaced`:
1211
+ // * placed + absent -> a real fill/phantom (booked as before),
1212
+ // * virtual + absent -> the id is simply STALE: clear it so the
1213
+ // level becomes a normal hole again. Without this a stale id
1214
+ // would keep the slot looking occupied forever (blocking the
1215
+ // CREATE that the level needs) and would keep masking a
1216
+ // genuine fill on the other side.
1135
1217
  // Don't virtualize orders placed by a successful COW commit.
1136
1218
  // The chain snapshot may lag behind confirmed transactions,
1137
1219
  // causing correctly-placed orders to appear missing. _committedOrderIds
@@ -1173,8 +1255,23 @@ class SyncEngine {
1173
1255
  }
1174
1256
  const currentGridOrder = mgr.orders.get(gridOrder.id) || gridOrder;
1175
1257
  const hadOrderId = Boolean(currentGridOrder?.orderId);
1258
+ const wasPlaced = isOrderPlaced(currentGridOrder);
1259
+ // A freshly assigned id on a NON-placed slot is not trustworthy
1260
+ // evidence of absence yet (an in-flight create/cancel whose
1261
+ // broadcast has not landed, or a lagging read). Mirrors the
1262
+ // reconcile's _orderIdAssignedAt deferral: keep the id, re-check
1263
+ // next sync. A PLACED slot keeps the existing behaviour.
1264
+ if (!wasPlaced && hadOrderId) {
1265
+ const assignedAt = Number(mgr._orderIdAssignedAt?.get(String(currentGridOrder.orderId)) || 0);
1266
+ if (assignedAt > 0 && Date.now() - assignedAt < TIMING.SYNC_LOCK_TIMEOUT_MS) {
1267
+ mgr.logger?.log?.(`[SYNC] Stale-id check for ${gridOrder.id} deferred: chain id ${currentGridOrder.orderId} was ` +
1268
+ `assigned ${Date.now() - assignedAt}ms ago and is not in the snapshot — absence not yet trustworthy`, 'debug');
1269
+ continue;
1270
+ }
1271
+ }
1176
1272
  const spreadOrder = convertToSpreadPlaceholder(currentGridOrder);
1177
- const phantomApplied = await mgr._applyOrderUpdate(spreadOrder, 'sync-cleanup-phantom', { skipAccounting: skipAccounting, fee: 0 });
1273
+ const cleanupContext = wasPlaced ? 'sync-cleanup-phantom' : 'sync-clear-stale-id';
1274
+ const phantomApplied = await mgr._applyOrderUpdate(spreadOrder, cleanupContext, { skipAccounting: skipAccounting, fee: 0 });
1178
1275
  if (phantomApplied === false) {
1179
1276
  // Rejected virtualization books no phantom fill: the slot
1180
1277
  // keeps its order and the disappearance re-detects next
@@ -1182,8 +1279,12 @@ class SyncEngine {
1182
1279
  mgr.logger?.log?.(`[SYNC] Phantom cleanup for ${gridOrder.id} rejected — fill NOT booked`, 'warn');
1183
1280
  continue;
1184
1281
  }
1185
- // Only genuine disappearances (had orderId) count as fills.
1186
- if (hadOrderId) {
1282
+ // Only genuine disappearances of a PLACED order count as fills.
1283
+ // A virtualised slot's stale id is cleared above without booking
1284
+ // anything: the funds for that level were already settled when
1285
+ // the slot was virtualised, and inventing a fill here would arm
1286
+ // the pivot and crawl for a trade that never happened.
1287
+ if (hadOrderId && wasPlaced) {
1187
1288
  // A SPREAD slot can carry an on-chain order (spread-correction
1188
1289
  // activation). Resolve the real side before pushing: the fill
1189
1290
  // drives deriveTargetBoundary, which only shifts on BUY/SELL —
@@ -1195,7 +1296,33 @@ class SyncEngine {
1195
1296
  if (resolvedType === ORDER_TYPES.SPREAD) {
1196
1297
  resolvedType = resolveSpreadOrderSide(currentGridOrder.price, mgr.config.startPrice);
1197
1298
  }
1198
- filledOrders.push({ ...currentGridOrder, type: resolvedType });
1299
+ const liveChainPrice = (() => {
1300
+ const raw = currentGridOrder?.rawOnChain;
1301
+ if (!raw)
1302
+ return null;
1303
+ try {
1304
+ const parsed = parseChainOrder(raw, mgr.assets);
1305
+ if (!parsed)
1306
+ return null;
1307
+ if (currentGridOrder.orderId && parsed.orderId !== currentGridOrder.orderId)
1308
+ return null;
1309
+ return Number.isFinite(Number(parsed.price)) && Number(parsed.price) > 0 ? Number(parsed.price) : null;
1310
+ }
1311
+ catch {
1312
+ return null;
1313
+ }
1314
+ })();
1315
+ filledOrders.push({
1316
+ ...currentGridOrder,
1317
+ type: resolvedType,
1318
+ ...(liveChainPrice != null ? { price: liveChainPrice } : {})
1319
+ });
1320
+ }
1321
+ else if (hadOrderId) {
1322
+ updatedOrders.push(spreadOrder);
1323
+ mgr.logger?.log?.(`[SYNC] Cleared stale chain id ${currentGridOrder?.orderId ?? ''} on ${gridOrder.id} ` +
1324
+ `(slot was ${currentGridOrder?.state ?? ORDER_STATES.VIRTUAL}): the order is gone from the ` +
1325
+ `chain read, so the level is a normal hole again — no fill booked`, 'debug');
1199
1326
  }
1200
1327
  }
1201
1328
  }
@@ -1331,7 +1458,29 @@ class SyncEngine {
1331
1458
  }
1332
1459
  return null;
1333
1460
  }
1334
- _computeFillContext(mgr, matchedGridOrder, paysAssetId, paysAmountRaw) {
1461
+ /**
1462
+ * Absorb a fill whose order id has no ACTIVE/PARTIAL slot ("order not found
1463
+ * in active grid").
1464
+ *
1465
+ * Thin wrapper over the shared `attributeUnmatchedFillToGrid` helper (see
1466
+ * utils/order.ts for the two identities and the incident it closes). The
1467
+ * work lives outside this class so the orphan-credit path in
1468
+ * dexbot_fill_runtime.ts attributes fills with literally the same rule
1469
+ * instead of keeping a second, weaker copy.
1470
+ *
1471
+ * @returns {boolean} true when the fill was attributed to the grid.
1472
+ */
1473
+ _absorbUnmatchedFill(mgr, params) {
1474
+ return attributeUnmatchedFillToGrid(mgr, {
1475
+ orderId: params?.orderId ?? null,
1476
+ paysAssetId: params?.paysAssetId ?? null,
1477
+ paysAmountRaw: params?.paysAmountRaw == null ? null : Number(params.paysAmountRaw),
1478
+ receivesAssetId: params?.receivesAssetId ?? null,
1479
+ receivesAmountRaw: params?.receivesAmountRaw == null ? null : Number(params.receivesAmountRaw),
1480
+ isPartial: params?.isPartial === true,
1481
+ });
1482
+ }
1483
+ _computeFillContext(mgr, matchedGridOrder, paysAssetId, paysAmountRaw, receivesAssetId = null, receivesAmountRaw = null) {
1335
1484
  const assets = mgr.assets;
1336
1485
  if (!assets?.assetA || !assets?.assetB)
1337
1486
  throw new Error('assets required for fill context');
@@ -1366,10 +1515,21 @@ class SyncEngine {
1366
1515
  const rawForSale = matchedGridOrder?.rawOnChain?.for_sale;
1367
1516
  const rawForSaleInt = rawForSale !== undefined && rawForSale !== null ? toFiniteNumber(rawForSale) : NaN;
1368
1517
  const driftSignal = Number.isFinite(rawForSaleInt) && Math.round(rawForSaleInt) < currentSizeIntFromGrid;
1369
- return { orderType, currentSize, precision, filledAmount, currentSizeIntFromGrid, rawForSaleInt, driftSignal };
1518
+ // Execution price from the actual paid/received amounts (quote per
1519
+ // base). This is the fill FACT the last-fill pivot and the re-anchor
1520
+ // need; the slot price is only a grid identity and may be stale after
1521
+ // a refused-commit chain adoption. Shared with the unmatched-fill
1522
+ // attribution so both resolve a price identically.
1523
+ const fillPrice = resolveExecutionPrice(assets, paysAssetId, paysAmountRaw, receivesAssetId, receivesAmountRaw);
1524
+ return { orderType, currentSize, precision, filledAmount, currentSizeIntFromGrid, rawForSaleInt, driftSignal, fillPrice };
1370
1525
  }
1371
1526
  async _computeFillTransitionResult(mgr, params) {
1372
- const { matchedGridOrder, orderType, precision, filledAmount, filledAmountInt, currentSizeIntFromGrid, chainRefetched, chainConfirmsEmpty, effectiveRawForSale, blockNum, historyId, isMaker } = params;
1527
+ const { matchedGridOrder, orderType, precision, filledAmount, filledAmountInt, currentSizeIntFromGrid, chainRefetched, chainConfirmsEmpty, effectiveRawForSale, blockNum, historyId, isMaker, fillPrice } = params;
1528
+ // Fill price provenance: prefer the real execution price, fall back to
1529
+ // the slot level only when no chain price/amounts are available.
1530
+ const resolvedFillPrice = Number.isFinite(Number(fillPrice)) && Number(fillPrice) > 0
1531
+ ? Number(fillPrice)
1532
+ : matchedGridOrder.price;
1373
1533
  let resolvedChainConfirmsEmpty = chainConfirmsEmpty;
1374
1534
  if (chainRefetched && Number.isFinite(effectiveRawForSale) && Math.round(effectiveRawForSale) <= 0) {
1375
1535
  resolvedChainConfirmsEmpty = true;
@@ -1462,6 +1622,7 @@ class SyncEngine {
1462
1622
  filledOrderResult = {
1463
1623
  ...matchedGridOrder,
1464
1624
  type: orderType,
1625
+ price: resolvedFillPrice,
1465
1626
  blockNum,
1466
1627
  historyId,
1467
1628
  isMaker
@@ -1471,6 +1632,7 @@ class SyncEngine {
1471
1632
  filledOrderResult = {
1472
1633
  ...matchedGridOrder,
1473
1634
  type: orderType,
1635
+ price: resolvedFillPrice,
1474
1636
  size: filledAmount,
1475
1637
  isPartial: true,
1476
1638
  blockNum,
@@ -1570,10 +1732,19 @@ class SyncEngine {
1570
1732
  }
1571
1733
  const matchedGridOrder = this._findMatchingGridOrder(mgr, orderId);
1572
1734
  if (!matchedGridOrder) {
1573
- mgr.logger.log(`[SYNC] Fill for order ${orderId} ignored: order not found in active grid.`, 'debug');
1735
+ // An order that filled while its slot was already virtualised
1736
+ // still proves a trade: absorb the pivot + owed crawl from the
1737
+ // real execution price instead of dropping it (see
1738
+ // _absorbUnmatchedFill). Only a truly unknown order is ignored.
1739
+ const absorbed = this._absorbUnmatchedFill(mgr, {
1740
+ orderId, paysAssetId, paysAmountRaw, receivesAssetId, receivesAmountRaw,
1741
+ });
1742
+ if (!absorbed) {
1743
+ mgr.logger.log(`[SYNC] Fill for order ${orderId} ignored: order not found in active grid.`, 'debug');
1744
+ }
1574
1745
  return { filledOrders: [], updatedOrders: [], partialFill: false };
1575
1746
  }
1576
- const ctx = this._computeFillContext(mgr, matchedGridOrder, paysAssetId, paysAmountRaw);
1747
+ const ctx = this._computeFillContext(mgr, matchedGridOrder, paysAssetId, paysAmountRaw, receivesAssetId, receivesAmountRaw);
1577
1748
  mgr.logger.log(`[SYNC] Order ${orderId} (${ctx.orderType}) currentSize=${ctx.currentSize}, filledAmount=${ctx.filledAmount}`, 'debug');
1578
1749
  let effectiveRawForSale = ctx.rawForSaleInt;
1579
1750
  let chainConfirmsEmpty = false;
@@ -1612,7 +1783,8 @@ class SyncEngine {
1612
1783
  effectiveRawForSale,
1613
1784
  blockNum,
1614
1785
  historyId,
1615
- isMaker
1786
+ isMaker,
1787
+ fillPrice: ctx.fillPrice
1616
1788
  });
1617
1789
  const filledOrders = [];
1618
1790
  const updatedOrders = [];
@@ -1768,11 +1940,20 @@ class SyncEngine {
1768
1940
  const { orderId, paysAmountRaw, paysAssetId } = entry;
1769
1941
  const matchedGridOrder = this._findMatchingGridOrder(mgr, orderId);
1770
1942
  if (!matchedGridOrder) {
1771
- mgr.logger.log(`[SYNC] Fill for order ${orderId} ignored: order not found in active grid.`, 'debug');
1943
+ // Same absorption as the single-fill path: keep the
1944
+ // pivot/crawl ledger honest so the next derivation and the
1945
+ // LAST-FILL-GUARD see the price that actually traded.
1946
+ const absorbed = this._absorbUnmatchedFill(mgr, {
1947
+ orderId, paysAssetId, paysAmountRaw,
1948
+ receivesAssetId: entry.receivesAssetId, receivesAmountRaw: entry.receivesAmountRaw,
1949
+ });
1950
+ if (!absorbed) {
1951
+ mgr.logger.log(`[SYNC] Fill for order ${orderId} ignored: order not found in active grid.`, 'debug');
1952
+ }
1772
1953
  anyRequiresSync = true;
1773
1954
  continue;
1774
1955
  }
1775
- const ctx = this._computeFillContext(mgr, matchedGridOrder, paysAssetId, paysAmountRaw);
1956
+ const ctx = this._computeFillContext(mgr, matchedGridOrder, paysAssetId, paysAmountRaw, entry.receivesAssetId, entry.receivesAmountRaw);
1776
1957
  mgr.logger.log(`[SYNC] Order ${orderId} (${ctx.orderType}) currentSize=${ctx.currentSize}, filledAmount=${ctx.filledAmount}`, 'debug');
1777
1958
  if (ctx.driftSignal && orderId) {
1778
1959
  driftOrderIds.add(orderId);
@@ -1784,7 +1965,8 @@ class SyncEngine {
1784
1965
  filledAmount: ctx.filledAmount,
1785
1966
  filledAmountInt: floatToBlockchainInt(ctx.filledAmount, ctx.precision),
1786
1967
  currentSizeIntFromGrid: ctx.currentSizeIntFromGrid,
1787
- rawForSaleInt: ctx.rawForSaleInt
1968
+ rawForSaleInt: ctx.rawForSaleInt,
1969
+ fillPrice: ctx.fillPrice
1788
1970
  });
1789
1971
  }
1790
1972
  // Phase 5: Batch drift refetch — one get_objects call for all order IDs
@@ -1886,7 +2068,8 @@ class SyncEngine {
1886
2068
  effectiveRawForSale,
1887
2069
  blockNum: lastCtx.entry.blockNum,
1888
2070
  historyId: lastCtx.entry.historyId,
1889
- isMaker: lastCtx.entry.isMaker
2071
+ isMaker: lastCtx.entry.isMaker,
2072
+ fillPrice: lastCtx.fillPrice
1890
2073
  });
1891
2074
  if (result.isFull) {
1892
2075
  mgr.logger.log(`[SYNC] Full fill for order ${orderId} (slot ${matchedGridOrder.id}).`, 'info');
@@ -838,11 +838,10 @@ declare function validateOrderSize(orderSize: number, orderType: string, assets:
838
838
  * @param {number} weight - Weight factor (0-1) controlling distribution steepness
839
839
  * @param {number} incrementFactor - Increment factor (typically 0.01 for 1% grid spacing)
840
840
  * @param {boolean} [reverse=false] - If true, allocate larger sizes to higher indices
841
- * @param {number} [minSize=0] - Minimum size for each allocation (currently unused, for future validation)
842
841
  * @param {number} [precision=null] - Asset precision; if provided, quantize to blockchain integers
843
842
  * @returns {Array<number>} Array of n allocation sizes
844
843
  */
845
- declare function allocateFundsByWeights(totalFunds: number, n: number, weight: unknown, incrementFactor: number, reverse?: boolean, _minSize?: number, precision?: number | null): number[];
844
+ declare function allocateFundsByWeights(totalFunds: number, n: number, weight: unknown, incrementFactor: number, reverse?: boolean, precision?: number | null): number[];
846
845
  /**
847
846
  * Calculate order sizes for a list of orders using weighted fund allocation.
848
847
  * Allocates buy and sell funds separately using weight distribution from config.
@@ -852,13 +851,11 @@ declare function allocateFundsByWeights(totalFunds: number, n: number, weight: u
852
851
  * @param {Object} config - Configuration with incrementPercent and weightDistribution
853
852
  * @param {number} sellFunds - Total funds available for SELL orders
854
853
  * @param {number} buyFunds - Total funds available for BUY orders
855
- * @param {number} [minSellSize=0] - Minimum size for sell allocations
856
- * @param {number} [minBuySize=0] - Minimum size for buy allocations
857
854
  * @param {number} [precisionA=null] - Precision for assetA (SELL asset)
858
855
  * @param {number} [precisionB=null] - Precision for assetB (BUY asset)
859
856
  * @returns {Array<Object>} Orders array with size property added to each
860
857
  */
861
- declare function calculateOrderSizes(orders: ManagedOrder[], config: GridConfig, sellFunds: number, buyFunds: number, minSellSize?: number, minBuySize?: number, precisionA?: number | null, precisionB?: number | null): ManagedOrder[];
858
+ declare function calculateOrderSizes(orders: ManagedOrder[], config: GridConfig, sellFunds: number, buyFunds: number, precisionA?: number | null, precisionB?: number | null): ManagedOrder[];
862
859
  /**
863
860
  * Calculate order sizes for rotation operations.
864
861
  * Combines available funds with existing grid allocation for sizing.
@@ -869,11 +866,10 @@ declare function calculateOrderSizes(orders: ManagedOrder[], config: GridConfig,
869
866
  * @param {number} orderCount - Number of orders to size
870
867
  * @param {string} orderType - Order type (BUY or SELL)
871
868
  * @param {Object} config - Configuration with incrementPercent and weightDistribution
872
- * @param {number} [minSize=0] - Minimum size for each allocation
873
869
  * @param {number} [precision=null] - Asset precision for quantization
874
870
  * @returns {Array<number>} Array of order sizes
875
871
  */
876
- declare function calculateRotationOrderSizes(availableFunds: number, totalGridAllocation: number, orderCount: number, orderType: string, config: GridConfig, minSize?: number, precision?: number | null): number[];
872
+ declare function calculateRotationOrderSizes(availableFunds: number, totalGridAllocation: number, orderCount: number, orderType: string, config: GridConfig, precision?: number | null): number[];
877
873
  /**
878
874
  * Calculate RMS (Root Mean Square) divergence between calculated and persisted grids.
879
875
  * Measures how much the current grid differs from the calculated ideal.
@@ -894,7 +890,7 @@ declare function calculateGridSideDivergenceMetric(calculatedOrders: ManagedOrde
894
890
  * Works for all pairs — returns the BTS fee budget needed for order operations.
895
891
  *
896
892
  * @param {string} assetA - First asset symbol
897
- * @param {string} assetB - Second asset symbol (unused in calculation, kept for signature compat)
893
+ * @param {string} assetB - Second asset symbol (used only to label the fee-cache warning)
898
894
  * @param {number} totalOrders - Number of orders to create
899
895
  * @param {number} [feeMultiplier=BTS_RESERVATION_MULTIPLIER] - Multiplier for reservation (typically 5x)
900
896
  * @returns {number} Total fee amount (fallback BTS_FALLBACK_FEE if fee lookup fails; warning logged)
@@ -1025,6 +1021,7 @@ declare const BOUNDARY_REJECT_PLACED_IN_BAND = "placed_order_in_band";
1025
1021
  */
1026
1022
  declare function validateBoundaryCommit(proposedBoundary: number | null | undefined, orders: Iterable<unknown>, gapSlots: number, options?: {
1027
1023
  rejectInBandPlacements?: boolean;
1024
+ allowInBandSlotIds?: Iterable<string>;
1028
1025
  }): {
1029
1026
  ok: boolean;
1030
1027
  reason?: string;
@@ -1058,7 +1055,9 @@ declare function validateBoundaryCommit(proposedBoundary: number | null | undefi
1058
1055
  * in-progress evacuation; true poison still refuses and structural resync
1059
1056
  * falls through to the clean full-grid reset instead of re-ingesting damage.
1060
1057
  */
1061
- declare function validatePersistedBoundary(proposedBoundary: number | null | undefined, orders: Iterable<unknown>, gapSlots: number): {
1058
+ declare function validatePersistedBoundary(proposedBoundary: number | null | undefined, orders: Iterable<unknown>, gapSlots: number, options?: {
1059
+ allowInBandSlotIds?: Iterable<string>;
1060
+ }): {
1062
1061
  ok: boolean;
1063
1062
  reason?: string;
1064
1063
  detail?: string;
@@ -1254,9 +1253,26 @@ declare function priceSlotEqual(a: number, b: number, precision: number): boolea
1254
1253
  * one that prevents non-termination, which no caller could recover from.
1255
1254
  */
1256
1255
  declare function derivePriceLevels(startPrice: number, minPrice: number, maxPrice: number, incrementPercent: number): number[];
1256
+ /**
1257
+ * True when two prices are the SAME grid step: within half an increment of
1258
+ * each other. Used to judge a placement against the price that just traded —
1259
+ * a fill's execution price and the slot level it filled at differ by rounding
1260
+ * (live: slot 1310.046339 filled at 1310.060435, i.e. ~1e-5), so a raw
1261
+ * `>=`/`<=` comparison lets a same-level re-place through.
1262
+ *
1263
+ * The half-step cap mirrors `pricesOnSameLevel`: it can never merge two
1264
+ * legitimately adjacent levels (a full increment apart). A missing/invalid
1265
+ * increment degrades to exact equality.
1266
+ *
1267
+ * @param {number} priceA - First price
1268
+ * @param {number} priceB - Second price
1269
+ * @param {number} incrementPercent - Grid step in percent (e.g. 0.3)
1270
+ * @returns {boolean} True when both prices sit on the same grid step
1271
+ */
1272
+ declare function pricesWithinHalfStep(priceA: number, priceB: number, incrementPercent: number | null | undefined): boolean;
1257
1273
  declare function buildGenesisFromPriceLevels(startPrice: number, incrementPercent: number, gapSlots: number, priceLevels: number[]): GridGenesis;
1258
1274
  export type { FeeCacheEntry };
1259
- export { getBtsSide, getSellStartIdx, resolveGapBand, countGapBandSpread, calculateGapSlots, isSlotInRail, isSlotIndexInGapBand, isEvacuationRotationAllowed, isEvacuationSizeStillValid, validateBoundaryCommit, validatePersistedBoundary, isTransientInBandRejection, BOUNDARY_REJECT_PLACED_IN_BAND, resolveGapSlots, isPercentageString, isPositiveNumber, isPositiveNumberOrPercent, isPositiveInt, parsePercentageString, toDecimal, resolveRelativePrice, parseRelativeMultiplier, validateGridPriceBounds, isExplicitZeroAllocation, getPrecision, computeChainFundTotals, calculateAvailableFundsValue, deriveChainTruthFundBudget, adjustBudgetForBtsFees, getGridBestPrices, calculateSpreadFromOrders, resolveConfigValue, resolveConfigValueWithRegistry, hasValidAccountTotals, blockchainToFloat, floatToBlockchainInt, floorToBlockchainInt, quantizeFloat, normalizeInt, getPrecisionByOrderType, getPrecisionsForManager, getPrecisionSlack, quantumForPrecision, calculatePriceTolerance, findCrossedOrder, pricesOnSameLevel, sameGridPrice, validateOrderAmountsWithinLimits, getMinOrderSize, getDustThresholdFactor, getSingleDustThreshold, getDoubleDustThreshold, validateOrderSize, getAssetFees, getAssetFeesSafe, allocateFundsByWeights, calculateOrderSizes, calculateRotationOrderSizes, calculateGridSideDivergenceMetric, calculateOrderCreationFees, calculateSwapInAmount, _setFeeCache, cloneWeightDistribution, clamp, roundTo, fixedTo, roundToDecimals, priceLevelsForGenesis, priceForSlot, slotIndexForPrice, slotIdForPrice, assertSlotPriceInvariant, priceSlotEqual, derivePriceLevels, sameGridLevel, buildGenesisFromPriceLevels, hashPriceLevels, isChainPriceOutOfGrid };
1275
+ export { getBtsSide, getSellStartIdx, resolveGapBand, countGapBandSpread, calculateGapSlots, isSlotInRail, isSlotIndexInGapBand, isEvacuationRotationAllowed, isEvacuationSizeStillValid, validateBoundaryCommit, validatePersistedBoundary, isTransientInBandRejection, BOUNDARY_REJECT_PLACED_IN_BAND, resolveGapSlots, isPercentageString, isPositiveNumber, isPositiveNumberOrPercent, isPositiveInt, parsePercentageString, toDecimal, resolveRelativePrice, parseRelativeMultiplier, validateGridPriceBounds, isExplicitZeroAllocation, getPrecision, computeChainFundTotals, calculateAvailableFundsValue, deriveChainTruthFundBudget, adjustBudgetForBtsFees, getGridBestPrices, calculateSpreadFromOrders, resolveConfigValue, resolveConfigValueWithRegistry, hasValidAccountTotals, blockchainToFloat, floatToBlockchainInt, floorToBlockchainInt, quantizeFloat, normalizeInt, getPrecisionByOrderType, getPrecisionsForManager, getPrecisionSlack, quantumForPrecision, calculatePriceTolerance, findCrossedOrder, pricesOnSameLevel, sameGridPrice, validateOrderAmountsWithinLimits, getMinOrderSize, getDustThresholdFactor, getSingleDustThreshold, getDoubleDustThreshold, validateOrderSize, getAssetFees, getAssetFeesSafe, allocateFundsByWeights, calculateOrderSizes, calculateRotationOrderSizes, calculateGridSideDivergenceMetric, calculateOrderCreationFees, calculateSwapInAmount, _setFeeCache, cloneWeightDistribution, clamp, roundTo, fixedTo, roundToDecimals, priceLevelsForGenesis, priceForSlot, slotIndexForPrice, slotIdForPrice, assertSlotPriceInvariant, priceSlotEqual, derivePriceLevels, sameGridLevel, pricesWithinHalfStep, buildGenesisFromPriceLevels, hashPriceLevels, isChainPriceOutOfGrid };
1260
1276
  /**
1261
1277
  * Round a value to a given factor.
1262
1278
  * @param {number} value - Value to round
@@ -1226,11 +1226,10 @@ function validateOrderSize(orderSize, orderType, assets, minFactor = GRID_LIMITS
1226
1226
  * @param {number} weight - Weight factor (0-1) controlling distribution steepness
1227
1227
  * @param {number} incrementFactor - Increment factor (typically 0.01 for 1% grid spacing)
1228
1228
  * @param {boolean} [reverse=false] - If true, allocate larger sizes to higher indices
1229
- * @param {number} [minSize=0] - Minimum size for each allocation (currently unused, for future validation)
1230
1229
  * @param {number} [precision=null] - Asset precision; if provided, quantize to blockchain integers
1231
1230
  * @returns {Array<number>} Array of n allocation sizes
1232
1231
  */
1233
- function allocateFundsByWeights(totalFunds, n, weight, incrementFactor, reverse = false, _minSize = 0, precision = null) {
1232
+ function allocateFundsByWeights(totalFunds, n, weight, incrementFactor, reverse = false, precision = null) {
1234
1233
  if (n <= 0)
1235
1234
  return [];
1236
1235
  if (!Number.isFinite(totalFunds) || totalFunds <= 0)
@@ -1282,21 +1281,19 @@ function allocateFundsByWeights(totalFunds, n, weight, incrementFactor, reverse
1282
1281
  * @param {Object} config - Configuration with incrementPercent and weightDistribution
1283
1282
  * @param {number} sellFunds - Total funds available for SELL orders
1284
1283
  * @param {number} buyFunds - Total funds available for BUY orders
1285
- * @param {number} [minSellSize=0] - Minimum size for sell allocations
1286
- * @param {number} [minBuySize=0] - Minimum size for buy allocations
1287
1284
  * @param {number} [precisionA=null] - Precision for assetA (SELL asset)
1288
1285
  * @param {number} [precisionB=null] - Precision for assetB (BUY asset)
1289
1286
  * @returns {Array<Object>} Orders array with size property added to each
1290
1287
  */
1291
- function calculateOrderSizes(orders, config, sellFunds, buyFunds, minSellSize = 0, minBuySize = 0, precisionA = null, precisionB = null) {
1288
+ function calculateOrderSizes(orders, config, sellFunds, buyFunds, precisionA = null, precisionB = null) {
1292
1289
  const incrementPercent = config.incrementPercent ?? 0;
1293
1290
  const sellWeight = config.weightDistribution?.sell ?? 0;
1294
1291
  const buyWeight = config.weightDistribution?.buy ?? 0;
1295
1292
  const incrementFactor = incrementPercent / 100;
1296
1293
  const sellOrders = orders.filter((o) => o.type === ORDER_TYPES.SELL);
1297
1294
  const buyOrders = orders.filter((o) => o.type === ORDER_TYPES.BUY);
1298
- const sellSizes = allocateFundsByWeights(sellFunds, sellOrders.length, sellWeight, incrementFactor, false, minSellSize, precisionA);
1299
- const buySizes = allocateFundsByWeights(buyFunds, buyOrders.length, buyWeight, incrementFactor, true, minBuySize, precisionB);
1295
+ const sellSizes = allocateFundsByWeights(sellFunds, sellOrders.length, sellWeight, incrementFactor, false, precisionA);
1296
+ const buySizes = allocateFundsByWeights(buyFunds, buyOrders.length, buyWeight, incrementFactor, true, precisionB);
1300
1297
  const sellState = { sizes: sellSizes, index: 0 };
1301
1298
  const buyState = { sizes: buySizes, index: 0 };
1302
1299
  return orders.map((order) => {
@@ -1324,11 +1321,10 @@ function calculateOrderSizes(orders, config, sellFunds, buyFunds, minSellSize =
1324
1321
  * @param {number} orderCount - Number of orders to size
1325
1322
  * @param {string} orderType - Order type (BUY or SELL)
1326
1323
  * @param {Object} config - Configuration with incrementPercent and weightDistribution
1327
- * @param {number} [minSize=0] - Minimum size for each allocation
1328
1324
  * @param {number} [precision=null] - Asset precision for quantization
1329
1325
  * @returns {Array<number>} Array of order sizes
1330
1326
  */
1331
- function calculateRotationOrderSizes(availableFunds, totalGridAllocation, orderCount, orderType, config, minSize = 0, precision = null) {
1327
+ function calculateRotationOrderSizes(availableFunds, totalGridAllocation, orderCount, orderType, config, precision = null) {
1332
1328
  if (orderCount <= 0)
1333
1329
  return [];
1334
1330
  const totalFunds = availableFunds + totalGridAllocation;
@@ -1339,7 +1335,7 @@ function calculateRotationOrderSizes(availableFunds, totalGridAllocation, orderC
1339
1335
  const incrementFactor = incrementPercent / 100;
1340
1336
  const weight = (orderType === ORDER_TYPES.SELL) ? (weightDistribution.sell ?? 0) : (weightDistribution.buy ?? 0);
1341
1337
  const reverse = (orderType === ORDER_TYPES.BUY);
1342
- return allocateFundsByWeights(totalFunds, orderCount, weight, incrementFactor, reverse, minSize, precision);
1338
+ return allocateFundsByWeights(totalFunds, orderCount, weight, incrementFactor, reverse, precision);
1343
1339
  }
1344
1340
  /**
1345
1341
  * Calculate RMS (Root Mean Square) divergence between calculated and persisted grids.
@@ -1404,7 +1400,7 @@ function calculateGridSideDivergenceMetric(calculatedOrders, persistedOrders, _s
1404
1400
  * Works for all pairs — returns the BTS fee budget needed for order operations.
1405
1401
  *
1406
1402
  * @param {string} assetA - First asset symbol
1407
- * @param {string} assetB - Second asset symbol (unused in calculation, kept for signature compat)
1403
+ * @param {string} assetB - Second asset symbol (used only to label the fee-cache warning)
1408
1404
  * @param {number} totalOrders - Number of orders to create
1409
1405
  * @param {number} [feeMultiplier=BTS_RESERVATION_MULTIPLIER] - Multiplier for reservation (typically 5x)
1410
1406
  * @returns {number} Total fee amount (fallback BTS_FALLBACK_FEE if fee lookup fails; warning logged)
@@ -1646,6 +1642,15 @@ function validateBoundaryCommit(proposedBoundary, orders, gapSlots, options = {}
1646
1642
  let inBandCount = 0;
1647
1643
  let firstInBandIdx = null;
1648
1644
  let firstInBandPrice = null;
1645
+ // Explicit allow-list for the fill's OWN residual order (partial fill at
1646
+ // the anchor slot). A re-anchor to `fillSlot - gapSlots` necessarily puts
1647
+ // that residual inside the implied band; refusing it deadlocks the
1648
+ // geometry (the residual cannot be cancelled by the re-anchor itself).
1649
+ // Callers must pass only the last-fill residual id — ACTIVE/foreign
1650
+ // in-band placements stay rejected.
1651
+ const allowedInBand = options.allowInBandSlotIds
1652
+ ? new Set(Array.from(options.allowInBandSlotIds).filter((id) => typeof id === 'string' && id.length > 0))
1653
+ : null;
1649
1654
  for (let idx = 0; idx < sorted.length; idx++) {
1650
1655
  const o = sorted[idx];
1651
1656
  if (!o.orderId)
@@ -1660,6 +1665,9 @@ function validateBoundaryCommit(proposedBoundary, orders, gapSlots, options = {}
1660
1665
  minSellPrice = price;
1661
1666
  }
1662
1667
  else if (options.rejectInBandPlacements) {
1668
+ const slotId = o.id;
1669
+ if (allowedInBand && typeof slotId === 'string' && allowedInBand.has(slotId))
1670
+ continue;
1663
1671
  inBandCount++;
1664
1672
  if (firstInBandIdx === null) {
1665
1673
  firstInBandIdx = idx;
@@ -1712,8 +1720,11 @@ function validateBoundaryCommit(proposedBoundary, orders, gapSlots, options = {}
1712
1720
  * in-progress evacuation; true poison still refuses and structural resync
1713
1721
  * falls through to the clean full-grid reset instead of re-ingesting damage.
1714
1722
  */
1715
- function validatePersistedBoundary(proposedBoundary, orders, gapSlots) {
1716
- return validateBoundaryCommit(proposedBoundary, orders, gapSlots, { rejectInBandPlacements: true });
1723
+ function validatePersistedBoundary(proposedBoundary, orders, gapSlots, options = {}) {
1724
+ return validateBoundaryCommit(proposedBoundary, orders, gapSlots, {
1725
+ rejectInBandPlacements: true,
1726
+ ...(options.allowInBandSlotIds ? { allowInBandSlotIds: options.allowInBandSlotIds } : {})
1727
+ });
1717
1728
  }
1718
1729
  /**
1719
1730
  * Whether a persisted-boundary rejection is the TRANSIENT kind that must not
@@ -2137,6 +2148,35 @@ function derivePriceLevels(startPrice, minPrice, maxPrice, incrementPercent) {
2137
2148
  }
2138
2149
  return deduped;
2139
2150
  }
2151
+ /**
2152
+ * True when two prices are the SAME grid step: within half an increment of
2153
+ * each other. Used to judge a placement against the price that just traded —
2154
+ * a fill's execution price and the slot level it filled at differ by rounding
2155
+ * (live: slot 1310.046339 filled at 1310.060435, i.e. ~1e-5), so a raw
2156
+ * `>=`/`<=` comparison lets a same-level re-place through.
2157
+ *
2158
+ * The half-step cap mirrors `pricesOnSameLevel`: it can never merge two
2159
+ * legitimately adjacent levels (a full increment apart). A missing/invalid
2160
+ * increment degrades to exact equality.
2161
+ *
2162
+ * @param {number} priceA - First price
2163
+ * @param {number} priceB - Second price
2164
+ * @param {number} incrementPercent - Grid step in percent (e.g. 0.3)
2165
+ * @returns {boolean} True when both prices sit on the same grid step
2166
+ */
2167
+ function pricesWithinHalfStep(priceA, priceB, incrementPercent) {
2168
+ const pa = Number(priceA);
2169
+ const pb = Number(priceB);
2170
+ if (!Number.isFinite(pa) || !Number.isFinite(pb))
2171
+ return false;
2172
+ const inc = Number(incrementPercent);
2173
+ if (!Number.isFinite(inc) || inc <= 0)
2174
+ return pa === pb;
2175
+ const level = Math.min(Math.abs(pa), Math.abs(pb));
2176
+ if (!Number.isFinite(level))
2177
+ return pa === pb;
2178
+ return Math.abs(pa - pb) <= level * (inc / 100) * 0.5;
2179
+ }
2140
2180
  function buildGenesisFromPriceLevels(startPrice, incrementPercent, gapSlots, priceLevels) {
2141
2181
  const hash = hashPriceLevels(priceLevels);
2142
2182
  return {
@@ -2148,7 +2188,7 @@ function buildGenesisFromPriceLevels(startPrice, incrementPercent, gapSlots, pri
2148
2188
  createdAt: Date.now()
2149
2189
  };
2150
2190
  }
2151
- export { getBtsSide, getSellStartIdx, resolveGapBand, countGapBandSpread, calculateGapSlots, isSlotInRail, isSlotIndexInGapBand, isEvacuationRotationAllowed, isEvacuationSizeStillValid, validateBoundaryCommit, validatePersistedBoundary, isTransientInBandRejection, BOUNDARY_REJECT_PLACED_IN_BAND, resolveGapSlots, isPercentageString, isPositiveNumber, isPositiveNumberOrPercent, isPositiveInt, parsePercentageString, toDecimal, resolveRelativePrice, parseRelativeMultiplier, validateGridPriceBounds, isExplicitZeroAllocation, getPrecision, computeChainFundTotals, calculateAvailableFundsValue, deriveChainTruthFundBudget, adjustBudgetForBtsFees, getGridBestPrices, calculateSpreadFromOrders, resolveConfigValue, resolveConfigValueWithRegistry, hasValidAccountTotals, blockchainToFloat, floatToBlockchainInt, floorToBlockchainInt, quantizeFloat, normalizeInt, getPrecisionByOrderType, getPrecisionsForManager, getPrecisionSlack, quantumForPrecision, calculatePriceTolerance, findCrossedOrder, pricesOnSameLevel, sameGridPrice, validateOrderAmountsWithinLimits, getMinOrderSize, getDustThresholdFactor, getSingleDustThreshold, getDoubleDustThreshold, validateOrderSize, getAssetFees, getAssetFeesSafe, allocateFundsByWeights, calculateOrderSizes, calculateRotationOrderSizes, calculateGridSideDivergenceMetric, calculateOrderCreationFees, calculateSwapInAmount, _setFeeCache, cloneWeightDistribution, clamp, roundTo, fixedTo, roundToDecimals, priceLevelsForGenesis, priceForSlot, slotIndexForPrice, slotIdForPrice, assertSlotPriceInvariant, priceSlotEqual, derivePriceLevels, sameGridLevel, buildGenesisFromPriceLevels, hashPriceLevels, isChainPriceOutOfGrid };
2191
+ export { getBtsSide, getSellStartIdx, resolveGapBand, countGapBandSpread, calculateGapSlots, isSlotInRail, isSlotIndexInGapBand, isEvacuationRotationAllowed, isEvacuationSizeStillValid, validateBoundaryCommit, validatePersistedBoundary, isTransientInBandRejection, BOUNDARY_REJECT_PLACED_IN_BAND, resolveGapSlots, isPercentageString, isPositiveNumber, isPositiveNumberOrPercent, isPositiveInt, parsePercentageString, toDecimal, resolveRelativePrice, parseRelativeMultiplier, validateGridPriceBounds, isExplicitZeroAllocation, getPrecision, computeChainFundTotals, calculateAvailableFundsValue, deriveChainTruthFundBudget, adjustBudgetForBtsFees, getGridBestPrices, calculateSpreadFromOrders, resolveConfigValue, resolveConfigValueWithRegistry, hasValidAccountTotals, blockchainToFloat, floatToBlockchainInt, floorToBlockchainInt, quantizeFloat, normalizeInt, getPrecisionByOrderType, getPrecisionsForManager, getPrecisionSlack, quantumForPrecision, calculatePriceTolerance, findCrossedOrder, pricesOnSameLevel, sameGridPrice, validateOrderAmountsWithinLimits, getMinOrderSize, getDustThresholdFactor, getSingleDustThreshold, getDoubleDustThreshold, validateOrderSize, getAssetFees, getAssetFeesSafe, allocateFundsByWeights, calculateOrderSizes, calculateRotationOrderSizes, calculateGridSideDivergenceMetric, calculateOrderCreationFees, calculateSwapInAmount, _setFeeCache, cloneWeightDistribution, clamp, roundTo, fixedTo, roundToDecimals, priceLevelsForGenesis, priceForSlot, slotIndexForPrice, slotIdForPrice, assertSlotPriceInvariant, priceSlotEqual, derivePriceLevels, sameGridLevel, pricesWithinHalfStep, buildGenesisFromPriceLevels, hashPriceLevels, isChainPriceOutOfGrid };
2152
2192
  /**
2153
2193
  * Round a value to a given factor.
2154
2194
  * @param {number} value - Value to round