dexbot 1.6.16 → 1.6.18

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 (124) hide show
  1. package/CHANGELOG.md +58 -0
  2. package/analysis/README.md +10 -9
  3. package/analysis/ama_fitting/README.md +2 -2
  4. package/analysis/bot_fitting/README.md +3 -3
  5. package/analysis/tradingview/README.md +2 -2
  6. package/analysis/trend_detection/DYNAMIC_WEIGHT_RESEARCH.md +1 -1
  7. package/claw/package.json +1 -1
  8. package/claw/runtimes/openclaw-plugin/openclaw.plugin.json +1 -1
  9. package/claw/runtimes/openclaw-plugin/package.json +1 -1
  10. package/dist/analysis/ama_fitting/analyze_lambda_vs_slow.js +5 -3
  11. package/dist/analysis/analyze_args.d.ts +2 -1
  12. package/dist/analysis/fills_source.d.ts +1 -8
  13. package/dist/analysis/fills_source.js +1 -1
  14. package/dist/analysis/grid_correction_check.d.ts +9 -6
  15. package/dist/analysis/grid_correction_check.js +56 -64
  16. package/dist/analysis/math_utils.d.ts +1 -1
  17. package/dist/analysis/trade_profitability.d.ts +1 -1
  18. package/dist/analysis/tradingview/grid_reset_sim.js +1 -1
  19. package/dist/analysis/tradingview/tradingview_uplot_chart_generator.js +7 -7
  20. package/dist/analysis/trend_detection/backtest_ama_slope_huber.js +1 -1
  21. package/dist/analysis/trend_detection/huber_scale_variants.d.ts +4 -3
  22. package/dist/market_adapter/cli_args.d.ts +6 -1
  23. package/dist/market_adapter/cli_args.js +16 -2
  24. package/dist/market_adapter/core/kibana_candles.d.ts +5 -1
  25. package/dist/market_adapter/core/kibana_candles.js +3 -1
  26. package/dist/market_adapter/core/strategies/regime_gate.d.ts +7 -1
  27. package/dist/market_adapter/core/strategies/regime_gate.js +3 -1
  28. package/dist/market_adapter/inputs/cex_candle_parsing.d.ts +7 -2
  29. package/dist/market_adapter/inputs/cex_candle_parsing.js +3 -1
  30. package/dist/market_adapter/inputs/fetch_book_data.d.ts +7 -1
  31. package/dist/market_adapter/inputs/fetch_book_data.js +3 -1
  32. package/dist/market_adapter/inputs/fetch_cex_synthetic_data.js +2 -11
  33. package/dist/market_adapter/inputs/fetch_lp_data.d.ts +26 -1
  34. package/dist/market_adapter/inputs/fetch_lp_data.js +62 -52
  35. package/dist/market_adapter/inputs/kibana_feed_source.d.ts +14 -2
  36. package/dist/market_adapter/inputs/kibana_feed_source.js +14 -1
  37. package/dist/market_adapter/inputs/window_cache.d.ts +14 -3
  38. package/dist/market_adapter/inputs/window_cache.js +14 -1
  39. package/dist/market_adapter/lp_chart_runner.d.ts +12 -9
  40. package/dist/market_adapter/lp_chart_runner.js +3 -1
  41. package/dist/market_adapter/lp_chart_strategy_loader.d.ts +5 -1
  42. package/dist/market_adapter/lp_chart_strategy_loader.js +3 -1
  43. package/dist/market_adapter/market_adapter.d.ts +10 -2
  44. package/dist/market_adapter/market_adapter.js +10 -11
  45. package/dist/market_adapter/utils/chain.d.ts +2 -3
  46. package/dist/market_adapter/utils/file_json_cache.d.ts +5 -1
  47. package/dist/market_adapter/utils/file_json_cache.js +3 -1
  48. package/dist/market_adapter/utils/file_lock.js +1 -1
  49. package/dist/market_adapter/utils/native_history.d.ts +7 -3
  50. package/dist/market_adapter/utils/native_history.js +3 -1
  51. package/dist/market_adapter/utils/pair_orientation.d.ts +2 -2
  52. package/dist/modules/account_bots.d.ts +3 -0
  53. package/dist/modules/bots_file_lock.d.ts +2 -2
  54. package/dist/modules/bots_file_lock.js +2 -2
  55. package/dist/modules/chain_keys.d.ts +1 -1
  56. package/dist/modules/constants.d.ts +6 -0
  57. package/dist/modules/constants.js +37 -6
  58. package/dist/modules/credit_pricing.d.ts +20 -1
  59. package/dist/modules/credit_pricing.js +23 -1
  60. package/dist/modules/credit_runtime.js +33 -16
  61. package/dist/modules/dexbot_class.d.ts +11 -1
  62. package/dist/modules/dexbot_class.js +15 -2
  63. package/dist/modules/dexbot_cow_runtime.d.ts +90 -38
  64. package/dist/modules/dexbot_cow_runtime.js +507 -108
  65. package/dist/modules/dexbot_credential_client.d.ts +5 -0
  66. package/dist/modules/dexbot_maintenance_runtime.js +117 -12
  67. package/dist/modules/dexbot_startup_runtime.js +7 -1
  68. package/dist/modules/graceful_shutdown.d.ts +2 -2
  69. package/dist/modules/graceful_shutdown.js +2 -2
  70. package/dist/modules/launcher/credential_daemon.d.ts +14 -2
  71. package/dist/modules/launcher/credential_daemon.js +60 -26
  72. package/dist/modules/launcher/runtime_mode.d.ts +4 -3
  73. package/dist/modules/node_manager.d.ts +1 -1
  74. package/dist/modules/node_manager.js +1 -1
  75. package/dist/modules/order/accounting.js +2 -1
  76. package/dist/modules/order/export.d.ts +2 -2
  77. package/dist/modules/order/export.js +2 -2
  78. package/dist/modules/order/grid.d.ts +26 -14
  79. package/dist/modules/order/grid.js +416 -73
  80. package/dist/modules/order/grid_reconcile.js +5 -1
  81. package/dist/modules/order/grid_reconcile_internal.js +2 -1
  82. package/dist/modules/order/index.d.ts +22 -1
  83. package/dist/modules/order/manager.d.ts +40 -7
  84. package/dist/modules/order/manager.js +149 -23
  85. package/dist/modules/order/strategy.d.ts +5 -0
  86. package/dist/modules/order/strategy.js +44 -3
  87. package/dist/modules/order/sync_engine.d.ts +12 -1
  88. package/dist/modules/order/sync_engine.js +135 -20
  89. package/dist/modules/order/utils/math.d.ts +49 -10
  90. package/dist/modules/order/utils/math.js +71 -14
  91. package/dist/modules/order/utils/order.d.ts +65 -11
  92. package/dist/modules/order/utils/order.js +198 -28
  93. package/dist/modules/order/utils/system.d.ts +112 -2
  94. package/dist/modules/order/utils/system.js +338 -12
  95. package/dist/modules/order/utils/validate.d.ts +4 -1
  96. package/dist/modules/order/utils/validate.js +9 -2
  97. package/dist/modules/storage/index.d.ts +3 -2
  98. package/dist/modules/storage/index.js +3 -2
  99. package/dist/modules/types.d.ts +44 -2
  100. package/dist/scripts/analyze-credit.js +64 -23
  101. package/dist/scripts/bts_distribution.d.ts +66 -0
  102. package/dist/scripts/bts_distribution.js +2102 -0
  103. package/dist/scripts/token_distribution.d.ts +45 -0
  104. package/dist/scripts/token_distribution.js +1870 -0
  105. package/dist/unlock.js +42 -24
  106. package/docs/COPY_ON_WRITE_MASTER_PLAN.md +1 -1
  107. package/docs/COW_INVARIANTS.md +24 -8
  108. package/docs/DEXBOT_COMPARISON.md +5 -5
  109. package/docs/EVOLUTION.md +10 -8
  110. package/docs/FUND_MOVEMENT_AND_ACCOUNTING.md +13 -11
  111. package/docs/GRID_PRICE_INVARIANT.md +29 -3
  112. package/docs/GRID_RECALCULATION.md +3 -3
  113. package/docs/GRID_RECONCILE.md +5 -5
  114. package/docs/LIFECYCLE.md +11 -11
  115. package/docs/LOGGING.md +22 -0
  116. package/docs/MPA_CREDIT_USAGE.md +3 -2
  117. package/docs/ORDER_ENGINE_POST_1.0_RETROSPECTIVE.md +236 -32
  118. package/docs/README.md +1 -1
  119. package/docs/architecture.md +205 -6
  120. package/docs/developer_guide.md +12 -0
  121. package/market_adapter/README.md +11 -6
  122. package/modules/README.md +18 -14
  123. package/package.json +6 -3
  124. package/scripts/README.md +85 -148
