dexbot 1.6.13 → 1.6.15

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 (114) hide show
  1. package/CHANGELOG.md +66 -4
  2. package/README.md +2 -2
  3. package/analysis/README.md +6 -6
  4. package/analysis/tradingview/README.md +2 -1
  5. package/claw/README.md +7 -7
  6. package/claw/docs/AI_BOT_LIBRARY_API.md +1 -1
  7. package/claw/docs/DEXBOT2_TUNING_CHEAT_SHEET.md +4 -4
  8. package/claw/modules/claw_catalog.ts +8 -4
  9. package/claw/modules/dexbot_profiles.ts +59 -15
  10. package/claw/modules/types.ts +2 -1
  11. package/claw/package.json +1 -1
  12. package/claw/runtimes/openclaw-plugin/openclaw.plugin.json +1 -1
  13. package/claw/runtimes/openclaw-plugin/package.json +1 -1
  14. package/claw/skills/margin-trading/SKILL.md +1 -1
  15. package/claw/skills/margin-trading/references/position-management.md +1 -1
  16. package/dist/analysis/tradingview/tradingview_uplot_chart_generator.js +105 -31
  17. package/dist/analysis/trend_detection/dynamic_weight_chart_generator.js +36 -2
  18. package/dist/dexbot.js +23 -3
  19. package/dist/market_adapter/core/strategies/dynamic_weight_series.js +26 -11
  20. package/dist/modules/account_bots.d.ts +10 -6
  21. package/dist/modules/account_bots.js +13 -10
  22. package/dist/modules/account_orders.d.ts +36 -4
  23. package/dist/modules/account_orders.js +76 -5
  24. package/dist/modules/bitshares-native/crypto/ecc_core.d.ts +1 -2
  25. package/dist/modules/bitshares-native/crypto/ecc_core.js +1 -1
  26. package/dist/modules/bitshares-native/serial/chain_constants.d.ts +1 -2
  27. package/dist/modules/bitshares-native/serial/chain_constants.js +1 -2
  28. package/dist/modules/bitshares-native/subscriptions.js +1 -1
  29. package/dist/modules/bot_defaults.d.ts +29 -4
  30. package/dist/modules/bot_defaults.js +65 -10
  31. package/dist/modules/bot_settings.d.ts +4 -0
  32. package/dist/modules/bot_settings.js +58 -21
  33. package/dist/modules/config.js +6 -1
  34. package/dist/modules/constants.d.ts +13 -5
  35. package/dist/modules/constants.js +36 -5
  36. package/dist/modules/credit_runtime.d.ts +35 -5
  37. package/dist/modules/credit_runtime.js +219 -38
  38. package/dist/modules/dexbot_class.d.ts +23 -0
  39. package/dist/modules/dexbot_class.js +60 -17
  40. package/dist/modules/dexbot_cow_runtime.d.ts +62 -174
  41. package/dist/modules/dexbot_cow_runtime.js +350 -64
  42. package/dist/modules/dexbot_credential_client.d.ts +1 -16
  43. package/dist/modules/dexbot_credential_client.js +1 -1
  44. package/dist/modules/dexbot_fill_runtime.d.ts +2 -2
  45. package/dist/modules/dexbot_fill_runtime.js +16 -8
  46. package/dist/modules/dexbot_maintenance_runtime.d.ts +24 -81
  47. package/dist/modules/dexbot_maintenance_runtime.js +104 -70
  48. package/dist/modules/dexbot_startup_runtime.js +15 -2
  49. package/dist/modules/dexbot_state_recovery.js +17 -1
  50. package/dist/modules/key_store.d.ts +0 -5
  51. package/dist/modules/key_store.js +1 -1
  52. package/dist/modules/order/accounting.js +11 -11
  53. package/dist/modules/order/export.js +4 -4
  54. package/dist/modules/order/format.d.ts +15 -1
  55. package/dist/modules/order/format.js +19 -1
  56. package/dist/modules/order/genesis_policy.d.ts +1 -1
  57. package/dist/modules/order/genesis_policy.js +1 -1
  58. package/dist/modules/order/grid.d.ts +141 -12
  59. package/dist/modules/order/grid.js +666 -92
  60. package/dist/modules/order/grid_reconcile.d.ts +1 -1
  61. package/dist/modules/order/grid_reconcile.js +9 -8
  62. package/dist/modules/order/grid_reconcile_internal.js +61 -58
  63. package/dist/modules/order/index.d.ts +37 -9
  64. package/dist/modules/order/logger.js +2 -2
  65. package/dist/modules/order/manager.d.ts +10 -2
  66. package/dist/modules/order/manager.js +56 -31
  67. package/dist/modules/order/strategy.d.ts +2 -2
  68. package/dist/modules/order/strategy.js +51 -21
  69. package/dist/modules/order/sync_engine.js +22 -9
  70. package/dist/modules/order/utils/math.d.ts +101 -29
  71. package/dist/modules/order/utils/math.js +215 -84
  72. package/dist/modules/order/utils/order.d.ts +58 -58
  73. package/dist/modules/order/utils/order.js +135 -106
  74. package/dist/modules/order/utils/system.d.ts +193 -6
  75. package/dist/modules/order/utils/system.js +394 -31
  76. package/dist/modules/order/utils/validate.d.ts +1 -1
  77. package/dist/modules/order/utils/validate.js +71 -59
  78. package/dist/modules/runtime_settings.d.ts +1 -1
  79. package/dist/modules/runtime_settings.js +3 -3
  80. package/dist/modules/types.d.ts +55 -4
  81. package/dist/scripts/analyze-credit.js +44 -27
  82. package/dist/scripts/analyze-orders.d.ts +1 -1
  83. package/dist/scripts/analyze-orders.js +4 -4
  84. package/dist/scripts/diagnose-pool-history.js +35 -30
  85. package/dist/scripts/divergence-calc.js +6 -6
  86. package/dist/scripts/pnl.js +1 -1
  87. package/dist/scripts/rich_list.d.ts +18 -0
  88. package/dist/scripts/rich_list.js +461 -0
  89. package/dist/scripts/run-tests.js +80 -4
  90. package/dist/scripts/validate_bots.d.ts +1 -1
  91. package/dist/scripts/validate_bots.js +3 -3
  92. package/dist/unlock.d.ts +2 -1
  93. package/dist/unlock.js +11 -5
  94. package/docs/COPY_ON_WRITE_MASTER_PLAN.md +1 -2
  95. package/docs/COW_INVARIANTS.md +12 -6
  96. package/docs/DEXBOT_COMPARISON.md +7 -7
  97. package/docs/EVOLUTION.md +10 -8
  98. package/docs/FUND_MOVEMENT_AND_ACCOUNTING.md +8 -6
  99. package/docs/GRID_PRICE_INVARIANT.md +3 -3
  100. package/docs/GRID_RECALCULATION.md +4 -1
  101. package/docs/GRID_RECONCILE.md +4 -4
  102. package/docs/LIFECYCLE.md +11 -11
  103. package/docs/LOGGING.md +30 -1
  104. package/docs/MPA_CREDIT_USAGE.md +11 -6
  105. package/docs/ORDER_ENGINE_POST_1.0_RETROSPECTIVE.md +170 -12
  106. package/docs/README.md +3 -3
  107. package/docs/WORKFLOW.md +1 -0
  108. package/docs/architecture.md +62 -8
  109. package/docs/developer_guide.md +12 -3
  110. package/market_adapter/README.md +4 -4
  111. package/modules/README.md +1 -1
  112. package/package.json +2 -1
  113. package/scripts/README.md +59 -32
  114. package/tests/README.md +12 -3
