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
@@ -6,9 +6,10 @@
6
6
  */
7
7
  import { ORDER_TYPES, ORDER_STATES, TIMING, BTS_PRECISION } from '../constants.js';
8
8
  import { readOpenOrdersGuarded } from '../chain_orders.js';
9
- import { getMinOrderSize, getAssetFees, getAssetFeesSafe, blockchainToFloat, findCrossedOrder, resolveGapBand, isSlotInRail, pricesOnSameLevel, sameGridLevel } from './utils/math.js';
10
- import { isOrderPlaced, parseChainOrder, buildCreateOrderArgs, buildOutsideInPairGroups, extractBatchOperationResults, chainOrderMatchesSlotWithTolerance, buildCrossingCheckCandidates, isCrossingCheckCandidate, getSideBudget, calculateBudgetedSizes, getCoreOrdersTotal, convertToSpreadPlaceholder, isOrderGoneErrorMessage, clearDuplicateOrphanDetection, resolveEdgeCount, resolveLiveEdgeAnchorPrice, edgeOrderIdSet, compareEdge, parseSlotIndex, reportGridPriceInvariant, liveWindowIdSet } from './utils/order.js';
11
- import { resolveAccountRef } from './utils/system.js';
9
+ import { getMinOrderSize, getAssetFees, getAssetFeesSafe, blockchainToFloat, findCrossedOrder, resolveGapBand, isSlotInRail, pricesOnSameLevel, pricesWithinHalfStep, sameGridLevel } from './utils/math.js';
10
+ import { isOrderPlaced, parseChainOrder, buildCreateOrderArgs, buildOutsideInPairGroups, extractBatchOperationResults, chainOrderMatchesSlotWithTolerance, buildCrossingCheckCandidates, isCrossingCheckCandidate, getSideBudget, calculateBudgetedSizes, getCoreOrdersTotal, convertToSpreadPlaceholder, isOrderGoneErrorMessage, clearDuplicateOrphanDetection, resolveEdgeCount, resolveLiveEdgeAnchorPrice, edgeOrderIdSet, compareEdge, reportGridPriceInvariant, liveWindowIdSet } from './utils/order.js';
11
+ import { parseSlotIndex } from './utils/slot.js';
12
+ import { resolveAccountRef, isLastFillPlacementBlocked, hasUnsettledFills } from './utils/system.js';
12
13
  import * as Format from './format.js';
13
14
  import { getErrorMessage, getErrorCode, getErrorName } from '../utils/errors.js';
14
15
  function computePlacementPriceCollision(manager, gridOrder) {
@@ -205,6 +206,15 @@ function _pickVirtualSlotsToActivate(manager, type, count) {
205
206
  // Derived budgeted size per slot, built once (O(n)) so below-min lookups
206
207
  // don't recompute full-side sizing for every candidate (avoid O(n²)).
207
208
  const derivedSizes = _deriveBudgetedSideSizes(manager, type);
209
+ // LAST-FILL placement discipline at PICK time: a candidate on the wrong
210
+ // side of the last fill (or on its own level) must not consume activation
211
+ // budget — the create would be refused downstream anyway, and the pick
212
+ // budget is what decides which levels get restored. Skipping it lets the
213
+ // picker fall through to the NEXT level down (BUY) / up (SELL), which is
214
+ // the "rotate to the bottom BUY / counter SELL" behaviour: the level that
215
+ // just traded is never re-stamped same-side.
216
+ let lastFillSkipped = 0;
217
+ let lastFillPivot = null;
208
218
  for (const slot of slotsOfType) {
209
219
  if (valid.length >= count)
210
220
  break;
@@ -225,6 +235,13 @@ function _pickVirtualSlotsToActivate(manager, type, count) {
225
235
  }
226
236
  }
227
237
  if (slot.id && effectiveSize >= effectiveMin) {
238
+ const fillGuard = isLastFillPlacementBlocked(manager, slot.price, type);
239
+ if (fillGuard.blocked) {
240
+ lastFillSkipped++;
241
+ if (lastFillPivot == null)
242
+ lastFillPivot = fillGuard.pivot;
243
+ continue;
244
+ }
228
245
  // Re-type the picked slot to the activation side: empty slots are
229
246
  // stored SPREAD (side-neutral), but an order being placed here must
230
247
  // carry the concrete BUY/SELL rail type (SPREAD+ACTIVE is illegal,
@@ -237,6 +254,10 @@ function _pickVirtualSlotsToActivate(manager, type, count) {
237
254
  }
238
255
  }
239
256
  }
257
+ if (lastFillSkipped > 0) {
258
+ manager.logger?.log?.(`Startup: ${type.toUpperCase()} pick skipped ${lastFillSkipped} slot(s) on the wrong side of the last fill ` +
259
+ `(pivot ${lastFillPivot == null ? 'n/a' : Format.formatPrice6(lastFillPivot)}); picked ${valid.length}/${count}`, 'debug');
260
+ }
240
261
  return valid;
241
262
  }