@@ -65,6 +65,25 @@ declare function borrowAmountForCollateral(collateralAmountInt: unknown, collate
65
65
  * accept op).
66
66
  */
67
67
  declare function capBorrowToCollateral(requestedBorrowInt: unknown, availableCollateralInt: unknown, collateralPrice: OfferPrice | null | undefined, debtAssetId?: string | null, collateralAssetId?: string | null): number | null;
68
+ /**
69
+ * Pick the conversion rate used to value collateral.
70
+ *
71
+ * LP-share collateral is a claim on pool reserves, so its market value comes
72
+ * from the live pool and must win over the credit offer's fixed contract price
73
+ * (which is a haircut that can go stale). Other collateral uses the offer
74
+ * price; the pool rate is only a fallback.
75
+ *
76
+ * Returns the selected rate plus its source, or null/ null when neither is
77
+ * usable.
78
+ */
79
+ declare function selectCollateralConversionRate({ offerRate, poolRate, isLiquidityPoolShare, }: {
80
+ offerRate?: unknown;
81
+ poolRate?: unknown;
82
+ isLiquidityPoolShare?: boolean;
83
+ }): {
84
+ rate: number | null;
85
+ source: 'offer' | 'pool' | null;
86
+ };
68
87
  /**
69
88
  * Per-deal CR from floats plus a conversion rate:
70
89
  * (collateralFloat * rate) / debtFloat.
@@ -94,5 +113,5 @@ declare function dailyOfferFeeRate(offer: {
94
113
  * (repay * feeRate + denom - 1) / denom. Zero when nothing is owed.
95
114
  */