@@ -70,7 +70,7 @@ export declare function decideStartupGridAction({ persistedGrid, chainOpenOrders
70
70
  * - Then create missing orders if chain has fewer than target.
71
71
  * - Then cancel excess orders if chain has more than target.
72
72
  *
73
- * Targets are derived from config.activeOrders.{buy,sell} and chain counts are computed
73
+ * Targets are derived from config.coreOrders.{buy,sell} and chain counts are computed
74
74
  * from current on-chain open orders.
75
75
  * @param {Object} params - Destructured parameters
76
76
  * @param {Object} params.manager - OrderManager instance
@@ -3,8 +3,8 @@ const require = createRequire(import.meta.url);
3
3
  import { _countActiveOnGrid, _cancelChainOrder, _recoverStartupSyncFailure, _refreshStartupUpdatePlans, _executeStartupUpdateBatch, _executeStartupSequentialUpdateFallback, _executePlannedStartupCreates, _reconcileStartupSide, } from './grid_reconcile_internal.js';
4
4
  import { ORDER_TYPES, ORDER_STATES, TIMING } from '../constants.js';
5
5
  import { readOpenOrdersGuarded } from '../chain_orders.js';
6
- import { getAssetFeesSafe, priceSlotEqual } from './utils/math.js';
7
- import { isOrderPlaced, parseChainOrder, isOrderOnChain, findLiveOrderOwnerByChainId, chainOrderMatchesSlotWithTolerance, duplicateOrphanLogInfo, resolveReserveCount, } from './utils/order.js';
6
+ import { getAssetFeesSafe, pricesOnSameLevel } from './utils/math.js';
7
+ import { isOrderPlaced, parseChainOrder, isOrderOnChain, findLiveOrderOwnerByChainId, chainOrderMatchesSlotWithTolerance, duplicateOrphanLogInfo, resolveEdgeCount, } from './utils/order.js';
8
8
  import * as Format from './format.js';
9
9
  import { getErrorMessage } from '../utils/errors.js';
10
10
  function _startupChainSnapshotSignature(orders, manager) {
@@ -142,7 +142,7 @@ export async function decideStartupGridAction({ persistedGrid, chainOpenOrders,
142
142
  * - Then create missing orders if chain has fewer than target.
143
143
  * - Then cancel excess orders if chain has more than target.
144
144
  *
145
- * Targets are derived from config.activeOrders.{buy,sell} and chain counts are computed
145
+ * Targets are derived from config.coreOrders.{buy,sell} and chain counts are computed
146
146
  * from current on-chain open orders.
147
147
  * @param {Object} params - Destructured parameters
148
148
  * @param {Object} params.manager - OrderManager instance
@@ -180,11 +180,11 @@ export async function reconcileGridOrders({ manager, config, account, privateKey
180
180
  const parsedChain = (chainOpenOrders || [])
181
181
  .map((co) => ({ chain: co, parsed: parseChainOrder(co, manager.assets) }))
182
182
  .filter((x) => x.parsed !== null);
183
- const activeCfg = (config && config.activeOrders) ? config.activeOrders : {};
183
+ const activeCfg = (config && config.coreOrders) ? config.coreOrders : {};
184
184
  let targetBuy = Math.max(0, Number.isFinite(Number(activeCfg.buy)) ? Number(activeCfg.buy) : 1)
185
- + resolveReserveCount(config, 'buy');
185
+ + resolveEdgeCount(config, 'buy');
186
186
  let targetSell = Math.max(0, Number.isFinite(Number(activeCfg.sell)) ? Number(activeCfg.sell) : 1)
187
- + resolveReserveCount(config, 'sell');
187
+ + resolveEdgeCount(config, 'sell');
188
188
  const chainBuys = parsedChain.filter((x) => x.parsed.type === ORDER_TYPES.BUY).map((x) => x.chain);
189
189
  const chainSells = parsedChain.filter((x) => x.parsed.type === ORDER_TYPES.SELL).map((x) => x.chain);
190
190
  // PHASE 1: In-memory reconciliation under lock — pure planning, no blockchain I/O.
@@ -251,8 +251,9 @@ export async function reconcileGridOrders({ manager, config, account, privateKey
251
251
  for (const gridOrder of activeGridOrders) {
252
252
  if (gridOrder.type !== p.type)
253
253
  continue;
254
- const precision = p.type === ORDER_TYPES.SELL ? manager.assets.assetA.precision : manager.assets.assetB.precision;
255
- const isEqual = priceSlotEqual(p.price, gridOrder.price, precision);
254
+ // Tolerance-based level check, NOT priceSlotEqual at the asset
255
+ // precision (a low-precision asset collapses adjacent levels).
256
+ const isEqual = pricesOnSameLevel(p.price, p.size ?? 0, p.type, gridOrder.price, gridOrder.size, gridOrder.type, manager.assets, manager.config?.incrementPercent);
256
257
  const priceDiff = Math.abs(p.price - gridOrder.price);
257
258
  const candidate = { gridOrder, priceDiff, isEqual };
258
259
  if (!nearest || priceDiff < nearest.priceDiff)
@@ -6,17 +6,22 @@
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, priceSlotEqual } from './utils/math.js';
10
- import { isOrderPlaced, parseChainOrder, buildCreateOrderArgs, buildOutsideInPairGroups, extractBatchOperationResults, chainOrderMatchesSlotWithTolerance, buildCrossingCheckCandidates, isCrossingCheckCandidate, getSideBudget, calculateBudgetedSizes, getActiveOrdersTotal, convertToSpreadPlaceholder, isOrderGoneErrorMessage, clearDuplicateOrphanDetection, resolveReserveCount, resolveLiveReserveEdgeAnchorPrice, reserveEdgeIdSet, compareReserveEdge, parseSlotIndex, reportGridPriceInvariant, liveWindowIdSet } from './utils/order.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
11
  import { resolveAccountRef } from './utils/system.js';
12
12
  import * as Format from './format.js';
13
13
  import { getErrorMessage, getErrorCode, getErrorName } from '../utils/errors.js';
14
14
  function computePlacementPriceCollision(manager, gridOrder) {
15
- const precision = gridOrder.type === ORDER_TYPES.SELL ? manager.assets.assetA.precision : manager.assets.assetB.precision;
15
+ // Grid-vs-grid: resolve each price to its frozen ladder level. NOT
16
+ // priceSlotEqual at the asset precision, which rounds a price through an
17
+ // asset AMOUNT precision and collapses an adjacent band for a
18
+ // low-precision asset (0.000318 and 0.000319 both -> 3 at precision 4,
19
+ // silently dropping every buy after the first). NOT the chain tolerance
20
+ // either: it can exceed the grid increment and merge adjacent levels.
16
21
  for (const o of manager.orders.values()) {
17
22
  if (!isOrderPlaced(o) || o.id === gridOrder.id)
18
23
  continue;
19
- if (priceSlotEqual(o.price, gridOrder.price, precision))
24
+ if (sameGridLevel(o.price, gridOrder.price, manager._genesis))
20
25
  return o;
21
26
  }
22
27
  return null;
@@ -58,7 +63,7 @@ function computePlacementCrossing(manager, gridOrder, excludeChainOrderId = null
58
63
  */
59
64
  function _countActiveOnGrid(manager, type) {
60
65
  // Slot-N gated: fork-kept shelf/manual orders (non-slot-N ids, e.g.
61
- // deep-*) sit outside window accounting — same gate as reserve
66
+ // deep-*) sit outside window accounting — same gate as edge
62
67
  // classification and matched-excess candidates (issue #27 follow-up).
63
68
  // Without this, a live shelf inflates matchedOnGrid, suppresses
64
69
  // neededSlots/creates, and its chain-count surplus cancels real window
@@ -107,7 +112,7 @@ function _deriveBudgetedSideSizes(manager, type) {
107
112
  if (!funds)
108
113
  return derived;
109
114
  const side = type === ORDER_TYPES.BUY ? 'buy' : 'sell';
110
- const totalTarget = getActiveOrdersTotal(manager.config);
115
+ const totalTarget = getCoreOrdersTotal(manager.config);
111
116
  const budget = getSideBudget(side, funds, manager.config, totalTarget);
112
117
  if (!(budget > 0))
113
118
  return derived;
@@ -182,7 +187,7 @@ function _pickVirtualSlotsToActivate(manager, type, count) {
182
187
  .filter(typeFilter)
183
188
  .filter(inRail)
184
189
  // Slot-N gated: fork-kept shelf/manual slots (non-slot-N ids, e.g.
185
- // deep-*) must never activate as window orders — same gate as reserve
190
+ // deep-*) must never activate as window orders — same gate as edge
186
191
  // classification and startup cancel candidates (issue #27 follow-up).
187
192
  // A VIRTUAL shelf passes the type + fail-open geometry filters above;
188
193
  // without this it would consume window activation budget at an
@@ -235,10 +240,10 @@ function _pickVirtualSlotsToActivate(manager, type, count) {
235
240
  return valid;
236
241
  }
237
242
  /**
238
- * Pick edge-pinned reserve slots (floor for BUY, ceiling for SELL).
243
+ * Pick edge-pinned edge slots (floor for BUY, ceiling for SELL).
239
244
  * Same rail membership gate as _pickVirtualSlotsToActivate, opposite end:
240
- * the reserve ladder rests at the grid edge instead of the market window.
241
- * Size gate is STRICTER than that picker's — reserves activate only with
245
+ * the edge ladder rests at the grid edge instead of the market window.
246
+ * Size gate is STRICTER than that picker's — edge orders activate only with
242
247
  * their own stored size (>= min order size), never a locally derived one,
243
248
  * so an unsized edge slot waits for the target-grid sizing pipeline.
244
249
  * @param {Object} manager - OrderManager instance.
@@ -248,7 +253,7 @@ function _pickVirtualSlotsToActivate(manager, type, count) {
248
253
  * @returns {Array<Object>} Array of picked edge slots (edge first).
249
254
  * @private
250
255
  */
251
- function _pickEdgeReserveSlots(manager, orderType, count, excludeIds = null) {
256
+ function _pickEdgeSlots(manager, orderType, count, excludeIds = null) {
252
257
  if (count <= 0)
253
258
  return [];
254
259
  const type = orderType;
@@ -259,20 +264,20 @@ function _pickEdgeReserveSlots(manager, orderType, count, excludeIds = null) {
259
264
  const typeFilter = boundaryKnown
260
265
  ? (slot) => slot && (slot.type === type || slot.type === ORDER_TYPES.SPREAD)
261
266
  : (slot) => slot && slot.type === type;
262
- // Reserve classification (reserveEdgeIdSet / countLiveReserveOrders) is
267
+ // Edge classification (edgeOrderIdSet / countLiveEdgeOrders) is
263
268
  // slot-N gated; keep placement in agreement so a kept virtual non-grid
264
- // shelf is never activated as a reserve it would then never be counted
269
+ // shelf is never activated as an edge order it would then never be counted
265
270
  // as (issue #27 follow-up). No-op upstream (grids only mint slot-N).
266
271
  const gridSlot = (slot) => parseSlotIndex(slot?.id) !== null;
267
272
  // Both edges anchor at the live grid's own edge (ladder/rail extreme):
268
273
  // floor — nearest at/above the live floor first; ceiling — nearest
269
274
  // at/below the live ceiling first. Stale out-of-grid slots sort last.
270
- const edgeAnchor = resolveLiveReserveEdgeAnchorPrice(manager, edgeDesc ? 'sell' : 'buy');
275
+ const edgeAnchor = resolveLiveEdgeAnchorPrice(manager, edgeDesc ? 'sell' : 'buy');
271
276
  const edgeFirst = Array.from(manager.orders.values())
272
277
  .filter(typeFilter)
273
278
  .filter(gridSlot)
274
279
  .filter(inRail)
275
- .sort((a, b) => compareReserveEdge(a, b, edgeDesc ? 'ceiling' : 'floor', edgeAnchor));
280
+ .sort((a, b) => compareEdge(a, b, edgeDesc ? 'ceiling' : 'floor', edgeAnchor));
276
281
  let effectiveMin = 0;
277
282
  try {
278
283
  effectiveMin = getMinOrderSize(type, manager.assets);
@@ -287,10 +292,10 @@ function _pickEdgeReserveSlots(manager, orderType, count, excludeIds = null) {
287
292
  if (excludeIds && excludeIds.has(slot.id))
288
293
  continue;
289
294
  if (!slot.orderId && slot.state === ORDER_STATES.VIRTUAL) {
290
- // Exact sizes only: a reserve is activated solely with the size the
295
+ // Exact sizes only: an edge order is activated solely with the size the
291
296
  // grid already carries (written by the target-grid sizing pipeline
292
297
  // and persisted with the slot). No local re-derivation — a second
293
- // sizing rule here could place the reserve with a size the target
298
+ // sizing rule here could place the edge with a size the target
294
299
  // grid then has to correct on the next cycle. An unsized slot
295
300
  // simply waits for the sizing pipeline instead of being guessed.
296
301
  const storedSize = Number(slot.size) || 0;
@@ -1401,32 +1406,32 @@ async function _reconcileStartupSide({ orderType, targetCount, chainSideOrders,
1401
1406
  const matchedOnGrid = _countActiveOnGrid(manager, orderType);
1402
1407
  const neededSlots = Math.max(0, targetCount - matchedOnGrid);
1403
1408
  let desiredSlots = _pickVirtualSlotsToActivate(manager, orderType, neededSlots);
1404
- // Reserve ladder: the closest-first picker above backfills the middle. Swap
1409
+ // Edge ladder: the closest-first picker above backfills the middle. Swap
1405
1410
  // its farthest tail for edge-pinned slots (floor for BUY, ceiling for SELL)
1406
1411
  // so startup converges to window + edge instead of one contiguous block.
1407
- let reserveEdgeIds = null;
1408
- const reserveSide = orderType === ORDER_TYPES.SELL ? 'sell' : 'buy';
1409
- const reserveCount = resolveReserveCount(manager.config, reserveSide);
1410
- if (reserveCount > 0) {
1412
+ let edgeOrderIds = null;
1413
+ const edgeSide = orderType === ORDER_TYPES.SELL ? 'sell' : 'buy';
1414
+ const edgeCount = resolveEdgeCount(manager.config, edgeSide);
1415
+ if (edgeCount > 0) {
1411
1416
  const pickedIds = new Set(desiredSlots.map((s) => s?.id).filter(Boolean));
1412
- const freshEdge = _pickEdgeReserveSlots(manager, orderType, reserveCount, pickedIds);
1413
- const reserveAnchor = resolveLiveReserveEdgeAnchorPrice(manager, reserveSide);
1414
- reserveEdgeIds = reserveEdgeIdSet(Array.from(manager.orders.values()), manager.config, orderType, reserveAnchor, liveWindowIdSet(manager, orderType));
1415
- // Window first, then the ready edge reserves. Only the reserve share
1416
- // still MISSING on-chain is held back for the edge (a live reserve is
1417
+ const freshEdge = _pickEdgeSlots(manager, orderType, edgeCount, pickedIds);
1418
+ const edgeAnchor = resolveLiveEdgeAnchorPrice(manager, edgeSide);
1419
+ edgeOrderIds = edgeOrderIdSet(Array.from(manager.orders.values()), manager.config, orderType, edgeAnchor, liveWindowIdSet(manager, orderType));
1420
+ // Window first, then the ready edge orders. Only the edge share
1421
+ // still MISSING on-chain is held back for the edge (a live edge order is
1417
1422
  // already part of matchedOnGrid and must not shrink the window plan), so
1418
1423
  // an edge pick that is not activatable yet (exact-size rule) leaves its
1419
1424
  // slot unplanned: the target-grid pipeline then creates it at the edge
1420
1425
  // with its own sizes, instead of the plan filling it with a middle
1421
1426
  // window slot that the next cycle would have to rotate out.
1422
- // Note: if the window picker itself took an edge/reserve slot (only
1427
+ // Note: if the window picker itself took an edge/edge slot (only
1423
1428
  // when the rail is too short to fill the window closer to market),
1424
- // that slot is not a placed reserve, so the plan comes out one short
1429
+ // that slot is not a placed edge order, so the plan comes out one short
1425
1430
  // here and the target grid settles it on the next cycle.
1426
- const liveReserves = reserveEdgeIds
1427
- ? [...reserveEdgeIds].filter((id) => isOrderPlaced(manager.orders.get(id))).length
1431
+ const liveEdges = edgeOrderIds
1432
+ ? [...edgeOrderIds].filter((id) => isOrderPlaced(manager.orders.get(id))).length
1428
1433
  : 0;
1429
- const missingReserves = Math.max(0, reserveCount - liveReserves);
1434
+ const missingReserves = Math.max(0, edgeCount - liveEdges);
1430
1435
  const keepCount = Math.max(0, neededSlots - missingReserves);
1431
1436
  desiredSlots = [...desiredSlots.slice(0, keepCount), ...freshEdge];
1432
1437
  }
@@ -1449,13 +1454,20 @@ async function _reconcileStartupSide({ orderType, targetCount, chainSideOrders,
1449
1454
  const planVacatedRailRefill = (chainOrder, parsedChain) => {
1450
1455
  const boundary = manager.boundaryIdx;
1451
1456
  const gapSlots = manager._gapSlots;
1457
+ // Explicit null/undefined/'' guard BEFORE Number(): Number(null) === 0
1458
+ // is finite and would defeat this bail-out, running the refill scan on
1459
+ // a bogus boundary 0 (and a null gapSlots would default to 0 through
1460
+ // getSellStartIdx).
1461
+ if (boundary === null || boundary === undefined || boundary === '')
1462
+ return;
1463
+ if (gapSlots === null || gapSlots === undefined || gapSlots === '')
1464
+ return;
1452
1465
  if (!Number.isFinite(Number(boundary)) || !Number.isFinite(Number(gapSlots)))
1453
1466
  return;
1454
1467
  const chainPrice = parsedChain?.price;
1455
1468
  if (!Number.isFinite(Number(chainPrice)))
1456
1469
  return;
1457
1470
  const chainPriceNum = Number(chainPrice);
1458
- const sidePrecision = orderType === ORDER_TYPES.SELL ? manager.assets?.assetA?.precision : manager.assets?.assetB?.precision;
1459
1471
  for (const slotOrder of manager.orders.values()) {
1460
1472
  if (!slotOrder || !slotOrder.id)
1461
1473
  continue;
@@ -1479,7 +1491,7 @@ async function _reconcileStartupSide({ orderType, targetCount, chainSideOrders,
1479
1491
  continue;
1480
1492
  if (Number(slotOrder.size) <= 0)
1481
1493
  continue;
1482
- if (!priceSlotEqual(slotOrder.price, chainPriceNum, sidePrecision))
1494
+ if (!pricesOnSameLevel(slotOrder.price, slotOrder.size, orderType, chainPriceNum, slotOrder.size, orderType, manager.assets, manager.config?.incrementPercent))
1483
1495
  continue;
1484
1496
  vacatedRefillPlanned.add(slotOrder.id);
1485
1497
  refillCandidates.push(slotOrder);
@@ -1627,32 +1639,23 @@ async function _reconcileStartupSide({ orderType, targetCount, chainSideOrders,
1627
1639
  .map((co) => ({ chain: co, parsed: parseChainOrder(co, manager.assets) }))
1628
1640
  .filter((x) => x.parsed !== null)
1629
1641
  .sort(sortExcessCancelComparator);
1630
- // Reserve ladder: edge-priced orphans cancel last (they are adoption
1631
- // candidates at reserve prices, not first-to-cut).
1632
- if (reserveEdgeIds && reserveEdgeIds.size > 0) {
1633
- const sidePrecision = orderType === ORDER_TYPES.SELL
1634
- ? manager.assets?.assetA?.precision
1635
- : manager.assets?.assetB?.precision;
1642
+ // Edge ladder: edge-priced orphans cancel last (they are adoption
1643
+ // candidates at edge prices, not first-to-cut).
1644
+ if (edgeOrderIds && edgeOrderIds.size > 0) {
1636
1645
  const edgePrices = [];
1637
- for (const eid of reserveEdgeIds) {
1646
+ for (const eid of edgeOrderIds) {
1638
1647
  const slot = manager.orders.get(eid);
1639
1648
  if (slot && Number.isFinite(Number(slot.price)))
1640
1649
  edgePrices.push(Number(slot.price));
1641
1650
  }
1642
- const isEdgePriced = (price) => {
1651
+ const isEdgePriced = (price, size) => {
1643
1652
  const p = Number(price);
1653
+ const s = Number(size) || 0;
1644
1654
  if (!Number.isFinite(p))
1645
1655
  return false;
1646
- return edgePrices.some((ep) => {
1647
- try {
1648
- return priceSlotEqual(ep, p, sidePrecision);
1649
- }
1650
- catch {
1651
- return ep === p;
1652
- }
1653
- });
1656
+ return edgePrices.some((ep) => pricesOnSameLevel(ep, s, orderType, p, s, orderType, manager.assets, manager.config?.incrementPercent));
1654
1657
  };
1655
- const parked = parsedUnmatched.filter((x) => isEdgePriced(x.parsed?.price));
1658
+ const parked = parsedUnmatched.filter((x) => isEdgePriced(x.parsed?.price, x.parsed?.size));
1656
1659
  if (parked.length > 0 && parked.length < parsedUnmatched.length) {
1657
1660
  const parkedIds = new Set(parked.map((x) => x.chain?.id));
1658
1661
  parsedUnmatched.sort((a, b) => {
@@ -1666,9 +1669,9 @@ async function _reconcileStartupSide({ orderType, targetCount, chainSideOrders,
1666
1669
  // matched (grid-known) slots. Computed once and shared by both the
1667
1670
  // planOnly and execute branches so planning can never drift from
1668
1671
  // execution: unmatched orphans cancel first, matched surplus after,
1669
- // reserve edge slots last (static insurance). Slot-N gated: fork-kept
1672
+ // edge order slots last (static insurance). Slot-N gated: fork-kept
1670
1673
  // shelf/manual orders (non-slot-N ids, e.g. deep-*) are never excess
1671
- // candidates — reserveEdgeIdSet already excludes them, so without this
1674
+ // candidates — edgeOrderIdSet already excludes them, so without this
1672
1675
  // gate a live shelf heads the cheapest-first sort and is wiped on the
1673
1676
  // next boot (issue #27 follow-up). No-op upstream (grids only mint
1674
1677
  // slot-N).
@@ -1676,11 +1679,11 @@ async function _reconcileStartupSide({ orderType, targetCount, chainSideOrders,
1676
1679
  .filter((o) => o && o.orderId)
1677
1680
  .filter((o) => parseSlotIndex(o?.id) !== null)
1678
1681
  .sort(sortMatchedCancelComparator);
1679
- // Reserve ladder: matched edge slots cancel last (static insurance).
1680
- if (reserveEdgeIds && reserveEdgeIds.size > 0) {
1682
+ // Edge ladder: matched edge slots cancel last (static insurance).
1683
+ if (edgeOrderIds && edgeOrderIds.size > 0) {
1681
1684
  matchedExcess.sort((a, b) => {
1682
- const fa = reserveEdgeIds.has(a.id) ? 1 : 0;
1683
- const fb = reserveEdgeIds.has(b.id) ? 1 : 0;
1685
+ const fa = edgeOrderIds.has(a.id) ? 1 : 0;
1686
+ const fb = edgeOrderIds.has(b.id) ? 1 : 0;
1684
1687
  return fa - fb;
1685
1688
  });
1686
1689
  }
@@ -1712,7 +1715,7 @@ async function _reconcileStartupSide({ orderType, targetCount, chainSideOrders,
1712
1715
  // could never converge to its additive window+edge target (live
1713
1716
  // 12 vs target 8 sat static across every restart). Same priority
1714
1717
  // as the execute branch: unmatched first (above), matched after,
1715
- // reserve edge last (matchedExcess ordering).
1718
+ // edge order last (matchedExcess ordering).
1716
1719
  for (const o of matchedExcess) {
1717
1720
  if (cancelCount <= 0)
1718
1721
  break;
@@ -72,12 +72,38 @@ declare const utils: {
72
72
  accountTotals: import("../types.js").AccountTotals | null;
73
73
  }): Promise<boolean>;
74
74
  restoreGapEvacStreaks(manager: import("../types.js").OrderManagerLike, persisted: unknown): number;
75
+ resolveSpreadFreshnessMs(manager: import("../types.js").OrderManagerLike): number;
76
+ resolveSpreadCrossingFloor(manager: import("../types.js").OrderManagerLike): number | null;
77
+ refreshLiveMarketPrice(manager: import("../types.js").OrderManagerLike, BitShares: unknown): Promise<number | null>;
78
+ maybeRefreshLiveMarketPrice(manager: import("../types.js").OrderManagerLike, BitShares: unknown, options?: {
79
+ now?: number;
80
+ }): Promise<number | null>;
81
+ evaluateSpreadCorrectionReadiness(manager: import("../types.js").OrderManagerLike, options?: {
82
+ now?: number;
83
+ onChainOrders?: {
84
+ buys: unknown[];
85
+ sells: unknown[];
86
+ } | null;
87
+ }): system.SpreadCorrectionReadiness;
88
+ resolveSpreadMarketReference(manager: import("../types.js").OrderManagerLike): number | null;
89
+ resolveLastFillGuardReference(manager: import("../types.js").OrderManagerLike): {
90
+ price: number | null;
91
+ type: string | null;
92
+ };
93
+ restoreLastMarketFill(manager: import("../types.js").OrderManagerLike, persisted: unknown, options?: {
94
+ now?: number;
95
+ }): boolean;
75
96
  normalizeLastFillPivot(row: unknown): {
76
97
  price: number;
77
98
  type: string;
78
99
  fillsAt: number;
79
100
  genesisHash: string;
80
101
  } | null;
102
+ normalizeLastMarketFill(row: unknown): {
103
+ price: number;
104
+ type: string;
105
+ fillsAt: number;
106
+ } | null;
81
107
  setLastFillPivot(manager: import("../types.js").OrderManagerLike, type: string, price: unknown, provenance: "fill" | "book", atMs?: number): boolean;
82
108
  resetLastFillPivot(manager: import("../types.js").OrderManagerLike, reason?: string): boolean;
83
109
  restoreLastFillPivot(manager: import("../types.js").OrderManagerLike, persisted: unknown, options?: {
@@ -200,10 +226,10 @@ declare const utils: {
200
226
  buildDelta: typeof order.buildDelta;
201
227
  deriveTargetBoundary: typeof order.deriveTargetBoundary;
202
228
  isShiftEligibleFill: typeof order.isShiftEligibleFill;
203
- resolveReserveCount: typeof order.resolveReserveCount;
204
- resolveReserveOrders: typeof order.resolveReserveOrders;
205
- selectReserveEdgeSlots: typeof order.selectReserveEdgeSlots;
206
- getActiveOrdersTotal: typeof order.getActiveOrdersTotal;
229
+ resolveEdgeCount: typeof order.resolveEdgeCount;
230
+ resolveEdgeOrders: typeof order.resolveEdgeOrders;
231
+ selectEdgeSlots: typeof order.selectEdgeSlots;
232
+ getCoreOrdersTotal: typeof order.getCoreOrdersTotal;
207
233
  getSideBudget: typeof order.getSideBudget;
208
234
  calculateBudgetedSizes: typeof order.calculateBudgetedSizes;
209
235
  buildCreateOpFingerprint: typeof order.buildCreateOpFingerprint;
@@ -214,13 +240,13 @@ declare const utils: {
214
240
  chainOrderUnchangedFromCache: typeof order.chainOrderUnchangedFromCache;
215
241
  detectCrossedBookPlan: typeof order.detectCrossedBookPlan;
216
242
  collectKnownOnChainOrderIds: typeof order.collectKnownOnChainOrderIds;
217
- reserveEdgeIdSet: typeof order.reserveEdgeIdSet;
243
+ edgeOrderIdSet: typeof order.edgeOrderIdSet;
218
244
  liveWindowIdSet: typeof order.liveWindowIdSet;
219
245
  checkGridPriceInvariant: typeof order.checkGridPriceInvariant;
220
246
  reportGridPriceInvariant: typeof order.reportGridPriceInvariant;
221
- resolveReserveEdgeAnchorPrice: typeof order.resolveReserveEdgeAnchorPrice;
222
- resolveLiveReserveEdgeAnchorPrice: typeof order.resolveLiveReserveEdgeAnchorPrice;
223
- compareReserveEdge: typeof order.compareReserveEdge;
247
+ resolveEdgeAnchorPrice: typeof order.resolveEdgeAnchorPrice;
248
+ resolveLiveEdgeAnchorPrice: typeof order.resolveLiveEdgeAnchorPrice;
249
+ compareEdge: typeof order.compareEdge;
224
250
  collectRefillSlotIds: typeof order.collectRefillSlotIds;
225
251
  recordOrderPlacement: typeof order.recordOrderPlacement;
226
252
  isFreshlyPlacedOrder: typeof order.isFreshlyPlacedOrder;
@@ -268,8 +294,9 @@ declare const utils: {
268
294
  getPrecisionSlack: typeof math.getPrecisionSlack;
269
295
  quantumForPrecision: typeof math.quantumForPrecision;
270
296
  calculatePriceTolerance: typeof math.calculatePriceTolerance;
271
- findPriceCollision: typeof math.findPriceCollision;
272
297
  findCrossedOrder: typeof math.findCrossedOrder;
298
+ pricesOnSameLevel: typeof math.pricesOnSameLevel;
299
+ sameGridPrice: typeof math.sameGridPrice;
273
300
  validateOrderAmountsWithinLimits: typeof math.validateOrderAmountsWithinLimits;
274
301
  getMinOrderSize: typeof math.getMinOrderSize;
275
302
  getDustThresholdFactor: typeof math.getDustThresholdFactor;
@@ -297,6 +324,7 @@ declare const utils: {
297
324
  assertSlotPriceInvariant: typeof math.assertSlotPriceInvariant;
298
325
  priceSlotEqual: typeof math.priceSlotEqual;
299
326
  derivePriceLevels: typeof math.derivePriceLevels;
327
+ sameGridLevel: typeof math.sameGridLevel;
300
328
  buildGenesisFromPriceLevels: typeof math.buildGenesisFromPriceLevels;
301
329
  hashPriceLevels: typeof math.hashPriceLevels;
302
330
  isChainPriceOutOfGrid: typeof math.isChainPriceOutOfGrid;
@@ -544,7 +544,7 @@ class Logger {
544
544
  if (!this.config.display?.statusSummary?.enabled && !forceOutput)
545
545
  return;
546
546
  const market = manager.marketName || manager.config?.market || 'unknown';
547
- const activeOrders = manager.getOrdersByTypeAndState?.(null, ORDER_STATES.ACTIVE) || [];
547
+ const liveOrders = manager.getOrdersByTypeAndState?.(null, ORDER_STATES.ACTIVE) || [];
548
548
  const partialOrders = manager.getOrdersByTypeAndState?.(null, ORDER_STATES.PARTIAL) || [];
549
549
  const virtualOrders = manager.getOrdersByTypeAndState?.(null, ORDER_STATES.VIRTUAL) || [];
550
550
  const buyName = manager.config?.assetB?.symbol || manager.config?.assetB || 'quote';
@@ -570,7 +570,7 @@ class Logger {
570
570
  `virtual.grid: ${buy}Buy ${Format.formatAmountByPrecision(virtualBuy, buyPrecision)}${reset} ${buyName} | ${sell}Sell ${Format.formatAmountByPrecision(virtualSell, sellPrecision)}${reset} ${sellName}`,
571
571
  `committed.grid: ${buy}Buy ${Format.formatAmountByPrecision(committedGridBuy, buyPrecision)}${reset} ${buyName} | ${sell}Sell ${Format.formatAmountByPrecision(committedGridSell, sellPrecision)}${reset} ${sellName}`,
572
572
  `committed.chain: ${buy}Buy ${Format.formatAmountByPrecision(committedChainBuy, buyPrecision)}${reset} ${buyName} | ${sell}Sell ${Format.formatAmountByPrecision(committedChainSell, sellPrecision)}${reset} ${sellName}`,
573
- `Orders: Virtual ${virtualOrders.length} | Active ${activeOrders.length} | Partial ${partialOrders.length}`,
573
+ `Orders: Virtual ${virtualOrders.length} | Active ${liveOrders.length} | Partial ${partialOrders.length}`,
574
574
  `Spreads: ${manager.initialSpreadCount > 0 ? `${manager.currentSpreadCount}/${manager.initialSpreadCount} (gap)` : 'n/a (gap)'}`,
575
575
  ];
576
576
  if (typeof manager.calculateCurrentSpread === 'function') {
@@ -77,7 +77,7 @@ interface COWExecuteParams {
77
77
  excludeIds?: Set<string>;
78
78
  gapSlots?: number | null;
79
79
  evacStreaks?: Map<string, number> | null;
80
- reserveEdgeAnchors?: {
80
+ edgeAnchors?: {
81
81
  buy?: number | null;
82
82
  sell?: number | null;
83
83
  } | null;
@@ -93,7 +93,7 @@ declare class COWRebalanceEngine {
93
93
  assets: AssetPair | null;
94
94
  config: GridConfig;
95
95
  });
96
- execute({ masterGrid, gridVersion, boundaryIdx, funds, manager, fills, excludeIds, gapSlots, evacStreaks, reserveEdgeAnchors }: COWExecuteParams): Promise<RebalanceResult>;
96
+ execute({ masterGrid, gridVersion, boundaryIdx, funds, manager, fills, excludeIds, gapSlots, evacStreaks, edgeAnchors }: COWExecuteParams): Promise<RebalanceResult>;
97
97
  }
98
98
  declare class OrderManager implements OrderManagerLike {
99
99
  config: GridConfig;
@@ -220,6 +220,13 @@ declare class OrderManager implements OrderManagerLike {
220
220
  _lastFilledType: string | null;
221
221
  _lastFilledAt: number;
222
222
  lastFillPivotSource: 'fill' | 'book' | null;
223
+ _lastMarketFillPrice: number | null;
224
+ _lastMarketFillType: string | null;
225
+ _lastMarketFillAt: number;
226
+ _liveMarketPrice: number | null;
227
+ _liveMarketPriceAt: number;
228
+ _liveMarketPriceAttemptedAt: number;
229
+ _lastSyncAt: number;
223
230
  _deferredRebalanceAt: number;
224
231
  _lastHeldPlanSignature: {
225
232
  boundaryIdx: number | null;
@@ -761,6 +768,7 @@ declare class OrderManager implements OrderManagerLike {
761
768
  ordersPlaced: number;
762
769
  partialsMoved: number;
763
770
  stall?: import("../types.js").SpreadCorrectionStall;
771
+ transient?: boolean;
764
772
  }>;
765
773
  /**
766
774
  * @param {Function} batchCb - Batch callback