242
263
  /**
@@ -482,6 +503,21 @@ async function _createOrderFromGrid({ chainOrders, account, privateKey, manager,
482
503
  `@${Format.formatPrice6(crossed.price ?? crossed.order?.price ?? 0)}`, 'warn');
483
504
  return null;
484
505
  }
506
+ // LAST-FILL GUARD: never place a BUY on/above the price that just traded,
507
+ // nor a SELL on/below it (same level included — see
508
+ // isLastFillPlacementBlocked). The COW planner has this discipline; the
509
+ // reconcile/startup create path did not, so a top-up could re-create the
510
+ // level it had just bought at (live: 19 of 37 creates at an already-filled
511
+ // level, 9 of them above the previous fill). Refusing here fails closed to
512
+ // the next reconcile cycle, when the crawl has moved the rail.
513
+ const fillGuard = isLastFillPlacementBlocked(manager, createPrice, gridOrder.type);
514
+ if (fillGuard.blocked) {
515
+ manager.logger?.log?.(`[_createOrderFromGrid] SKIP (LAST-FILL-GUARD): Create for ${gridOrder.id} at ` +
516
+ `${Format.formatPrice6(createPrice)} on the wrong side of the last fill ` +
517
+ `${Format.formatPrice6(Number(fillGuard.pivot))} (${fillGuard.reason}); ` +
518
+ `the rail must crawl before this level is refilled`, 'warn');
519
+ return null;
520
+ }
485
521
  // Price collision guard: reject if another placed order already exists at this price level.
486
522
  const priceCollision = computePlacementPriceCollision(manager, gridOrder);
487
523
  if (priceCollision) {
@@ -760,11 +796,30 @@ function _prepareStartupUpdatePlan(plan, manager, logger) {
760
796
  `re-align on the next reconcile cycle.`, 'warn');
761
797
  return null;
762
798
  }
799
+ // LAST-FILL GUARD: a relocation re-prices a live order onto a different
800
+ // level, so it is a placement and obeys the same direction rule as a
801
+ // create (BUY lower, SELL higher; never the level that just traded). A
802
+ // same-price relocation is an ADOPTION (the chain order already rests at
803
+ // the target level), not a placement — it is left alone.
804
+ const parsedChainOrder = parseChainOrder(plan.chainOrderObj, manager.assets);
805
+ const chainPrice = Number(parsedChainOrder?.price);
806
+ const samePriceAdoption = Number.isFinite(chainPrice)
807
+ && pricesWithinHalfStep(chainPrice, Number(gridOrder.price), manager.config?.incrementPercent);
808
+ if (!samePriceAdoption) {
809
+ const fillGuard = isLastFillPlacementBlocked(manager, gridOrder.price, gridOrder.type);
810
+ if (fillGuard.blocked) {
811
+ logger?.log?.(`[STARTUP-LAST-FILL-GUARD] Skipping relocation update ${chainOrderId} -> ${gridOrder.id}: ` +
812
+ `target ${gridOrder.type} @${Format.formatPrice6(gridOrder.price)} is on the wrong side of the ` +
813
+ `last fill ${Format.formatPrice6(Number(fillGuard.pivot))} (${fillGuard.reason}); ` +
814
+ `re-align on the next reconcile cycle.`, 'warn');
815
+ return null;
816
+ }
817
+ }
763
818
  return {
764
819
  plan,
765
820
  chainOrderId,
766
821
  gridOrder,
767
- parsedChain: parseChainOrder(plan.chainOrderObj, manager.assets),
822
+ parsedChain: parsedChainOrder,
768
823
  updateParams: {
769
824
  newPrice: gridOrder.price,
770
825
  amountToSell,
@@ -1151,6 +1206,16 @@ async function _executeStartupCreateGroupBatch({ group, chainOrders, account, pr
1151
1206
  `@${Format.formatPrice6(crossed.price ?? crossed.order?.price ?? 0)}`, 'warn');
1152
1207
  continue;
1153
1208
  }
1209
+ // LAST-FILL GUARD: creates only — never restore a level on the wrong
1210
+ // side of the last fill (includes the level that just traded). See
1211
+ // isLastFillPlacementBlocked.
1212
+ const fillGuard = isLastFillPlacementBlocked(manager, createPrice, gridOrder.type);
1213
+ if (fillGuard.blocked) {
1214
+ logger?.log?.(`Startup: Skip create ${plan.orderLabel} (LAST-FILL-GUARD) - price ` +
1215
+ `${Format.formatPrice6(createPrice)} is on the wrong side of the last fill ` +
1216
+ `${Format.formatPrice6(Number(fillGuard.pivot))} (${fillGuard.reason})`, 'warn');
1217
+ continue;
1218
+ }
1154
1219
  const { amountToSell, sellAssetId, minToReceive, receiveAssetId } = buildCreateOrderArgs(gridOrder, manager.assets.assetA, manager.assets.assetB);
1155
1220
  // GRID-PRICE-INVARIANT (blocking): see docs/GRID_PRICE_INVARIANT.md.
1156
1221
  if (!reportGridPriceInvariant(manager, gridOrder?.id, gridOrder?.price, 'STARTUP-CREATE')) {
@@ -1608,17 +1673,31 @@ async function _reconcileStartupSide({ orderType, targetCount, chainSideOrders,
1608
1673
  catch { /* fail-open: keep unfiltered count */ }
