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
@@ -35,7 +35,7 @@
35
35
  // ===============================================================================
36
36
  import * as Format from '../format.js';
37
37
  import { ORDER_STATES, ORDER_TYPES, COW_ACTIONS, COW_ORIGINS, GRID_LIMITS } from '../../constants.js';
38
- import { floatToBlockchainInt, blockchainToFloat, getPrecisionSlack, getPrecisionByOrderType, getDoubleDustThreshold, getSellStartIdx, isSlotIndexInGapBand, isEvacuationRotationAllowed, clamp, priceSlotEqual } from './math.js';
38
+ import { floatToBlockchainInt, blockchainToFloat, getPrecisionSlack, getPrecisionByOrderType, getDoubleDustThreshold, getSellStartIdx, isSlotIndexInGapBand, isEvacuationRotationAllowed, clamp, pricesOnSameLevel, sameGridPrice } from './math.js';
39
39
  import { parseSlotIndex } from './slot.js';
40
40
  import { isOrderOnChain, isPhantomOrder, convertToSpreadPlaceholder, detectGapEvacuationCandidates, updateGapEvacuationStreaks, isNonBlockingUnmatchedOrder } from './order.js';
41
41
  const { isValidNumber, toFiniteNumber } = Format;
@@ -356,6 +356,15 @@ function clampRotationSizeForPartial(surplusMaster, holeSize, logger = null, hol
356
356
  * @returns {Object} The action, stamped when it qualifies
357
357
  */
358
358
  function stampGapEvacuationRotation(action, sourceMaster, destPrice, destSize, type, frozenBoundary, frozenGapSlots, assets = null) {
359
+ // Explicit null/undefined/'' guard BEFORE Number(): Number(null) === 0 is
360
+ // finite and would stamp a bogus gap-evacuation bypass at boundary 0 when
361
+ // the plan geometry is unknown (absent geometry means no stamp, never
362
+ // fail-open — same trap guarded across the COW/gap-evacuation stack).
363
+ if (frozenBoundary === null || frozenBoundary === undefined || frozenBoundary === '')
364
+ return action;
365
+ const rawFrozenGapSlots = frozenGapSlots;
366
+ if (rawFrozenGapSlots === null || rawFrozenGapSlots === undefined || rawFrozenGapSlots === '')
367
+ return action;
359
368
  const b = Number(frozenBoundary);
360
369
  const g = Number(frozenGapSlots);
361
370
  if (!Number.isFinite(b) || !Number.isFinite(g) || g < 0)
@@ -399,8 +408,11 @@ function reconcileGrid(masterGrid, targetGrid, targetBoundary, options = {}) {
399
408
  const { logger = null, dustThresholdPercent = GRID_LIMITS.PARTIAL_DUST_THRESHOLD_PERCENTAGE } = options;
400
409
  // B-stamp inputs for gap-evacuation rotation stamping (frozen at
401
410
  // plan-build): callers pass the geometry this plan was built for. Absent
402
- // or non-finite => no stamping (guarded default, never fail-open).
403
- const planGapSlots = Number(options?.gapSlots);
411
+ // (null/undefined/'') or non-finite => no stamping (guarded default, never
412
+ // fail-open). Absent-aware coercion: Number(null) === 0 would otherwise
413
+ // feed 0 into stampGapEvacuationRotation/detectGapEvacuationCandidates and
414
+ // defeat their own null guards.
415
+ const planGapSlots = Format.toKnownNumber(options?.gapSlots);
404
416
  const hasPlanGeometry = Number.isFinite(planGapSlots) && planGapSlots >= 0;
405
417
  const evacAssets = options?.assets ?? null;
406
418
  const actions = [];
@@ -593,8 +605,20 @@ function optimizeRebalanceActions(actions, masterGrid, options = {}) {
593
605
  // B-stamp inputs (same contract as reconcileGrid): frozen plan-build
594
606
  // boundary + gap width for gap-evacuation rotation stamping. Absent =>
595
607
  // no stamping, guarded default.
596
- const optBoundary = Number(options?.boundaryIdx);
597
- const optGapSlots = Number(options?.gapSlots);
608
+ // Explicit null/undefined guard BEFORE Number(): Number(null) === 0 is
609
+ // finite and would turn an absent boundary into a valid slot-0 geometry,
610
+ // stamping a bogus gap-evacuation bypass (undefined already fails open via
611
+ // NaN, so only null was hazardous). '' is equally hazardous (Number('')
612
+ // === 0) and is guarded here the same way as in
613
+ // stampGapEvacuationRotation.
614
+ const rawOptBoundary = options?.boundaryIdx;
615
+ const rawOptGapSlots = options?.gapSlots;
616
+ const optBoundary = (rawOptBoundary === null || rawOptBoundary === undefined || rawOptBoundary === '')
617
+ ? NaN
618
+ : Number(rawOptBoundary);
619
+ const optGapSlots = (rawOptGapSlots === null || rawOptGapSlots === undefined || rawOptGapSlots === '')
620
+ ? NaN
621
+ : Number(rawOptGapSlots);
598
622
  const hasOptGeometry = Number.isFinite(optBoundary) && Number.isFinite(optGapSlots) && optGapSlots >= 0;
599
623
  const optAssets = options?.assets ?? null;
600
624
  const creates = [];
@@ -712,7 +736,7 @@ function hasExecutableActions(rebalanceResult) {
712
736
  * with {chainOrderId, price, size, type} to check beyond the grid
713
737
  * @returns {{isValid: boolean, violations: Array<Object>, violatingTargetIds: Set<string>}} Validation result
714
738
  */
715
- function validateCreateTargetSlots(actions, orders, _assets = null, chainOrderCandidates = []) {
739
+ function validateCreateTargetSlots(actions, orders, _assets = null, chainOrderCandidates = [], incrementPercent = null) {
716
740
  const safeActions = Array.isArray(actions) ? actions : [];
717
741
  const orderMap = orders instanceof Map ? orders : new Map();
718
742
  const releasedSlotIds = new Set();
@@ -785,9 +809,9 @@ function validateCreateTargetSlots(actions, orders, _assets = null, chainOrderCa
785
809
  // set entirely, letting a CREATE collide with a slot-unknown
786
810
  // chain order sitting at the same price level (duplicate order).
787
811
  if (_assets) {
788
- // priceSlotEqual is a top-level import (the old inline
789
- // require('./math.js') threw under ESM and the catch-all
790
- // below silently disabled the whole fallback).
812
+ // Tolerance-based level check (pricesOnSameLevel); NOT
813
+ // priceSlotEqual at the asset precision, which collapses
814
+ // adjacent grid levels for a low-precision asset.
791
815
  const slotlessCandidates = validChainCandidates.filter((u) => !(u.chainSlotId || u.candidateSlotId));
792
816
  for (const entry of createEntries) {
793
817
  if (violations.some(v => v.targetId === entry.targetId))
@@ -797,14 +821,10 @@ function validateCreateTargetSlots(actions, orders, _assets = null, chainOrderCa
797
821
  continue;
798
822
  if (u.type && entry.type && u.type !== entry.type)
799
823
  continue;
800
- const precision = entry.type === 'sell' ? _assets.assetA?.precision : _assets.assetB?.precision;
801
- try {
802
- if (priceSlotEqual(u.price, entry.price, precision)) {
803
- violations.push({ targetId: entry.targetId, currentOrderId: u.chainOrderId, currentType: entry.type, currentState: 'CHAIN_ORPHAN', reason: 'chain_orphan_collision' });
804
- break;
805
- }
824
+ if (pricesOnSameLevel(Number(u.price), Number(u.size) || 0, u.type, Number(entry.price), Number(entry.size) || 0, entry.type, _assets, incrementPercent)) {
825
+ violations.push({ targetId: entry.targetId, currentOrderId: u.chainOrderId, currentType: entry.type, currentState: 'CHAIN_ORPHAN', reason: 'chain_orphan_collision' });
826
+ break;
806
827
  }
807
- catch { }
808
828
  }
809
829
  }
810
830
  }
@@ -818,21 +838,24 @@ function validateCreateTargetSlots(actions, orders, _assets = null, chainOrderCa
818
838
  else
819
839
  seen.add(entry.targetId);
820
840
  }
821
- // Same-batch bit-identical duplicate price across DIFFERENT target slots.
841
+ // Same-batch duplicate price across DIFFERENT target slots.
822
842
  // The genesis-frozen slot mapping gives every slot a distinct price
823
- // level, so two CREATEs at the exact same price on different slots
824
- // indicate a degenerate plan (production incident 2026-08-29: several
825
- // slots planned at one price; every batch was filtered down to a
826
- // single op and the grid rebuild crawled at one placement per cycle).
827
- // The tolerance-based price-collision check that caught this class was
828
- // removed with the slot-based rewrite; this exact-equality check
829
- // restores the protection without tolerance false-positives. First
830
- // target per (type, price) wins; later duplicates are skipped by the
831
- // caller via violatingTargetIds.
832
- const priceOwner = new Map();
843
+ // level, so two CREATEs at the same price on different slots indicate a
844
+ // degenerate plan (production incident 2026-08-29: several slots
845
+ // planned at one price; every batch was filtered down to a single op
846
+ // and the grid rebuild crawled at one placement per cycle).
847
+ //
848
+ // Identity is the ladder level, NOT the on-chain integer at the asset
849
+ // precision: a price is not an amount, so a low-precision asset
850
+ // (e.g. precision 4) collapses an entire adjacent band (0.000318 and
851
+ // 0.000343 both -> 3) and would flag every CREATE but the first as a
852
+ // duplicate. sameGridPrice carries 1e-9 relative slack so float noise
853
+ // in a repeated level still matches without merging distinct levels.
854
+ // First target per (type, level) wins; later duplicates are skipped by
855
+ // the caller via violatingTargetIds.
856
+ const invalidPriceTargets = new Set();
833
857
  for (const entry of createEntries) {
834
- const priceNum = Number(entry.price);
835
- if (!Number.isFinite(priceNum)) {
858
+ if (!Number.isFinite(Number(entry.price))) {
836
859
  // Fail closed: an unpriceable CREATE cannot be proven
837
860
  // collision-free, so it is rejected, not skipped.
838
861
  violations.push({
@@ -842,37 +865,26 @@ function validateCreateTargetSlots(actions, orders, _assets = null, chainOrderCa
842
865
  currentState: 'CREATE',
843
866
  reason: 'create_price_invalid',
844
867
  });
845
- continue;
846
- }
847
- // Key on the on-chain integer repr when the side precision is
848
- // known (bit-exact: prices that quantize to the same chain int
849
- // ARE the same price on the DEX); float fallback preserves the
850
- // old behavior for callers without assets context.
851
- let key;
852
- let sidePrecision = null;
853
- try {
854
- sidePrecision = _assets ? getPrecisionByOrderType(_assets, entry.type) : null;
855
- }
856
- catch {
857
- sidePrecision = null;
858
- }
859
- if (Number.isFinite(Number(sidePrecision)) && Number(sidePrecision) > 0) {
860
- try {
861
- key = `${String(entry.type)}:i${floatToBlockchainInt(priceNum, Number(sidePrecision))}`;
862
- }
863
- catch {
864
- key = `${String(entry.type)}:${priceNum}`;
865
- }
866
- }
867
- else {
868
- key = `${String(entry.type)}:${priceNum}`;
868
+ invalidPriceTargets.add(entry.targetId);
869
869
  }
870
- const owner = priceOwner.get(key);
871
- if (owner === undefined) {
872
- priceOwner.set(key, entry.targetId);
873
- }
874
- else if (owner !== entry.targetId) {
875
- violations.push({ targetId: entry.targetId, currentOrderId: null, currentType: entry.type, currentState: 'CREATE', reason: 'same_batch_price_duplicate', duplicateOf: owner });
870
+ }
871
+ const duplicateTargets = new Set();
872
+ for (let i = 0; i < createEntries.length; i++) {
873
+ const a = createEntries[i];
874
+ if (invalidPriceTargets.has(a.targetId))
875
+ continue;
876
+ for (let j = i + 1; j < createEntries.length; j++) {
877
+ const b = createEntries[j];
878
+ if (invalidPriceTargets.has(b.targetId))
879
+ continue;
880
+ if (a.targetId === b.targetId || a.type !== b.type)
881
+ continue;
882
+ if (!sameGridPrice(a.price, b.price))
883
+ continue;
884
+ if (duplicateTargets.has(b.targetId))
885
+ continue;
886
+ duplicateTargets.add(b.targetId);
887
+ violations.push({ targetId: b.targetId, currentOrderId: null, currentType: b.type, currentState: 'CREATE', reason: 'same_batch_price_duplicate', duplicateOf: a.targetId });
876
888
  }
877
889
  }
878
890
  }
@@ -20,7 +20,7 @@ export declare const RUNTIME_SETTINGS_KEYS: readonly string[];
20
20
  * process restart (Issue #27 follow-up). Single source of truth — consumed
21
21
  * by the live bot-config check (dexbot_maintenance_runtime.ts) and the
22
22
  * `dexbot bot` editor hint (account_bots.ts) so the two can never drift.
23
- * activeOrders/reserveOrders are re-read via the targeted-reconcile path,
23
+ * coreOrders/edgeOrders are re-read via the targeted-reconcile path,
24
24
  * botFunds via recalculateFunds, weightDistribution base via
25
25
  * refreshDynamicWeightDistribution, min_BTS_value via the fee/acquisition
26
26
  * reads, and debtPolicy via the credit runtime's live getter (next credit
@@ -28,7 +28,7 @@ export const RUNTIME_SETTINGS_KEYS = [
28
28
  * process restart (Issue #27 follow-up). Single source of truth — consumed
29
29
  * by the live bot-config check (dexbot_maintenance_runtime.ts) and the
30
30
  * `dexbot bot` editor hint (account_bots.ts) so the two can never drift.
31
- * activeOrders/reserveOrders are re-read via the targeted-reconcile path,
31
+ * coreOrders/edgeOrders are re-read via the targeted-reconcile path,
32
32
  * botFunds via recalculateFunds, weightDistribution base via
33
33
  * refreshDynamicWeightDistribution, min_BTS_value via the fee/acquisition
34
34
  * reads, and debtPolicy via the credit runtime's live getter (next credit
@@ -36,8 +36,8 @@ export const RUNTIME_SETTINGS_KEYS = [
36
36
  * (re)starts the credit watchdog, removal stops it).
37
37
  */
38
38
  export const BOT_LIVE_CONFIG_KEYS = [
39
- 'activeOrders',
40
- 'reserveOrders',
39
+ 'coreOrders',
40
+ 'edgeOrders',
41
41
  'botFunds',
42
42
  'weightDistribution',
43
43
  'min_BTS_value',
@@ -23,10 +23,22 @@ export type OrderState = 'virtual' | 'active' | 'partial';
23
23
  * behind it). Only a chain sync can tell the two apart,
24
24
  * so it arms the refresh too; the out-of-spread staleness
25
25
  * watchdog remains the backstop if the sync heals nothing.
26
+ * cold-book — no live order on either side (readiness P-A): there is
27
+ * no realized spread to repair. The reconcile path owns
28
+ * the first window; a targeted sync is armed.
29
+ * unmatched-orders — readiness P-C: the only tightening candidates collided
30
+ * with known-unmatched chain orders, so planning skipped
31
+ * them and let the sync adopt them first.
32
+ * readiness-gate — the readiness gate itself failed (threw), so the cycle
33
+ * was refused correct-by-refusal. A fault to triage, not
34
+ * a structural candidate condition.
26
35
  * batch-not-executed— a plan was prepared but the COW batch did not run.
27
36
  * apply-error — the broadcast threw.
37
+ *
38
+ * ('stale-snapshot' is degraded-ok, not a stall: the planner still acts, it
39
+ * only withholds the LAST-FILL-GUARD bypass.)
28
40
  */
29
- export type SpreadCorrectionStall = 'no-free-funds' | 'unfunded' | 'no-candidates' | 'batch-not-executed' | 'apply-error';
41
+ export type SpreadCorrectionStall = 'no-free-funds' | 'unfunded' | 'no-candidates' | 'cold-book' | 'unmatched-orders' | 'readiness-gate' | 'batch-not-executed' | 'apply-error';
30
42
  /**
31
43
  * Dict with unknown values. The canonical replacement for
32
44
  * `Record<string, any>`; callers must narrow a value before using it.
@@ -210,6 +222,7 @@ export interface BotLike {
210
222
  _gridLockHoldWarnAt: number;
211
223
  _outOfSpreadSince: number;
212
224
  _outOfSpreadStaleWarned: boolean;
225
+ _outOfSpreadTransientCount: number;
213
226
  _strandedHoldSince: Map<string, number>;
214
227
  _recoverySyncInFlight: number;
215
228
  _batchInFlight: number;
@@ -484,6 +497,22 @@ export interface BotMetrics extends UnknownRecord {
484
497
  maxQueueDepth: number;
485
498
  gridLockContention: number;
486
499
  fundRecalcCount: number;
500
+ /** Genuine post-broadcast commit refusals (working grid rejected). Excludes a poll-confirmed success that merely reuses the recovery funnel for adoption. */
501
+ refusedCommitCount: number;
502
+ /** Orphan fills whose proceeds were credited outside slot accounting. */
503
+ orphanFillCreditedCount: number;
504
+ /** BUY emissions at/above the last filled BUY pivot (guard bypass / leak). */
505
+ restampBuyAboveAnchorCount: number;
506
+ /** Derived boundary moved more than the active window in one plan. */
507
+ boundaryDriftExceedsWindowCount: number;
508
+ /** Non-spread-correction CREATE/UPDATE destinations inside the gap band (shadow). */
509
+ gapBandPlacementShadowCount: number;
510
+ /** Every spread-correction batch that failed to land (executed !== true), any cause. */
511
+ spreadCorrectionRefusedCount: number;
512
+ /** Spread-correction refusal breakdown keyed by SPREAD_CORRECTION_REFUSAL value (commit-refused, version-mismatch, create-collision, update-target-missing, unmatched-chain-orders, shutdown, batch-not-executed). */
513
+ spreadCorrectionRefusalCauses: Record<string, number>;
514
+ /** Bounded re-plan retries attempted after a transient spread-correction refusal. */
515
+ spreadCorrectionRetryCount: number;
487
516
  }
488
517
  /** An unmatched chain order surfaced by a sync pass. */
489
518
  export interface UnmatchedChainOrder extends UnknownRecord {
@@ -562,8 +591,8 @@ export interface ManagedOrder {
562
591
  sideHint?: string;
563
592
  [key: string]: unknown;
564
593
  }
565
- /** Active-order target counts. */
566
- export interface ActiveOrdersConfig extends UnknownRecord {
594
+ /** Market-order target counts (core-order window). */
595
+ export interface CoreOrdersConfig extends UnknownRecord {
567
596
  buy?: number;
568
597
  sell?: number;
569
598
  }
@@ -598,7 +627,7 @@ export interface GridConfig extends UnknownRecord {
598
627
  [key: string]: unknown;
599
628
  };
600
629
  targetSpreadPercent?: number;
601
- activeOrders?: ActiveOrdersConfig;
630
+ coreOrders?: CoreOrdersConfig;
602
631
  assetA?: string;
603
632
  assetB?: string;
604
633
  botKey?: string;
@@ -649,6 +678,16 @@ interface TimingConfig extends UnknownRecord {
649
678
  BLOCKCHAIN_FETCH_INTERVAL_MIN?: number;
650
679
  BOTS_CONFIG_POLL_INTERVAL_MS?: number;
651
680
  BTS_ACQUIRE_COOLDOWN_MIN?: number;
681
+ /**
682
+ * Spread-correction trust window (ms). How old the last completed
683
+ * open-orders sync may be before the local snapshot is treated as stale
684
+ * (the planner still acts but loses the LAST-FILL-GUARD bypass), and how
685
+ * often the live market price is re-read for the crossing floor. Defaults to
686
+ * `TIMING.SPREAD_CORRECTION_SYNC_FRESH_MS` (10 min); a non-positive value
687
+ * disables the time bound entirely (snapshot is never stale and the live
688
+ * price is never force-refreshed, so the floor stays on the fill anchor).
689
+ */
690
+ SPREAD_CORRECTION_SYNC_FRESH_MS?: number;
652
691
  }
653
692
  /** `config.fillProcessing` knobs read by the fill consumer. */
654
693
  interface FillProcessingConfig extends UnknownRecord {
@@ -821,6 +860,7 @@ export interface AccountOrdersLike {
821
860
  loadGenesis(forceReload?: boolean): unknown;
822
861
  loadGapEvacStreaks(forceReload?: boolean): unknown;
823
862
  loadLastFillPivot?(forceReload?: boolean): unknown;
863
+ loadLastMarketFill?(forceReload?: boolean): unknown;
824
864
  loadPendingFillCrawls(forceReload?: boolean): unknown[];
825
865
  loadRecentFillKeys(forceReload?: boolean): unknown;
826
866
  loadPersistedAssets(forceReload?: boolean): {
@@ -832,6 +872,8 @@ export interface AccountOrdersLike {
832
872
  clearGrid(): Promise<unknown>;
833
873
  clearPersistedBoundary(...args: unknown[]): Promise<unknown>;
834
874
  clearPersistedLastFillPivot(...args: unknown[]): Promise<unknown>;
875
+ clearPersistedLastMarketFill?(...args: unknown[]): Promise<unknown>;
876
+ backupSnapshot?(reason?: string): Promise<string | null>;
835
877
  loadProcessedFills(options?: boolean | {
836
878
  forceReload?: boolean;
837
879
  minTimestamp?: number | null;
@@ -999,6 +1041,8 @@ export interface OrderManagerLike {
999
1041
  createdAt?: number;
1000
1042
  } | null;
1001
1043
  _missingGenesis?: unknown;
1044
+ _metrics?: BotMetrics;
1045
+ _lastBoundaryDriftWarnAt?: number;
1002
1046
  _genesisInvariantViolations?: number;
1003
1047
  _genesisInvariantLoggedAt?: number;
1004
1048
  _fundDriftLedger?: {
@@ -1014,6 +1058,13 @@ export interface OrderManagerLike {
1014
1058
  _lastFilledType: string | null;
1015
1059
  _lastFilledAt: number | null;
1016
1060
  lastFillPivotSource: 'fill' | 'book' | null;
1061
+ _lastMarketFillPrice?: number | null;
1062
+ _lastMarketFillType?: string | null;
1063
+ _lastMarketFillAt?: number | null;
1064
+ _liveMarketPrice?: number | null;
1065
+ _liveMarketPriceAt?: number | null;
1066
+ _liveMarketPriceAttemptedAt?: number | null;
1067
+ _lastSyncAt?: number;
1017
1068
  _lastUnmatchedChainOrders?: UnmatchedChainOrder[];
1018
1069
  _lastUnmatchedChainOrdersAt?: number;
1019
1070
  _lastAccountingFailure?: unknown;
@@ -590,7 +590,6 @@ async function main() {
590
590
  const ignoredRows = crRows.filter((r) => !r.supported);
591
591
  const pricedSupported = supportedRows.filter((r) => r.cr !== null && r.value !== null && r.debtFloat !== null);
592
592
  const unpricedSupported = supportedRows.filter((r) => r.cr === null);
593
- const avgCr = averageCreditCr(pricedSupported.map((r) => ({ debt: r.debtFloat, value: r.value })));
594
593
  async function fmtParts(m, showBiggest = false) {
595
594
  if (m.size === 0)
596
595
  return [];
@@ -639,39 +638,57 @@ async function main() {
639
638
  await printAssetLines('Credit coll', creditSumAll.coll, true, colors.buy);
640
639
  if (creditPairs.length > 0)
641
640
  console.log('');
642
- // Compact CR summary: one Avar. CR line per bot, then one Curr. CR
643
- // line per whitelisted pair. A CR exists only for pairs both whitelisted
644
- // in bots.json and listed on the current credit offer.
641
+ // Compact CR summary: one Avar. CR line per borrowed credit (debt
642
+ // asset), then one Curr. CR line per whitelisted pair. A CR exists only
643
+ // for pairs both whitelisted in bots.json and listed on the current
644
+ // credit offer.
645
645
  const feeDenom = Number(FEE_PARAMETERS?.GRAPHENE_FEE_RATE_DENOM) || 1000000;
646
646
  const walletRaw = await fetchWalletRaw(account);
647
647
  const matchPair = (pair, r) => (pair.debtId !== null && r.debtId !== null && pair.debtId === r.debtId && pair.collId !== null && r.collId !== null && pair.collId === r.collId) ||
648
648
  (isSameAssetSymbol(pair.debtSym, r.debtSym) && isSameAssetSymbol(pair.collSym, r.collSym));
649
- if (avgCr !== null) {
650
- // Label in orange to distinguish from Curr. CR; value keeps the
651
- // original health color (single shared max → green/red, mixed or
652
- // undefined max → white).
653
- const avgMaxSet = new Set();
649
+ if (pricedSupported.length > 0) {
650
+ // Group by borrowed credit (debt asset) so unrelated debt assets are
651
+ // not blended into one figure; each line carries its own
652
+ // value-weighted average CR.
653
+ const debtGroups = new Map();
654
654
  for (const r of pricedSupported) {
655
- const pair = creditPairs.find((p) => matchPair(p, r));
656
- if (pair?.maxCR != null)
657
- avgMaxSet.add(pair.maxCR);
655
+ const key = r.debtId ?? `sym:${normalizeAssetSymbol(r.debtSym)}`;
656
+ if (!debtGroups.has(key))
657
+ debtGroups.set(key, { debtSym: r.debtSym, rows: [] });
658
+ debtGroups.get(key).rows.push(r);
658
659
  }
659
- const avgMax = avgMaxSet.size === 1 ? [...avgMaxSet][0] : null;
660
- const avgColor = avgMax === null ? colors.white : avgCr > avgMax ? colors.sell : colors.buy;
661
- const pairTotals = new Map();
662
- for (const r of pricedSupported) {
663
- const key = `${r.debtSym}←${r.collSym}`;
664
- if (!pairTotals.has(key)) {
665
- pairTotals.set(key, { debtSym: r.debtSym, collSym: r.collSym, debt: 0, coll: 0 });
660
+ // Largest borrowed credit first so the biggest exposure leads.
661
+ const debtOrder = [...debtGroups.values()].sort((a, b) => b.rows.reduce((s, r) => s + (r.debtFloat || 0), 0)
662
+ - a.rows.reduce((s, r) => s + (r.debtFloat || 0), 0));
663
+ for (const group of debtOrder) {
664
+ const groupCr = averageCreditCr(group.rows.map((r) => ({ debt: r.debtFloat, value: r.value })));
665
+ if (groupCr === null)
666
+ continue;
667
+ // Label in orange to distinguish from Curr. CR; value keeps the
668
+ // original health color (single shared max → green/red, mixed or
669
+ // undefined max → white).
670
+ const groupMaxSet = new Set();
671
+ for (const r of group.rows) {
672
+ const pair = creditPairs.find((p) => matchPair(p, r));
673
+ if (pair?.maxCR != null)
674
+ groupMaxSet.add(pair.maxCR);
675
+ }
676
+ const groupMax = groupMaxSet.size === 1 ? [...groupMaxSet][0] : null;
677
+ const groupColor = groupMax === null ? colors.white : groupCr > groupMax ? colors.sell : colors.buy;
678
+ const collTotals = new Map();
679
+ for (const r of group.rows) {
680
+ const key = r.collId ?? `sym:${normalizeAssetSymbol(r.collSym)}`;
681
+ if (!collTotals.has(key))
682
+ collTotals.set(key, { collSym: r.collSym, debt: 0, coll: 0 });
683
+ const t = collTotals.get(key);
684
+ t.debt += r.debtFloat || 0;
685
+ t.coll += r.collFloat || 0;
666
686
  }
667
- const t = pairTotals.get(key);
668
- t.debt += r.debtFloat || 0;
669
- t.coll += r.collFloat || 0;
687
+ const segments = [...collTotals.values()]
688
+ .map((t) => `${formatAmount(t.debt)} ${group.debtSym} ← ${formatAmount(t.coll)} ${t.collSym}`)
689
+ .join(' + ');
690
+ console.log(` ${colors.orange}${colors.bold}Avar. CR:${colors.reset} ${groupColor}${formatAmount(groupCr)}${colors.reset}, ${segments} ${colors.gray}(x${group.rows.length})${colors.reset}`);
670
691
  }
671
- const segments = [...pairTotals.values()]
672
- .map((t) => `${formatAmount(t.debt)} ${t.debtSym} ← ${formatAmount(t.coll)} ${t.collSym}`)
673
- .join(' + ');
674
- console.log(` ${colors.orange}${colors.bold}Avar. CR:${colors.reset} ${avgColor}${formatAmount(avgCr)}${colors.reset}, ${segments} ${colors.gray}(x${pricedSupported.length})${colors.reset}`);
675
692
  }
676
693
  else if (supportedRows.length > 0) {
677
694
  console.log(` ${colors.orange}${colors.bold}Avar. CR:${colors.reset} n/a (no priced, available credit)`);
@@ -686,7 +703,7 @@ async function main() {
686
703
  reasons.push(`${unpriced} no offer price`);
687
704
  console.log(` ${colors.gray}Excluded: ${ignored + unpriced} deal${ignored + unpriced === 1 ? '' : 's'} (${reasons.join(', ')})${colors.reset}`);
688
705
  }
689
- if ((avgCr !== null || supportedRows.length > 0) && creditPairs.length > 0)
706
+ if (supportedRows.length > 0 && creditPairs.length > 0)
690
707
  console.log('');
691
708
  for (const pair of creditPairs) {
692
709
  const pairRows = supportedRows.filter((r) => matchPair(pair, r));
@@ -63,7 +63,7 @@ interface BotConfig {
63
63
  targetSpreadPercent?: unknown;
64
64
  incrementPercent?: unknown;
65
65
  gridPrice?: unknown;
66
- activeOrders?: unknown;
66
+ coreOrders?: unknown;
67
67
  botFunds?: JsonObj;
68
68
  weightDistribution?: JsonObj;
69
69
  [key: string]: unknown;
@@ -539,7 +539,7 @@ function analyzeOrder(botData, config, botKey) {
539
539
  sell: sellSlots
540
540
  },
541
541
  // Target active orders from config
542
- activeOrdersTarget: config ? config.activeOrders : null,
542
+ coreOrdersTarget: config ? config.coreOrders : null,
543
543
  // Bot fund allocation settings from config (normalized to strings for
544
544
  // the display paths; bots.json allows percentage strings or numbers)
545
545
  botFunds: config && config.botFunds
@@ -1137,9 +1137,9 @@ function formatAnalysis(analysisInput) {
1137
1137
  lines.push(` Spread:${formatPercent(analysis.spread.real).padStart(6)} | Incr.:${formatPercent(analysis.increment.avg).padStart(6)}`);
1138
1138
  }
1139
1139
  // Active orders comparison
1140
- if (analysis.hasConfig && analysis.activeOrdersTarget) {
1141
- const buyTarget = analysis.activeOrdersTarget.buy;
1142
- const sellTarget = analysis.activeOrdersTarget.sell;
1140
+ if (analysis.hasConfig && analysis.coreOrdersTarget) {
1141
+ const buyTarget = analysis.coreOrdersTarget.buy;
1142
+ const sellTarget = analysis.coreOrdersTarget.sell;
1143
1143
  const buyActual = analysis.slots.activeBuy;
1144
1144
  const sellActual = analysis.slots.activeSell;
1145
1145
  // Collect raw buy/sell values across Active, Weight, Funds for column alignment
@@ -3,9 +3,12 @@ import { createRequire } from 'node:module';
3
3
  const require = createRequire(import.meta.url);
4
4
  'use strict';
5
5
  /**
6
- * Diagnostic: Inspect raw BitShares pool history API responses for pool 1.19.133.
6
+ * Diagnostic: Inspect raw BitShares pool history API responses for a liquidity pool.
7
7
  *
8
- * Usage: node dist/scripts/diagnose-pool-history.js [--pool <id>] [--limit <n>] [--hours <n>] [--maxPages <n>]
8
+ * The pool ID must be a concrete object ID (e.g. 1.19.133); placeholders such as
9
+ * "1.19.x" are rejected up front because the node cannot parse them as a uint64.
10
+ *
11
+ * Usage: node dist/scripts/diagnose-pool-history.js [--pool <1.19.N>] [--limit <n>] [--hours <n>] [--maxPages <n>]
9
12
  */
10
13
  const { BitShares, waitForConnected } = require('../modules/bitshares_client');
11
14
  const { getErrorMessage } = require('../modules/utils/errors');
@@ -23,6 +26,15 @@ const MAX_PAGES = process.argv.includes('--maxPages')
23
26
  ? Number(process.argv[process.argv.indexOf('--maxPages') + 1])
24
27
  : 20;
25
28
  const LP_OP_TYPE = 63;
29
+ // Fail fast on non-numeric pool IDs: the node parses the instance of a 1.19.N
30
+ // object ID as a uint64, so a placeholder like "1.19.x" surfaces as an opaque
31
+ // remote "Parse Error: Couldn't parse uint64_t".
32
+ if (!/^1\.19\.\d+$/.test(POOL_ID)) {
33
+ console.error(`Invalid pool ID: "${POOL_ID}"`);
34
+ console.error('Expected a numeric liquidity-pool object ID, e.g. 1.19.133 (not "1.19.x").');
35
+ console.error('Usage: node dist/scripts/diagnose-pool-history.js [--pool <1.19.N>] [--limit <n>] [--hours <n>] [--maxPages <n>]');
36
+ process.exit(1);
37
+ }
26
38
  function fmt(obj) {
27
39
  try {
28
40
  return JSON.stringify(obj);
@@ -198,43 +210,33 @@ async function main() {
198
210
  catch (err) {
199
211
  console.log(`Could not list methods: ${getErrorMessage(err)}`);
200
212
  }
201
- // ── Test 4: Try get_account_history for pool account ───────────
202
- console.log(`\n\n═══ TEST 4: get_account_history_by_operations for pool account ═══`);
213
+ // ── Test 4: get_liquidity_pool_history_by_sequence (pagination) ──
214
+ // Account-history APIs (get_account_history_by_operations,
215
+ // get_relative_account_history) do NOT apply here: a liquidity pool
216
+ // (1.19.N) is not an account (1.2.N). Their object IDs as the start/stop
217
+ // sequence arguments is what produced the old "Couldn't parse uint64_t".
218
+ console.log(`\n\n═══ TEST 4: get_liquidity_pool_history_by_sequence(poolId, startSeq, null, ${LIMIT}, 63) ═══`);
203
219
  try {
204
- // Pool "account" is 1.19.133 — try account history API
205
- if (typeof BitShares.history.get_account_history_by_operations === 'function') {
206
- const rows = await BitShares.history.get_account_history_by_operations(POOL_ID, [LP_OP_TYPE], '1.19.0', '1.19.999', LIMIT);
207
- console.log(`Result: ${Array.isArray(rows) ? `Array[${rows.length}]` : typeof rows}`);
208
- if (Array.isArray(rows)) {
209
- rows.slice(0, 3).forEach((r, i) => inspectRow(r, i));
210
- }
220
+ const firstPage = await BitShares.history.get_liquidity_pool_history(POOL_ID, null, null, LIMIT, LP_OP_TYPE);
221
+ const firstRows = Array.isArray(firstPage) ? firstPage : [];
222
+ const lastSeq = Number(firstRows[firstRows.length - 1]?.sequence);
223
+ if (!Number.isFinite(lastSeq) || lastSeq <= 1) {
224
+ console.log(`No usable sequence to page from (first page length: ${firstRows.length})`);
211
225
  }
212
226
  else {
213
- console.log('get_account_history_by_operations NOT available');
214
- }
215
- }
216
- catch (err) {
217
- console.log(`ERROR: ${getErrorMessage(err)}`);
218
- }
219
- // ── Test 5: Try get_relative_account_history ─────────────────
220
- console.log(`\n\n═══ TEST 5: get_relative_account_history ═══`);
221
- try {
222
- if (typeof BitShares.history.get_relative_account_history === 'function') {
223
- const rows = await BitShares.history.get_relative_account_history(POOL_ID, 0, LIMIT, 0);
227
+ const startSeq = lastSeq - 1;
228
+ const rows = await BitShares.history.get_liquidity_pool_history_by_sequence(POOL_ID, startSeq, null, LIMIT, LP_OP_TYPE);
224
229
  console.log(`Result: ${Array.isArray(rows) ? `Array[${rows.length}]` : typeof rows}`);
225
230
  if (Array.isArray(rows)) {
226
- rows.slice(0, 3).forEach((r, i) => inspectRow(r, i));
231
+ rows.slice(0, 5).forEach((r, i) => inspectRow(r, i));
227
232
  }
228
233
  }
229
- else {
230
- console.log('get_relative_account_history NOT available');
231
- }
232
234
  }
233
235
  catch (err) {
234
236
  console.log(`ERROR: ${getErrorMessage(err)}`);
235
237
  }
236
- // ── Test 6: Last 24h of trades — try to query recent only ─────
237
- console.log(`\n\n═══ TEST 6: Last 100 results with larger limit ═══`);
238
+ // ── Test 5: Last 24h of trades — try to query recent only ─────
239
+ console.log(`\n\n═══ TEST 5: Last 100 results with larger limit ═══`);
238
240
  try {
239
241
  const rows = await BitShares.history.get_liquidity_pool_history(POOL_ID, null, null, 100, LP_OP_TYPE);
240
242
  console.log(`Result: ${Array.isArray(rows) ? `Array[${rows.length}]` : typeof rows}`);
@@ -262,8 +264,8 @@ async function main() {
262
264
  catch (err) {
263
265
  console.log(`ERROR: ${getErrorMessage(err)}`);
264
266
  }
265
- // ── Test 7: Paged recent summary ──────────────────────────────
266
- console.log(`\n\n═══ TEST 7: Paged LP history summary, last ${HOURS}h ═══`);
267
+ // ── Test 6: Paged recent summary ──────────────────────────────
268
+ console.log(`\n\n═══ TEST 6: Paged LP history summary, last ${HOURS}h ═══`);
267
269
  try {
268
270
  const sinceMs = Date.now() - (HOURS * 3600 * 1000);
269
271
  const collected = await collectRecentPoolHistory(POOL_ID, sinceMs, Math.min(101, LIMIT), MAX_PAGES);
@@ -290,6 +292,9 @@ async function main() {
290
292
  if (typeof BitShares.disconnect === 'function') {
291
293
  BitShares.disconnect();
292
294
  }
295
+ // Force-exit: the native transport keeps reconnect timers alive and exposes
296
+ // no way to disable autoreconnect, so without this the process never exits.
297
+ process.exit(0);
293
298
  }
294
299
  main().catch(err => {
295
300
  console.error(`Fatal: ${getErrorMessage(err)}`);