96
115
  declare function creditDealFee(repayAmountInt: unknown, feeRate: unknown, feeDenom: unknown): number;
97
- export { normalizeCollateralMap, creditPriceOrientation, extractOfferConversionRate, collateralValueFromOfferPrice, requiredCollateralForBorrow, borrowAmountForCollateral, capBorrowToCollateral, creditDealCollateralRatio, averageCollateralRatio, dailyOfferFeeRate, creditDealFee, };
116
+ export { normalizeCollateralMap, creditPriceOrientation, extractOfferConversionRate, collateralValueFromOfferPrice, requiredCollateralForBorrow, borrowAmountForCollateral, capBorrowToCollateral, selectCollateralConversionRate, creditDealCollateralRatio, averageCollateralRatio, dailyOfferFeeRate, creditDealFee, };
98
117
  //# sourceMappingURL=credit_pricing.d.ts.map
@@ -179,6 +179,28 @@ function capBorrowToCollateral(requestedBorrowInt, availableCollateralInt, colla
179
179
  return null;
180
180
  return Math.min(requested, budgetBorrow);
181
181
  }
182
+ /**
183
+ * Pick the conversion rate used to value collateral.
184
+ *
185
+ * LP-share collateral is a claim on pool reserves, so its market value comes
186
+ * from the live pool and must win over the credit offer's fixed contract price
187
+ * (which is a haircut that can go stale). Other collateral uses the offer
188
+ * price; the pool rate is only a fallback.
189
+ *
190
+ * Returns the selected rate plus its source, or null/ null when neither is
191
+ * usable.
192
+ */
193
+ function selectCollateralConversionRate({ offerRate, poolRate, isLiquidityPoolShare, }) {
194
+ const offer = positiveOrNull(offerRate);
195
+ const pool = positiveOrNull(poolRate);
196
+ if (isLiquidityPoolShare && pool !== null)
197
+ return { rate: pool, source: 'pool' };
198
+ if (offer !== null)
199
+ return { rate: offer, source: 'offer' };
200
+ if (pool !== null)
201
+ return { rate: pool, source: 'pool' };
202
+ return { rate: null, source: null };
203
+ }
182
204
  /**
183
205
  * Per-deal CR from floats plus a conversion rate:
184
206
  * (collateralFloat * rate) / debtFloat.
@@ -243,5 +265,5 @@ function creditDealFee(repayAmountInt, feeRate, feeDenom) {
243
265
  return 0;
244
266
  return Number(((repay * rate) + denom - 1n) / denom);
245
267
  }
246
- export { normalizeCollateralMap, creditPriceOrientation, extractOfferConversionRate, collateralValueFromOfferPrice, requiredCollateralForBorrow, borrowAmountForCollateral, capBorrowToCollateral, creditDealCollateralRatio, averageCollateralRatio, dailyOfferFeeRate, creditDealFee, };
268
+ export { normalizeCollateralMap, creditPriceOrientation, extractOfferConversionRate, collateralValueFromOfferPrice, requiredCollateralForBorrow, borrowAmountForCollateral, capBorrowToCollateral, selectCollateralConversionRate, creditDealCollateralRatio, averageCollateralRatio, dailyOfferFeeRate, creditDealFee, };
247
269
  //# sourceMappingURL=credit_pricing.js.map
@@ -672,14 +672,32 @@ class CreditRuntime {
672
672
  const cached = positiveOrNull(this.state.positions[posKey]?.creditConversionRate);
673
673
  const cachedAt = this.state.positions[posKey]?.creditConversionRateAt || 0;
674
674
  const cachedIsFresh = cached !== null && (Date.now() - cachedAt) < CREDIT_RATE_MAX_AGE_MS;
675
- // Prefer the offer map (live-offer / owned-offer) — it provides an
676
- // authoritative conversion rate even for LP share collateral that has
677
- // an explicit entry in acceptable_collateral. Only when the offer map
678
- // has no entry for the debt/collateral pair do we fall back to pool
679
- // derivation (reserveA*priceA + reserveB*priceB / supply). This avoids
680
- // re-attempting deriveLiquidityPoolTokenValue on every hourly call
681
- // when a fresh live-offer rate exists and would otherwise log a pool
682
- // failure even though the offer would succeed.
675
+ // LP-share collateral is a claim on pool reserves, so its market value
676
+ // comes from the live pool and must win over the offer's fixed
677
+ // acceptable_collateral price (a contract haircut). This matches the
678
+ // borrow gate in _calculateCollateralValueInDebtAsset(). Other
679
+ // collateral uses the offer map; pool/market pricing is only a
680
+ // fallback for those pairs.
681
+ {
682
+ const debtAsset = await this._resolveAsset(debtAssetId);
683
+ const collateralAsset = await this._resolveAsset(collateralAssetId);
684
+ if (collateralAsset?.for_liquidity_pool && debtAsset?.id) {
685
+ const poolRate = await deriveLiquidityPoolTokenValue(BitShares, String(collateralAsset.id), String(debtAsset.id), 'auto', true).catch((e) => {
686
+ this.log(`credit runtime: pool token rate derivation failed for ${collateralAsset.id}/${debtAsset.id}: ${getErrorMessage(e)}`);
687
+ return null;
688
+ });
689
+ if (poolRate != null && Number.isFinite(poolRate) && poolRate > 0) {
690
+ if (!this.state.positions[posKey])
691
+ this.state.positions[posKey] = {};
692
+ this.state.positions[posKey].creditConversionRate = poolRate;
693
+ this.state.positions[posKey].creditConversionRateAt = Date.now();
694
+ return options.includeSource ? { price: poolRate, source: 'pool-derived' } : poolRate;
695
+ }
696
+ }
697
+ }
698
+ // Non-LP collateral uses the offer map (live-offer / owned-offer) —
699
+ // the offer's acceptable_collateral price is the contract's
700
+ // debt-per-collateral conversion rate.
683
701
  const offerIds = new Set();
684
702
  const deals = Array.isArray(this.state.positions[posKey]?.creditDeals)
685
703
  ? this.state.positions[posKey].creditDeals
@@ -747,14 +765,13 @@ class CreditRuntime {
747
765
  return options.includeSource ? { price: rate, source: 'live-offer' } : rate;
748
766
  }
749
767
  }
750
- // Offer map had no usable entry — fall back to pool derivation for LP
751
- // shares, then to universal DEX pricing (direct market, else bridge
752
- // hops via BTS) so every collateral/debt pair resolves a rate even
753
- // when the collateral or pool is not part of the credit offer.
754
- // Only attempt when cached is stale to avoid hourly
755
- // deriveLiquidityPoolTokenValue failures when a fresh live-offer rate
756
- // would already have returned. Reuses debtAsset/collateralAsset
757
- // resolved above.
768
+ // Offer map had no usable entry (or the LP pool valuation above
769
+ // failed) — fall back to pool derivation for LP shares, then to
770
+ // universal DEX pricing (direct market, else bridge hops via BTS) so
771
+ // every collateral/debt pair resolves a rate even when the collateral
772
+ // or pool is not part of the credit offer. Only attempt when cached is
773
+ // stale to avoid hourly deriveLiquidityPoolTokenValue failures.
774
+ // Reuses debtAsset/collateralAsset resolved above.
758
775
  if (!cachedIsFresh) {
759
776
  if (collateralAsset?.for_liquidity_pool && debtAsset?.id) {
760
777
  const poolRate = await deriveLiquidityPoolTokenValue(BitShares, String(collateralAsset.id), String(debtAsset.id), 'auto', true).catch((e) => {
@@ -185,13 +185,23 @@ declare class DEXBot implements BotLike {
185
185
  _lastHeldChainOrderSignatureSince: number;
186
186
  _lastHeldChainOrderWarnAt: number;
187
187
  _lastSpreadStaleResyncAt: number;
188
+ /**
189
+ * Fill pivot (`price|type`) the geometry-bind escalation already re-centered
190
+ * for. A re-center cannot move the pivot, so the same fill is never
191
+ * re-centered twice — churn guard, cleared when the spread heals.
192
+ */
193
+ _lastGeometryResyncPivotKey: string;
194
+ /** Pivot key the "re-center cannot clear this" warning was already logged for. */
195
+ _geometryResyncWarnedPivotKey: string;
188
196
  _marketAdapterWatchdogInFlight: boolean;