1609
1674
  const createCount = Math.max(0, targetCount - chainCount);
1610
1675
  const remainingSlots = desiredSlots.slice(updateCount);
1611
- for (let i = 0; i < Math.min(createCount, remainingSlots.length); i++) {
1612
- const gridOrder = remainingSlots[i];
1613
- logger?.log?.(`Startup: Creating ${sideUpper} for grid ${gridOrder.id} (price=${Format.formatPrice6(gridOrder.price)}, size=${Format.formatSizeByOrderType(gridOrder.size, orderType, manager.assets)})`, 'info');
1614
- plannedCreates.push({
1615
- orderType,
1616
- gridOrder,
1617
- orderLabel: sideUpper,
1618
- // Intentionally no recovery metadata here.
1619
- // This preserves legacy behavior: regular virtual-slot creates only log failures,
1620
- // while cancelled-slot replacement creates trigger a startup recovery sync.
1621
- });
1676
+ // UNSETTLED-FILL GATE: while fills are queued, draining, in flight, or
1677
+ // owed a crawl, the master still treats filled slots as ACTIVE and the
1678
+ // boundary has not crawled for them. Any window top-up derived from that
1679
+ // geometry refills the EXPENSIVE end of the rail — the live incident
1680
+ // (12s of buys at 1282.78 -> 1310.04 while the market was ~1280). Defer
1681
+ // the top-up to the cycle after the fills (and their crawl) are committed;
1682
+ // 1:1 repairs (cancelled-slot replacement, vacated-rail refill) still run.
1683
+ const unsettled = hasUnsettledFills(manager);
1684
+ if (unsettled.unsettled && createCount > 0) {
1685
+ logger?.log?.(`Startup: Deferring ${Math.min(createCount, remainingSlots.length)} ${sideUpper} window top-up create(s): ` +
1686
+ `${unsettled.reason} — the rail must absorb the fills before it is refilled`, 'warn');
1687
+ }
1688
+ else {
1689
+ for (let i = 0; i < Math.min(createCount, remainingSlots.length); i++) {
1690
+ const gridOrder = remainingSlots[i];
1691
+ logger?.log?.(`Startup: Creating ${sideUpper} for grid ${gridOrder.id} (price=${Format.formatPrice6(gridOrder.price)}, size=${Format.formatSizeByOrderType(gridOrder.size, orderType, manager.assets)})`, 'info');
1692
+ plannedCreates.push({
1693
+ orderType,
1694
+ gridOrder,
1695
+ orderLabel: sideUpper,
1696
+ // Intentionally no recovery metadata here.
1697
+ // This preserves legacy behavior: regular virtual-slot creates only log failures,
1698
+ // while cancelled-slot replacement creates trigger a startup recovery sync.
1699
+ });
1700
+ }
1622
1701
  }
1623
1702
  // Guard: when the matcher found zero active grid orders (matchedOnGrid === 0)
1624
1703
  // AND we're actively scaling up (neededSlots > 0), the grid is freshly
@@ -86,7 +86,11 @@ declare const utils: {
86
86
  } | null;
87
87
  }): system.SpreadCorrectionReadiness;
88
88
  resolveSpreadMarketReference(manager: import("../types.js").OrderManagerLike): number | null;
89
- reanchorBoundaryFromLastFill(manager: import("../types.js").OrderManagerLike, boundaryIdx: number | null | undefined, slots: import("../types.js").ManagedOrder[] | null | undefined, gapSlots: number): {
89
+ reanchorBoundaryFromLastFill(manager: import("../types.js").OrderManagerLike, boundaryIdx: number | null | undefined, slots: import("../types.js").ManagedOrder[] | null | undefined, gapSlots: number, fills?: Array<{
90
+ id?: string;
91
+ type?: string;
92
+ price?: unknown;
93
+ }> | null | undefined): {
90
94
  boundaryIdx: number | null;
91
95
  reanchored: boolean;
92
96
  from?: number | null;
@@ -95,18 +99,28 @@ declare const utils: {
95
99
  fillSlot?: number;
96
100
  reason?: string;
97
101
  };
98
- resolveLastFillGuardReference(manager: import("../types.js").OrderManagerLike): {
102
+ resolveLastFillGuardReference(manager: import("../types.js").OrderManagerLike | null | undefined): {
99
103
  price: number | null;
100
104
  type: string | null;
101
105
  };
102
- isLastFillGuardBlocked(price: number, _size: number, type: unknown, lastPrice: number | null, lastType: string | null, _incrementPercent?: number): {
106
+ isLastFillGuardBlocked(price: number, type: unknown, lastPrice: number | null, lastType: string | null): {
103
107
  blocked: boolean;
104
108
  pivot: number | null;
105
109
  threshold?: number | null;
106
110
  };
111
+ isLastFillPlacementBlocked(manager: import("../types.js").OrderManagerLike | null | undefined, price: unknown, type: unknown): {
112
+ blocked: boolean;
113
+ pivot: number | null;
114
+ reason?: "direction" | "same-level";
115
+ };
116
+ hasUnsettledFills(source: unknown): {
117
+ unsettled: boolean;
118
+ reason: string | null;
119
+ };
107
120
  restoreLastMarketFill(manager: import("../types.js").OrderManagerLike, persisted: unknown, options?: {
108
121
  now?: number;
109
122
  }): boolean;
123
+ rearmLastFillPivotFromMarketFill(manager: import("../types.js").OrderManagerLike): boolean;
110
124
  normalizeLastFillPivot(row: unknown): {
111
125
  price: number;
112
126
  type: string;
@@ -191,7 +205,12 @@ declare const utils: {
191
205
  reason?: string;
192
206
  };
193
207
  parseChainOrder: typeof order.parseChainOrder;
208
+ resolveLiveOrderLadderPosition: typeof order.resolveLiveOrderLadderPosition;
194
209
  applyChainSizeToGridOrder: typeof order.applyChainSizeToGridOrder;
210
+ resolveExecutionPrice: typeof order.resolveExecutionPrice;
211
+ resolveSlotIdForFillPrice: typeof order.resolveSlotIdForFillPrice;
212
+ reviveVirtualSlotFromChain: typeof order.reviveVirtualSlotFromChain;
213
+ attributeUnmatchedFillToGrid: typeof order.attributeUnmatchedFillToGrid;
195
214
  buildFillKey: typeof order.buildFillKey;
196
215
  correctOrderPriceOnChain: typeof order.correctOrderPriceOnChain;
197
216
  correctAllPriceMismatches: typeof order.correctAllPriceMismatches;
@@ -213,7 +232,6 @@ declare const utils: {
213
232
  crossingCandidateChainId: typeof order.crossingCandidateChainId;
214
233
  isCrossingCheckCandidate: typeof order.isCrossingCheckCandidate;
215
234
  buildCrossingCheckCandidates: typeof order.buildCrossingCheckCandidates;
216
- parseSlotIndex: typeof order.parseSlotIndex;
217
235
  filterOrdersByType: typeof order.filterOrdersByType;
218
236
  buildOutsideInPairGroups: typeof order.buildOutsideInPairGroups;
219
237
  extractBatchOperationResults: typeof order.extractBatchOperationResults;
@@ -254,6 +272,7 @@ declare const utils: {
254
272
  chainOrderUnchangedFromCache: typeof order.chainOrderUnchangedFromCache;
255
273
  detectCrossedBookPlan: typeof order.detectCrossedBookPlan;
256
274
  collectKnownOnChainOrderIds: typeof order.collectKnownOnChainOrderIds;
275
+ collectEdgePinnedFillIds: typeof order.collectEdgePinnedFillIds;
257
276
  edgeOrderIdSet: typeof order.edgeOrderIdSet;
258
277
  liveWindowIdSet: typeof order.liveWindowIdSet;
259
278
  checkGridPriceInvariant: typeof order.checkGridPriceInvariant;
@@ -340,6 +359,7 @@ declare const utils: {
340
359
  priceSlotEqual: typeof math.priceSlotEqual;
341
360
  derivePriceLevels: typeof math.derivePriceLevels;
342
361
  sameGridLevel: typeof math.sameGridLevel;
362
+ pricesWithinHalfStep: typeof math.pricesWithinHalfStep;
343
363
  buildGenesisFromPriceLevels: typeof math.buildGenesisFromPriceLevels;
344
364
  hashPriceLevels: typeof math.hashPriceLevels;
345
365
  isChainPriceOutOfGrid: typeof math.isChainPriceOutOfGrid;
@@ -219,6 +219,8 @@ declare class OrderManager implements OrderManagerLike {
219
219
  _lastFilledPrice: number | null;
220
220
  _lastFilledType: string | null;
221
221
  _lastFilledAt: number;
222
+ /** Timestamp of the fill reference whose read-time expiry was already logged (one line per expired value). */
223
+ _lastFillPivotExpiryLoggedAt: number;
222
224
  lastFillPivotSource: 'fill' | 'book' | null;
223
225
  _lastMarketFillPrice: number | null;
224
226
  _lastMarketFillType: string | null;
@@ -759,6 +761,16 @@ declare class OrderManager implements OrderManagerLike {
759
761
  * discriminator (null => disabled). The per-side fields are not read by the
760
762
  * guard itself; they feed the book-seed cold-check and per-side seeding in
761
763
  * seedLastFilledPricesFromBook.
764
+ *
765
+ * EDGE-PINNED FILLS ARE SKIPPED. An edge order is static fat-finger
766
+ * insurance resting at the grid floor/ceiling, not market movement: the
767
+ * boundary crawl already excludes its fills, and the pivot doubles as the
768
+ * geometry anchor for reanchorBoundaryFromLastFill. Letting a wick on an
769
+ * edge order arm the pivot at a rail-edge price would both veto that whole
770
+ * side of the book and (as an absolute anchor) teleport the window to the
771
+ * edge. Skipping keeps the reference on the last WINDOW trade, matching
772
+ * the crawl's classification (collectEdgePinnedFillIds is the shared
773
+ * definition).
762
774
  * @param {Array} fills
763
775
  */
764
776
  recordLastFilledPrices(fills: COWFillLike[]): void;
@@ -30,7 +30,8 @@ import { ORDER_TYPES, ORDER_STATES, REBALANCE_STATES, TIMING, LOG_LEVEL, PIPELIN
30
30
  import { seedBotRuntimeConfig, createDefaultBotMetrics } 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, resolveEdgeCount, resolveLiveEdgeAnchorPrice, compareEdge, collectRefillSlotIds, recordOrderPlacement, isFreshlyPlacedOrder } from './utils/order.js';
33
+ import { resolveSpreadOrderSide, resolveLiveOrderLadderPosition, parseChainOrder, geometryTypeForSlotIndex, isOrderOnChain, resolveEdgeCount, resolveLiveEdgeAnchorPrice, compareEdge, collectRefillSlotIds, recordOrderPlacement, isFreshlyPlacedOrder, collectEdgePinnedFillIds } from './utils/order.js';
34
+ import { parseSlotIndex } from './utils/slot.js';
34
35
  import { getErrorMessage, getErrorCode } from '../utils/errors.js';
35
36
  const { toFiniteNumber } = Format;
36
37
  function stalePlacementDropReason(action, planBoundary) {
@@ -139,7 +140,8 @@ class COWRebalanceEngine {
139
140
  dustThresholdPercent,
140
141
  gapSlots: gapSlots ?? undefined,
141
142
  evacStreaks: evacStreaks ?? undefined,
142
- assets: this.assets
143
+ assets: this.assets,
144
+ genesis: manager?._genesis ?? null
143
145
  });
144
146
  // Gap-evacuation telemetry: evacReady is the streak-tick output of
145
147
  // reconcileGrid (stuck in-band candidates). It must survive both
@@ -434,6 +436,8 @@ class OrderManager {
434
436
  _lastFilledPrice;
435
437
  _lastFilledType;
436
438
  _lastFilledAt;
439
+ /** Timestamp of the fill reference whose read-time expiry was already logged (one line per expired value). */
440
+ _lastFillPivotExpiryLoggedAt;
437
441
  lastFillPivotSource;
438
442
  // Bot-scoped "last market fill" reference. Unlike the genesis-bound
439
443
  // LAST-FILL-GUARD pivot (reset with the grid generation), this survives a
@@ -582,6 +586,7 @@ class OrderManager {
582
586
  this._lastFilledPrice = null;
583
587
  this._lastFilledType = null;
584
588
  this._lastFilledAt = 0;
589
+ this._lastFillPivotExpiryLoggedAt = 0;
585
590
  // Pivot provenance for the LAST-FILL-GUARD persist/restore contract:
586
591
  // 'fill' = armed by a real fill (persist-eligible), 'book' = armed by
587
592
  // the startup book seed (heuristic, in-memory only), null = unarmed.
@@ -1897,17 +1902,33 @@ class OrderManager {
1897
1902
  * discriminator (null => disabled). The per-side fields are not read by the
1898
1903
  * guard itself; they feed the book-seed cold-check and per-side seeding in
1899
1904
  * seedLastFilledPricesFromBook.
1905
+ *
1906
+ * EDGE-PINNED FILLS ARE SKIPPED. An edge order is static fat-finger
1907
+ * insurance resting at the grid floor/ceiling, not market movement: the
1908
+ * boundary crawl already excludes its fills, and the pivot doubles as the
1909
+ * geometry anchor for reanchorBoundaryFromLastFill. Letting a wick on an
1910
+ * edge order arm the pivot at a rail-edge price would both veto that whole
1911
+ * side of the book and (as an absolute anchor) teleport the window to the
1912
+ * edge. Skipping keeps the reference on the last WINDOW trade, matching
1913
+ * the crawl's classification (collectEdgePinnedFillIds is the shared
1914
+ * definition).
1900
1915
  * @param {Array} fills
1901
1916
  */
1902
1917
  recordLastFilledPrices(fills) {
1903
1918
  if (!Array.isArray(fills) || fills.length === 0)
1904
1919
  return;
1920
+ const edgeFillIds = collectEdgePinnedFillIds(this, fills);
1905
1921
  let recorded = 0;
1922
+ let skippedEdge = 0;
1906
1923
  let lastKind = 'unknown';
1907
1924
  let lastPriceSrc = 'direct';
1908
1925
  for (const f of fills) {
1909
1926
  if (!f || (f.type !== ORDER_TYPES.BUY && f.type !== ORDER_TYPES.SELL))
1910
1927
  continue;
1928
+ if (f.id != null && edgeFillIds.has(String(f.id))) {
1929
+ skippedEdge++;
1930
+ continue;
1931
+ }
1911
1932
  let price = Number(f.price ?? f.order?.price);
1912
1933
  let priceSrc = 'direct';
1913
1934
  if (!Number.isFinite(price) || price <= 0) {
@@ -1937,7 +1958,14 @@ class OrderManager {
1937
1958
  const fmt = (v) => (v == null || !Number.isFinite(Number(v)) ? 'none' : Format.formatPrice6(Number(v)));
1938
1959
  this.logger?.log?.(`[FILL-PIVOT] pivot=${fmt(this._lastFilledPrice)}(${this._lastFilledType}) ` +
1939
1960
  `buy=${fmt(this._lastFilledBuyPrice)} sell=${fmt(this._lastFilledSellPrice)} ` +
1940
- `n=${recorded} src=${lastKind}/${lastPriceSrc}`, 'info');
1961
+ `n=${recorded} src=${lastKind}/${lastPriceSrc}` +
1962
+ `${skippedEdge > 0 ? ` edge-skipped=${skippedEdge}` : ''}`, 'info');
1963
+ }
1964
+ catch { /* logging is best-effort */ }
1965
+ }
1966
+ else if (skippedEdge > 0) {
1967
+ try {
1968
+ this.logger?.log?.(`[FILL-PIVOT] ${skippedEdge} edge-pinned fill(s) ignored — the guard pivot and the boundary anchor stay on the last window trade`, 'info');
1941
1969
  }
1942
1970
  catch { /* logging is best-effort */ }
1943
1971
  }
@@ -2143,7 +2171,8 @@ class OrderManager {
2143
2171
  dustThresholdPercent: this.config?.gridLimits?.PARTIAL_DUST_THRESHOLD_PERCENTAGE,
2144
2172
  gapSlots: this._gapSlots,
2145
2173
  evacStreaks: this._gapEvacStreaks,
2146
- assets: this.assets
2174
+ assets: this.assets,
2175
+ genesis: this._genesis ?? null
2147
2176
  });
2148
2177
  }
2149
2178
  /**
@@ -2197,9 +2226,17 @@ class OrderManager {
2197
2226
  const chainOrderId = candidate?.orderId;
2198
2227
  if (!slotId || !chainOrderId)
2199
2228
  continue;
2200
- // 1. Re-verify geometry against the CURRENT committed boundary.
2201
- const idx = parseSlotIndex(slotId);
2202
- if (idx === null || geometryTypeForSlotIndex(idx, boundary, gapSlots) !== ORDER_TYPES.SPREAD)
2229
+ // 1. Live slot check + geometry re-verification against the CURRENT
2230
+ // committed boundary. Prefer the order's LIVE chain price: a
2231
+ // refused-commit adoption can leave the local slot id in-rail while
2232
+ // the order actually rests inside the band.
2233
+ const slot = this.orders.get(slotId);
2234
+ if (!slot || !isOrderOnChain(slot) || slot.orderId !== chainOrderId)
2235
+ continue;
2236
+ const live = resolveLiveOrderLadderPosition(slot, this.assets, this._genesis);
2237
+ // Unknown ladder position is not evidence of an in-band order.
2238
+ if (live.idx === null || !Number.isFinite(Number(live.idx))
2239
+ || geometryTypeForSlotIndex(live.idx, boundary, gapSlots) !== ORDER_TYPES.SPREAD)
2203
2240
  continue;
2204
2241
  // 2. Act threshold (stricter than the warn threshold).
2205
2242
  if (Number(this._gapEvacStreaks.get(slotId) || 0) < cancelThreshold)
@@ -2209,10 +2246,6 @@ class OrderManager {
2209
2246
  continue;
2210
2247
  if (this.ordersNeedingPriceCorrection.some((entry) => entry?.chainOrderId === chainOrderId))
2211
2248
  continue;
2212
- // 5. Live slot check.
2213
- const slot = this.orders.get(slotId);
2214
- if (!slot || !isOrderOnChain(slot) || slot.orderId !== chainOrderId)
2215
- continue;
2216
2249
  this.ordersNeedingPriceCorrection.push({
2217
2250
  gridOrder: { ...slot },
2218
2251
  chainOrderId,
@@ -52,7 +52,8 @@ import { isSlotInRail } from './utils/math.js';
52
52
  import { deriveTargetBoundary, getSideBudget, calculateBudgetedSizes, getCoreOrdersTotal, resolveEdgeCount, resolveLiveEdgeAnchorPrice, selectEdgeSlots, isShiftEligibleFill } from './utils/order.js';
53
53
  import { reanchorBoundaryFromLastFill } from './utils/system.js';
54
54
  import { assignGridRoles } from './utils/order.js';
55
- import { convertToSpreadPlaceholder, toRailHolePlaceholder, geometryTypeForSlotIndex, parseSlotIndex, hasOnChainId, isOrderPlaced } from "./utils/order.js";
55
+ import { convertToSpreadPlaceholder, toRailHolePlaceholder, geometryTypeForSlotIndex, hasOnChainId, isOrderPlaced } from "./utils/order.js";
56
+ import { parseSlotIndex } from "./utils/slot.js";
56
57
  class StrategyEngine {
57
58
  manager;
58
59
  /**
@@ -271,9 +272,28 @@ class StrategyEngine {
271
272
  // inventory. The fill is the anchor: place it outside its own window.
272
273
  // Validated like a boundary commit (strands no live in-band order), and
273
274
  // only for an on-ladder fill price.
274
- const reanchor = reanchorBoundaryFromLastFill(this.manager, newBoundaryIdx, allSlots, gapSlots);
275
+ const reanchor = reanchorBoundaryFromLastFill(this.manager, newBoundaryIdx, allSlots, gapSlots, fills);
275
276
  if (reanchor.reanchored) {
276
277
  newBoundaryIdx = reanchor.boundaryIdx;
278
+ // An absolute fill anchor already reflects every older owed crawl.
279
+ // The derivation may have left records owed (cap exhausted, mixed
280
+ // remainder), so consuming only its subset would let a later
281
+ // derivation apply those deltas ON TOP of the re-anchored boundary
282
+ // and overshoot. Snapshot at PLAN time (not commit time): a fill
283
+ // recorded after this plan must stay owed and crawl next cycle.
284
+ const pendingAtPlan = Array.isArray(this.manager._pendingFillCrawls)
285
+ ? this.manager._pendingFillCrawls
286
+ : [];
287
+ consumedCrawlIds = pendingAtPlan
288
+ .filter((e) => e && typeof e.slotId === 'string' && e.slotId.length > 0)
289
+ .map((e) => {
290
+ const ts = Number(e.ts);
291
+ return {
292
+ slotId: e.slotId,
293
+ side: String(e.side ?? ''),
294
+ ...(Number.isFinite(ts) ? { ts } : {})
295
+ };
296
+ });
277
297
  try {
278
298
  this.manager._markGridDirty?.();
279
299
  }
@@ -141,6 +141,16 @@ interface FillTransitionParams {
141
141
  blockNum?: number;
142
142
  historyId?: string;
143
143
  isMaker: boolean;
144
+ /**
145
+ * Execution price (quote per base) from the chain fill / chain order, when
146
+ * known. The fill record must carry the REAL trade price: `matchedGridOrder`
147
+ * is keyed by slot, and a refused-commit adoption can leave that slot at a
148
+ * stale generation price (e.g. slot-118 @1267 while the chain order traded
149
+ * at 1345.7). The last-fill pivot / re-anchor read this field, never the
150
+ * slot price. The slot's own identity price is intentionally NOT rewritten
151
+ * (GRID-PRICE-INVARIANT).
152
+ */
153
+ fillPrice?: number | null;
144
154
  }
145
155
  interface SyncChainData {
146
156
  gridOrderId?: string;
@@ -290,7 +300,27 @@ declare class SyncEngine {
290
300
  unmatchedChainOrders: UnmatchedChainOrder[];
291
301
  }>;
292
302
  _findMatchingGridOrder(mgr: OrderManagerLike, orderId: string | null | undefined): ManagedOrder | null;
293
- _computeFillContext(mgr: OrderManagerLike, matchedGridOrder: ManagedOrder, paysAssetId: string | null | undefined, paysAmountRaw: number): {
303
+ /**
304
+ * Absorb a fill whose order id has no ACTIVE/PARTIAL slot ("order not found
305
+ * in active grid").
306
+ *
307
+ * Thin wrapper over the shared `attributeUnmatchedFillToGrid` helper (see
308
+ * utils/order.ts for the two identities and the incident it closes). The
309
+ * work lives outside this class so the orphan-credit path in
310
+ * dexbot_fill_runtime.ts attributes fills with literally the same rule
311
+ * instead of keeping a second, weaker copy.
312
+ *
313
+ * @returns {boolean} true when the fill was attributed to the grid.
314
+ */
315
+ _absorbUnmatchedFill(mgr: OrderManagerLike, params: {
316
+ orderId: string | null | undefined;
317
+ paysAssetId?: string | null;
318
+ paysAmountRaw?: unknown;
319
+ receivesAssetId?: string | null;
320
+ receivesAmountRaw?: unknown;
321
+ isPartial?: boolean;
322
+ }): boolean;
323
+ _computeFillContext(mgr: OrderManagerLike, matchedGridOrder: ManagedOrder, paysAssetId: string | null | undefined, paysAmountRaw: number, receivesAssetId?: string | null | undefined, receivesAmountRaw?: number | null): {
294
324
  orderType: OrderType;
295
325
  currentSize: number;
296
326
  precision: number;
@@ -298,6 +328,7 @@ declare class SyncEngine {
298
328
  currentSizeIntFromGrid: number;
299
329
  rawForSaleInt: number;
300
330
  driftSignal: boolean;
331
+ fillPrice: number | null;
301
332
  };
302
333
  _computeFillTransitionResult(mgr: OrderManagerLike, params: FillTransitionParams): Promise<{
303
334
  isFull: boolean;