189
197
  _outOfSpreadSince: number;
190
198
  _outOfSpreadStaleWarned: boolean;
191
199
  _outOfSpreadTransientCount: number;
200
+ /** When the spread first read within tolerance; cleared on any out-of-tolerance cycle. */
201
+ _outOfSpreadToleranceSince: number;
192
202
  _postRecoveryRebalanceDefers: number;
193
203
  _skipEmptyReadConfirmDelay: boolean;
194
- _spreadFundsExhausted: boolean;
204
+ _spreadStallArmed: boolean;
195
205
  _spreadCorrectionStall: SpreadCorrectionStall | null;
196
206
  _strandedHoldSince: Map<string, number>;
197
207
  _structuralGridResyncDeferCount: number;
@@ -213,13 +213,23 @@ class DEXBot {
213
213
  _lastHeldChainOrderSignatureSince;
214
214
  _lastHeldChainOrderWarnAt;
215
215
  _lastSpreadStaleResyncAt;
216
+ /**
217
+ * Fill pivot (`price|type`) the geometry-bind escalation already re-centered
218
+ * for. A re-center cannot move the pivot, so the same fill is never
219
+ * re-centered twice — churn guard, cleared when the spread heals.
220
+ */
221
+ _lastGeometryResyncPivotKey;
222
+ /** Pivot key the "re-center cannot clear this" warning was already logged for. */
223
+ _geometryResyncWarnedPivotKey;
216
224
  _marketAdapterWatchdogInFlight;
217
225
  _outOfSpreadSince;
218
226
  _outOfSpreadStaleWarned;
219
227
  _outOfSpreadTransientCount;
228
+ /** When the spread first read within tolerance; cleared on any out-of-tolerance cycle. */
229
+ _outOfSpreadToleranceSince;
220
230
  _postRecoveryRebalanceDefers;
221
231
  _skipEmptyReadConfirmDelay;
222
- _spreadFundsExhausted;
232
+ _spreadStallArmed;
223
233
  _spreadCorrectionStall;
224
234
  _strandedHoldSince;
225
235
  _structuralGridResyncDeferCount;
@@ -276,9 +286,12 @@ class DEXBot {
276
286
  // the first maintenance tick. Values mirror the lazy fallbacks in
277
287
  // trackOutOfSpreadStaleness.
278
288
  this._lastSpreadStaleResyncAt = 0;
289
+ this._lastGeometryResyncPivotKey = '';
290
+ this._geometryResyncWarnedPivotKey = '';
279
291
  this._outOfSpreadSince = 0;
280
292
  this._outOfSpreadStaleWarned = false;
281
293
  this._outOfSpreadTransientCount = 0;
294
+ this._outOfSpreadToleranceSince = 0;
282
295
  this.logPrefix = options.logPrefix || '';
283
296
  this._credentialDaemonWatchdogInterval = null;
284
297
  this._credentialDaemonDown = false;
@@ -338,7 +351,7 @@ class DEXBot {
338
351
  // Spread-correction stall state: the boolean gate and its companion cause
339
352
  // are read by getTargetedSyncReason before the first spread check, so
340
353
  // initialize both rather than leaving them undefined.
341
- this._spreadFundsExhausted = false;
354
+ this._spreadStallArmed = false;
342
355
  this._spreadCorrectionStall = null;
343
356
  this._lightweightSyncCheckAt = 0;
344
357
  this._targetedDriftSyncCooldownMs = this.config.timing?.TARGETED_DRIFT_SYNC_COOLDOWN_MS;
@@ -8,6 +8,7 @@
8
8
  * the same pattern as dexbot_fill_runtime.ts.
9
9
  */
10
10
  import * as chainOrdersModule from './chain_orders.js';
11
+ import { isLastFillGuardBlocked } from './order/utils/system.js';
11
12
  /**
12
13
  * Re-verify a B-stamped gap-evacuation rotation against the LIVE committed
13
14
  * geometry (boundaryIdx/_gapSlots at execution time). The stamp freezes
@@ -56,6 +57,19 @@ export interface CowResult extends JsonObj {
56
57
  workingIndexes: unknown;
57
58
  origin?: string;
58
59
  refillSlotIds?: string[];
60
+ /**
61
+ * Owed fill-crawl records this plan's derivation actually folded. The
62
+ * commit clears ONLY these; a record the derivation could not apply (a
63
+ * truncated cross-chunk shift, an edge-classified slot, a newer record for
64
+ * the same slot) stays owed. Without this the commit cleared the whole
65
+ * ledger and silently lost the difference (2026-10-25: 7 fills swept
66
+ * slots 147-153, boundary ended 7 levels behind).
67
+ */
68
+ consumedCrawlIds?: Array<{
69
+ slotId: string;
70
+ side: string;
71
+ ts?: number;
72
+ }>;
59
73
  fills?: unknown[];
60
74
  }
61
75
  /** A chain order enriched with the loose fields COW recovery reads. */
@@ -304,47 +318,24 @@ declare function recordRestampBuyAboveAnchor(bot: BotLike, price: unknown, type:
304
318
  * @returns {string[]} destinations inside the gap band
305
319
  */
306
320
  declare function collectGapBandPlacementShadowSlots(actions: CowAction[] | null | undefined, boundary: unknown, gapSlots: unknown): string[];
307
- /**
308
- * LAST-FILL-GUARD helper — pivot ± halfIncrement (replaces price-tolerance).
309
- * last fill @x with increment i (blocked shapes): BUY > x*(1 - i/2/100),
310
- * SELL < x*(1 + i/2/100)
311
- * e.g. x=1000, i=0.5% => BUY > 997.5 and SELL < 1002.5 are blocked
312
- * Cold (pivot null or lastType null) => disabled. Spread-correction CREATES
313
- * bypass per-action (see broadcast sites); gap-evacuation rotation UPDATEs
314
- * bypass only via the violation-reducing allowance (origin='gap-evacuation',
315
- * UPDATE-only, frozen B-stamp or live-proven isEvacuationRotationAllowed) —
316
- * see the UPDATE rotation guard block.
317
- * The pivot is the latest fill of either side and is never expired: it stays
318
- * the durable mark (last sold level floors new sells; buy fills pull it down
319
- * and re-open the sell side, buy-below-sell is never gated).
320
- * @param {number} price - Target order price
321
- * @param {number} size - Order size (unused, kept for compat)
322
- * @param {string} type - ORDER_TYPES.BUY/SELL
323
- * @param {number|null} lastPrice - Most recent fill price
324
- * @param {string|null} lastType - Most recent fill side (BUY/SELL)
325
- * @param {number|any} incrementPercent - Grid increment percent (e.g. 0.5). If assets object passed, falls back to default.
326
- * @returns {{blocked: boolean, pivot: number|null, halfInc: number, threshold: number|null}}
327
- */
328
- declare function isLastFillGuardBlocked(price: number, _size: number, type: unknown, lastPrice: number | null, lastType: string | null, incrementPercent: number): {
329
- blocked: boolean;
330
- pivot: number | null;
331
- halfInc?: number;
332
- threshold?: number | null;
333
- };
334
321
  /**
335
322
  * Whether a spread-correction CREATE may bypass the LAST-FILL-GUARD.
336
323
  *
337
- * The bypass exists so gap repair can close even after a recent fill (the
338
- * correction is tightening the spread, not chasing it). It must not become a
339
- * licence to place THROUGH the market the bot last traded at:
324
+ * Remaining purpose: the STARTUP BOOK SEED proxy. Before the first real fill a
325
+ * single-sided book arms the guard on our own resting quote (max bid / min
326
+ * ask) — a proxy that `b14a1fc8` deliberately keeps non-persistent ("a book
327
+ * seed never fossilizes into the snapshot as market truth") because it goes
328
+ * wrong whenever the book is not adjacent to the last fill. Blocking a
329
+ * tightening placement against that proxy would be arbitrary, so the correction
330
+ * is released from it while the local snapshot can be trusted.
331
+ *
332
+ * A real FILL reference always denies the bypass. Since the planner now filters
333
+ * candidates with the SAME predicate the guard applies, planner-built
334
+ * corrections never even propose an op that would need it — the bypass is a
335
+ * proxy-case valve, not a licence to trade through the last real fill.
340
336
  *
341
- * 1. A real fill pivot (`lastFillPivotSource === 'fill'`) is always honored —
342
- * no bypass. A sell below the last fill (or a buy above it) is the
343
- * issue-#31 adverse fill.
344
- * 2. A cold/book pivot is a heuristic (book seed) or absent, so the historical
345
- * fail-open bypass is kept — but only while the LOCAL snapshot is fresh.
346
- * A stale snapshot (known-unmatched chain orders, or an old sync) can hide
347
- * the real window edge, so the bypass is withheld and the guard applies.
337
+ * Denied too when the snapshot is stale or has known-unmatched chain orders
338
+ * (a stale edge can hide the real window edge), fail-closed on a gate throw.
348
339
  *
349
340
  * Exported for tests.
350
341
  * @param {Object} bot
@@ -412,6 +403,42 @@ declare function resolveRefillBoundaryHold(workingBoundary: unknown, committedBo
412
403
  effectiveBoundary: unknown;
413
404
  heldRefillSlotIds: string[];
414
405
  };
406
+ /**
407
+ * Derive the boundary the actual rails imply.
408
+ *
409
+ * `boundary` is a claim about where the BUY rail ends and the gap band begins;
410
+ * live orders are the fact. A fill-driven plan built at a re-anchored boundary
411
+ * places COUNTER orders above the committed boundary (SELL fill at slot s =>
412
+ * counter BUY at s - gapSlots). If the refill hold then keeps the old boundary,
413
+ * those counters sit inside the implied band; the next plan sees the old
414
+ * geometry and places a SELL on top of them, collapsing the spread (live
415
+ * incident: a sweep's counters at 1329.7-1345.7 were reclassified as in-band by
416
+ * a hold to 133, then sells were rotated to 1345.728664 — the exact price of
417
+ * the buy that had just filled).
418
+ *
419
+ * Rails are clamped by construction:
420
+ *
421
+ * maxBuyIdx <= boundary <= minSellIdx - gapSlots - 1
422
+ *
423
+ * Counter orders therefore win over empty refill holes: a held boundary may
424
+ * never strand a placed counter. When the plan did not place an order on the
425
+ * promoted rail (the normal refill-hold case) `maxBuyIdx` stays at/below the
426
+ * committed boundary and the hold is preserved unchanged.
427
+ *
428
+ * @param manager - OrderManager (master grid rails)
429
+ * @param opContexts - Kept op contexts of the batch (post guard/final gate)
430
+ * @param desiredBoundary - Plan boundary (falls back to the committed one)
431
+ * @param gapSlots - Gap band width
432
+ * @returns Boundary implied by the rails, or null when no rail geometry is
433
+ * usable / the rails already cross (caller keeps the current value).
434
+ */
435
+ export declare function deriveRailBoundary(manager: OrderManagerLike, opContexts: Iterable<unknown> | null | undefined, desiredBoundary: unknown, gapSlots: unknown): {
436
+ boundary: number | null;
437
+ maxBuyIdx: number | null;
438
+ minSellIdx: number | null;
439
+ clamped: boolean;
440
+ reason?: string;
441
+ };
415
442
  /**
416
443
  * Track consecutive boundary-hold batches on the manager (ops visibility).
417
444
  *
@@ -463,6 +490,28 @@ declare function resolveOnGridPivot(manager: OrderManagerLike, rawPrice: unknown
463
490
  idx: number | null;
464
491
  nearestDrift: number | null;
465
492
  };
493
+ /**
494
+ * Warn (once per batch) when a generic CREATE is emitted on the ADVERSE side of
495
+ * the crossing floor — the guard the spread-correction planner applies through
496
+ * `doesNotCrossMarket`.
497
+ *
498
+ * Non-blocking by design (see the call site): a crossing limit order executes at
499
+ * the BEST available price, so the risk is taker fees and unintended immediate
500
+ * execution, not a worse price. Blocking here would re-open the counter-order
501
+ * deadlock — after a gap the counter lands on the better side by construction,
502
+ * and a gapped market can put the planned level on the other side of the floor,
503
+ * where waiting for the market to return is worse than taking it.
504
+ *
505
+ * The floor is a pure read of already-cached evidence (a fresh live market read
506
+ * wins over the fill reference by recency), so this costs no chain call.
507
+ *
508
+ * @param {Object} bot
509
+ * @param {unknown} price - Emitted CREATE price
510
+ * @param {unknown} type - ORDER_TYPES.BUY/SELL
511
+ * @param {unknown} slotId - Slot the CREATE targets (log context)
512
+ * @returns {boolean} True when a warning was emitted (caller stops re-checking this batch)
513
+ */
514
+ declare function warnCrossingCreate(bot: BotLike, price: unknown, type: unknown, slotId: unknown): boolean;
466
515
  /**
467
516
  * Final pre-broadcast pivot gate: re-check BUILT ops against a re-refreshed
468
517
  * pivot RIGHT BEFORE broadcast.
@@ -547,8 +596,11 @@ declare function processBatchResults(bot: BotLike, result: JsonObj, opContexts:
547
596
  executed: boolean;
548
597
  hadRotation: boolean;
549
598
  updateOperationCount: number;
599
+ executedActionCount: number;
600
+ createOperationCount: number;
601
+ rotationOperationCount: number;
550
602
  }>;
551
- export { isSpreadCorrectionBypassAllowed, isLastFillGuardBlocked, resolveOnGridPivot, checkGridPriceInvariant, recordRestampBuyAboveAnchor, collectGapBandPlacementShadowSlots, deriveRotationPrice, refreshLastFillPivotFromQueue, runFinalPivotGate, buildOutsideInPairGroupsForOrders, buildOutsideInPairGroupsForCreateEntries, markMissingCreateResultsAsStructuralBlocker, formatUnmatchedChainOrderForLog, recordPendingBroadcast, clearPendingBroadcasts, popPushedWorkingGrid, findChainOrderForSlot, reconcileAfterUncertainBroadcast, executeWithRetryOnUncertain, executeChunkedWithRetryOnUncertain, formatPartialBroadcastSummary, buildActionsFromPlan, buildCowResultFromPlan, applyRotationTransitionsToWorkingGrid, updateOrdersOnChainBatchCOW, processBatchResults, adoptPlacedBatchFromChain, resolveRefillBoundaryHold, toRefillSlotIdSet, trackBoundaryHold };
603
+ export { isSpreadCorrectionBypassAllowed, isLastFillGuardBlocked, resolveOnGridPivot, warnCrossingCreate, checkGridPriceInvariant, recordRestampBuyAboveAnchor, collectGapBandPlacementShadowSlots, deriveRotationPrice, refreshLastFillPivotFromQueue, runFinalPivotGate, buildOutsideInPairGroupsForOrders, buildOutsideInPairGroupsForCreateEntries, markMissingCreateResultsAsStructuralBlocker, formatUnmatchedChainOrderForLog, recordPendingBroadcast, clearPendingBroadcasts, popPushedWorkingGrid, findChainOrderForSlot, reconcileAfterUncertainBroadcast, executeWithRetryOnUncertain, executeChunkedWithRetryOnUncertain, formatPartialBroadcastSummary, buildActionsFromPlan, buildCowResultFromPlan, applyRotationTransitionsToWorkingGrid, updateOrdersOnChainBatchCOW, processBatchResults, adoptPlacedBatchFromChain, resolveRefillBoundaryHold, toRefillSlotIdSet, trackBoundaryHold };
552
604
  export { restoreDiscardedCreates };
553
605
  declare const _default: {
554
606
  buildOutsideInPairGroupsForOrders: typeof buildOutsideInPairGroupsForOrders;