dexbot 1.6.15 → 1.6.17

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 (130) hide show
  1. package/CHANGELOG.md +52 -0
  2. package/README.md +4 -4
  3. package/analysis/tradingview/README.md +2 -2
  4. package/analysis/trend_detection/DYNAMIC_WEIGHT_RESEARCH.md +1 -1
  5. package/claw/docs/DEXBOT2_TUNING_CHEAT_SHEET.md +3 -2
  6. package/claw/modules/chain_queries.ts +3 -3
  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/ama_fitting/fetch_lp_candles.js +8 -1
  12. package/dist/analysis/ama_fitting/optimizer_high_resolution.d.ts +50 -1
  13. package/dist/analysis/ama_fitting/optimizer_high_resolution.js +33 -7
  14. package/dist/analysis/bot_fitting/backtest_bot_fitting.d.ts +8 -6
  15. package/dist/analysis/bot_fitting/backtest_bot_fitting.js +8 -10
  16. package/dist/analysis/bot_key_utils.js +9 -7
  17. package/dist/analysis/chart_utils.d.ts +9 -2
  18. package/dist/analysis/chart_utils.js +51 -1
  19. package/dist/analysis/tradingview/grid_reset_sim.js +1 -1
  20. package/dist/analysis/tradingview/tradingview_uplot_chart_generator.d.ts +2 -1
  21. package/dist/analysis/tradingview/tradingview_uplot_chart_generator.js +23 -9
  22. package/dist/analysis/trend_detection/backtest_ama_slope_huber.js +1 -1
  23. package/dist/analysis/trend_detection/dynamic_weight_chart_generator.js +21 -2
  24. package/dist/analysis/trend_detection/kalman_chart_generator.js +1 -0
  25. package/dist/analysis/trend_detection/regime_chart_generator.js +1 -1
  26. package/dist/analysis/trend_detection/volatility_chart_generator.js +1 -0
  27. package/dist/dexbot.js +89 -138
  28. package/dist/market_adapter/inputs/fetch_book_data.js +36 -12
  29. package/dist/market_adapter/inputs/fetch_lp_data.d.ts +6 -0
  30. package/dist/market_adapter/inputs/fetch_lp_data.js +65 -19
  31. package/dist/market_adapter/inputs/kibana_feed_source.js +45 -12
  32. package/dist/market_adapter/inputs/window_cache.d.ts +14 -1
  33. package/dist/market_adapter/inputs/window_cache.js +53 -17
  34. package/dist/market_adapter/lp_chart_core.js +1 -0
  35. package/dist/market_adapter/utils/chain.js +4 -3
  36. package/dist/market_adapter/utils/pair_orientation.d.ts +60 -0
  37. package/dist/market_adapter/utils/pair_orientation.js +142 -0
  38. package/dist/modules/account_bots.d.ts +40 -3
  39. package/dist/modules/account_bots.js +77 -37
  40. package/dist/modules/account_orders.d.ts +4 -1
  41. package/dist/modules/account_orders.js +4 -1
  42. package/dist/modules/bitshares-native/resolvers.js +3 -3
  43. package/dist/modules/bitshares_client.d.ts +12 -10
  44. package/dist/modules/bitshares_client.js +12 -10
  45. package/dist/modules/bot_settings.js +3 -3
  46. package/dist/modules/chain_keys.d.ts +6 -2
  47. package/dist/modules/chain_keys.js +5 -1
  48. package/dist/modules/chain_orders.d.ts +6 -2
  49. package/dist/modules/chain_orders.js +6 -2
  50. package/dist/modules/constants.d.ts +11 -0
  51. package/dist/modules/constants.js +41 -7
  52. package/dist/modules/credit_pricing.d.ts +20 -1
  53. package/dist/modules/credit_pricing.js +23 -1
  54. package/dist/modules/credit_runtime.js +33 -16
  55. package/dist/modules/dexbot_class.d.ts +6 -2
  56. package/dist/modules/dexbot_class.js +8 -3
  57. package/dist/modules/dexbot_cow_runtime.d.ts +28 -37
  58. package/dist/modules/dexbot_cow_runtime.js +47 -66
  59. package/dist/modules/dexbot_maintenance_runtime.js +68 -10
  60. package/dist/modules/graceful_shutdown.d.ts +6 -2
  61. package/dist/modules/graceful_shutdown.js +6 -2
  62. package/dist/modules/launcher/bot_supervisor.js +4 -0
  63. package/dist/modules/launcher/credential_daemon.d.ts +14 -2
  64. package/dist/modules/launcher/credential_daemon.js +60 -26
  65. package/dist/modules/launcher/launch_modes.js +6 -3
  66. package/dist/modules/launcher/monolithic_runtime.d.ts +39 -1
  67. package/dist/modules/launcher/monolithic_runtime.js +60 -1
  68. package/dist/modules/launcher/runtime_mode.d.ts +79 -0
  69. package/dist/modules/launcher/runtime_mode.js +223 -0
  70. package/dist/modules/market_adapter_whitelist.d.ts +8 -0
  71. package/dist/modules/market_adapter_whitelist.js +8 -0
  72. package/dist/modules/order/accounting.d.ts +15 -1
  73. package/dist/modules/order/accounting.js +15 -1
  74. package/dist/modules/order/async_lock.d.ts +9 -3
  75. package/dist/modules/order/async_lock.js +9 -3
  76. package/dist/modules/order/export.d.ts +0 -5
  77. package/dist/modules/order/export.js +0 -5
  78. package/dist/modules/order/format.d.ts +6 -4
  79. package/dist/modules/order/format.js +6 -4
  80. package/dist/modules/order/grid.d.ts +36 -18
  81. package/dist/modules/order/grid.js +186 -33
  82. package/dist/modules/order/index.d.ts +16 -1
  83. package/dist/modules/order/index.js +1 -1
  84. package/dist/modules/order/logger_state.d.ts +1 -1
  85. package/dist/modules/order/logger_state.js +1 -1
  86. package/dist/modules/order/manager.d.ts +30 -7
  87. package/dist/modules/order/manager.js +108 -12
  88. package/dist/modules/order/strategy.d.ts +5 -0
  89. package/dist/modules/order/strategy.js +23 -2
  90. package/dist/modules/order/sync_engine.d.ts +26 -11
  91. package/dist/modules/order/sync_engine.js +26 -11
  92. package/dist/modules/order/utils/math.d.ts +100 -22
  93. package/dist/modules/order/utils/math.js +106 -22
  94. package/dist/modules/order/utils/order.d.ts +77 -20
  95. package/dist/modules/order/utils/order.js +125 -27
  96. package/dist/modules/order/utils/system.d.ts +107 -11
  97. package/dist/modules/order/utils/system.js +176 -11
  98. package/dist/modules/order/utils/validate.d.ts +8 -3
  99. package/dist/modules/order/utils/validate.js +10 -3
  100. package/dist/modules/types.d.ts +35 -2
  101. package/dist/modules/utils/asset_symbols.d.ts +5 -5
  102. package/dist/modules/utils/asset_symbols.js +5 -5
  103. package/dist/modules/utils/errors.d.ts +2 -1
  104. package/dist/modules/utils/errors.js +2 -1
  105. package/dist/scripts/analyze-credit.js +64 -23
  106. package/dist/scripts/bts_distribution.d.ts +66 -0
  107. package/dist/scripts/bts_distribution.js +2102 -0
  108. package/dist/scripts/rich_list.d.ts +32 -0
  109. package/dist/scripts/rich_list.js +16 -8
  110. package/dist/scripts/token_distribution.d.ts +45 -0
  111. package/dist/scripts/token_distribution.js +1870 -0
  112. package/dist/unlock.js +91 -42
  113. package/docs/BITSHARES_ONBOARDING.md +7 -0
  114. package/docs/COW_INVARIANTS.md +7 -1
  115. package/docs/DEXBOT_COMPARISON.md +5 -5
  116. package/docs/EVOLUTION.md +10 -8
  117. package/docs/FUND_MOVEMENT_AND_ACCOUNTING.md +5 -3
  118. package/docs/GRID_PRICE_INVARIANT.md +6 -0
  119. package/docs/GRID_RECALCULATION.md +18 -6
  120. package/docs/LIFECYCLE.md +8 -8
  121. package/docs/LOGGING.md +9 -0
  122. package/docs/MPA_CREDIT_USAGE.md +3 -2
  123. package/docs/ORDER_ENGINE_POST_1.0_RETROSPECTIVE.md +121 -4
  124. package/docs/README.md +1 -1
  125. package/docs/WORKFLOW.md +5 -5
  126. package/docs/architecture.md +98 -1
  127. package/market_adapter/README.md +10 -3
  128. package/package.json +5 -1
  129. package/scripts/README.md +85 -148
  130. package/tests/README.md +29 -0
@@ -4,45 +4,75 @@
4
4
  * Price derivation, persistence, grid correction, and UI/interactive utilities.
5
5
  *
6
6
  * ===============================================================================
7
- * TABLE OF CONTENTS (21 exported functions)
7
+ * TABLE OF CONTENTS (43 exported functions + 11 structural view types)
8
8
  * ===============================================================================
9
9
  *
10
- * SECTION 1: PRICE DERIVATION (10 functions)
10
+ * SECTION 1: PRICE DERIVATION (9 functions + 1 internal)
11
11
  * - lookupAsset(BitShares, symbol) - Lookup asset metadata from blockchain
12
+ * - resolveAssetByRef(BitShares, ref) - Resolve a full asset object from id/symbol
12
13
  * - deriveMarketPrice(BitShares, symA, symB) - Derive price from order book
13
14
  * - derivePoolPrice(BitShares, symA, symB) - Derive price from liquidity pool
15
+ * - setDerivePriceTestHook(hook) - Test-only seam for derivePrice
14
16
  * - derivePrice(BitShares, symA, symB, mode) - Derive price with fallback chain
15
17
  * - derivePriceViaBridges(BitShares, symA, symB, bridges, mode) - Multi-hop price via bridge assets
16
18
  * - derivePriceWithBridges(BitShares, symA, symB, bridges, mode) - Direct price, else bridge hops
17
- * - resolveLiquidityPoolByShareAsset(BitShares, shareAsset) - Resolve LP by share asset
18
19
  * - deriveLiquidityPoolTokenValue(BitShares, symA, symB) - Derive LP token value
19
- * - loadAmaCenterPrice(manager) - Load AMA center price
20
- * - loadAmaCenterSnapshot(manager) - Load AMA center snapshot
20
+ * - resolveLiquidityPoolByShareAsset(BitShares, shareAsset) - Resolve LP by share asset (internal)
21
21
  *
22
- * SECTION 2: FEE MANAGEMENT (1 function)
22
+ * SECTION 2: AMA CENTER SNAPSHOT (2 functions)
23
+ * - loadAmaCenterSnapshot(manager) - Load the full dynamic-grid snapshot
24
+ * - loadAmaCenterPrice(manager) - Load the AMA center price
25
+ *
26
+ * SECTION 3: FEE MANAGEMENT (1 function)
23
27
  * - initializeFeeCache(botsConfig, BitShares) - Initialize fee cache from blockchain
24
28
  *
25
- * SECTION 3: GRID STATE MANAGEMENT (3 functions)
29
+ * SECTION 4: GRID STATE MANAGEMENT (5 functions)
26
30
  * - persistGridSnapshot(manager, accountOrders) - Persist grid to storage
31
+ * - restoreGapEvacStreaks(manager) - Restore persisted gap-evacuation streaks
27
32
  * - retryPersistenceIfNeeded(manager) - Retry persistence if previous failed
28
33
  * - applyGridDivergenceCorrections(manager, ...) - Apply grid divergence corrections
29
- *
30
- * SECTION 4: UI & INTERACTIVE UTILITIES (7 functions)
34
+ * - applyPersistedPendingCrawls(...) - Apply persisted-but-uncommitted fill crawls
35
+ *
36
+ * SECTION 5: SPREAD-CORRECTION READINESS (7 functions)
37
+ * - resolveSpreadFreshnessMs(manager) - The single freshness window for spread trust
38
+ * - resolveSpreadCrossingFloor(manager) - Crossing floor spread correction must not trade through
39
+ * - refreshLiveMarketPrice(manager) - Refresh the cached live market price
40
+ * - maybeRefreshLiveMarketPrice(manager) - Refresh if stale, paced to one attempt per window
41
+ * - evaluateSpreadCorrectionReadiness(manager) - Evaluate whether spread correction may act
42
+ * - resolveSpreadMarketReference(manager) - Resolve the last real FILL price
43
+ * - resolveLastFillGuardReference(manager) - Resolve the reference the LAST-FILL-GUARD judges
44
+ *
45
+ * SECTION 6: LAST-FILL / MARKET-FILL PERSISTENCE (6 functions)
46
+ * - restoreLastMarketFill(manager) - Restore the persisted last-market-fill reference
47
+ * - normalizeLastFillPivot(row) - Normalize a persisted LAST-FILL-GUARD pivot row
48
+ * - normalizeLastMarketFill(row) - Normalize a persisted last-market-fill row
49
+ * - setLastFillPivot(manager, ...) - Write the LAST-FILL-GUARD pivot scalar family
50
+ * - resetLastFillPivot(manager) - Clear the pivot to cold state
51
+ * - restoreLastFillPivot(manager) - Restore the persisted pivot into the manager
52
+ *
53
+ * SECTION 7: UI & INTERACTIVE UTILITIES (6 functions)
31
54
  * - ensureProfilesDirectory(profilesDir) - Ensure profiles directory exists
32
55
  * - sleep(ms) - Pause execution for specified duration
33
56
  * - readInput(prompt, options) - Read user input from stdin
34
57
  * - readPassword(prompt) - Read password with masked echo
35
58
  * - withRetry(fn, options) - Execute async function with exponential backoff
36
- * - withTimeout(promise, timeoutMs, options) - defined in ./timeout
37
59
  * - withBlockchainRetry(fn, label, options) - Blockchain op with timeout + retry + node failover
60
+ * (withTimeout lives in ./timeout)
38
61
  *
39
- * SECTION 6: GENERAL UTILITIES (5 functions)
62
+ * SECTION 8: GENERAL UTILITIES (7 functions)
40
63
  * - resolveAccountRef(manager, account) - Resolve best account reference
41
64
  * - deepFreeze(obj) - Recursively freeze object for immutability
42
65
  * - cloneMap(map) - Create shallow clone of Map
43
66
  * - ensureDir(dirPath) - Ensure directory exists, creating recursively
67
+ * - nowIso() - Current time as an ISO string
68
+ * - fireStructuralResync(manager, ...) - Fire-and-forget structural grid resync
44
69
  * - parseJsonWithComments(raw) - Parse JSON with comment stripping
45
70
  *
71
+ * STRUCTURAL VIEW TYPES:
72
+ * AssetMeta, PoolReserve, PoolEntry, BitSharesClient, AmaCenterSnapshot,
73
+ * FeeCacheEntryData, SpreadCorrectionRefusalReason, SpreadCorrectionReadiness,
74
+ * UnmatchedChainOrderLike, GridResizeResult, CowResult
75
+ *
46
76
  * ===============================================================================
47
77
  */
48
78
  import type { OrderManagerLike, BotLike, AccountOrdersLike, ManagedOrder, AccountTotals, CowAction } from '../../types.js';
@@ -468,10 +498,76 @@ export declare function resolveSpreadMarketReference(manager: OrderManagerLike):
468
498
  * @param {Object} manager - OrderManager instance
469
499
  * @returns {{price: number|null, type: string|null}} Effective pivot (both null when cold)
470
500
  */
501
+ /**
502
+ * Re-anchor the boundary so the newest REAL fill sits outside its own window.
503
+ *
504
+ * A boundary crawl is ±1 slot per committed fill, so a window that ended up
505
+ * behind the fill (a sweep filled several slots while the commit dropped the
506
+ * owed crawls, or the crawl was capped) cannot catch up by crawling: every
507
+ * tightening slot on that side is then at/through the last fill and the
508
+ * last-fill guard refuses all of them, while the funds sit in the resting
509
+ * (stranded) inventory — the 2026-10-25 deadlock (7 sells swept slots 147-153,
510
+ * the boundary ended at 146 and stayed there; `last-fill-blocked` thereafter).
511
+ *
512
+ * The fill itself is the anchor, so place it outside its window:
513
+ * SELL fill at slot f -> boundary >= f - gapSlots (sellStart = f + 1)
514
+ * BUY fill at slot f -> boundary <= f - 1 (buy window ends below f)
515
+ *
516
+ * Only a genuine on-ladder fill price is accepted (same one-increment drift
517
+ * bound as `resolveOnGridPivot`), and the candidate must pass the same
518
+ * placed-order-aware validation the boundary commit gate uses, so a re-anchor
519
+ * can never strand a live order inside the re-typed band.
520
+ *
521
+ * @param {Object} manager - OrderManager (pivot + genesis)
522
+ * @param {number|null} boundaryIdx - Boundary the derivation would commit
523
+ * @param {Array<Object>} slots - Grid slots (current generation)
524
+ * @param {number} gapSlots - Gap band width
525
+ * @returns {{boundaryIdx: number|null, reanchored: boolean, from?: number|null, to?: number, side?: string, fillSlot?: number, reason?: string}}
526
+ */
527
+ export declare function reanchorBoundaryFromLastFill(manager: OrderManagerLike, boundaryIdx: number | null | undefined, slots: ManagedOrder[] | null | undefined, gapSlots: number): {
528
+ boundaryIdx: number | null;
529
+ reanchored: boolean;
530
+ from?: number | null;
531
+ to?: number;
532
+ side?: string;
533
+ fillSlot?: number;
534
+ reason?: string;
535
+ };
471
536
  export declare function resolveLastFillGuardReference(manager: OrderManagerLike): {
472
537
  price: number | null;
473
538
  type: string | null;
474
539
  };
540
+ /**
541
+ * LAST-FILL-GUARD — DIRECTION ONLY, relative to the last fill price.
542
+ *
543
+ * BUY blocked if price >= pivot (never place a higher BUY)
544
+ * SELL blocked if price <= pivot (never place a lower SELL)
545
+ *
546
+ * Lives here (not in the COW runtime) so the spread-correction PLANNER and the
547
+ * broadcast guard judge candidates with literally the same predicate: a batch
548
+ * must never be built from a create the guard will drop, and a dropped batch
549
+ * must never be reported as an unexplained "prepared but not executed".
550
+ *
551
+ * A placement on the permitted side is always profitable against the last trade
552
+ * we actually did: a BUY below the last sell, a SELL above the last buy. Equal
553
+ * price counts as blocked — that is a re-place at the just-filled level, the
554
+ * immediate re-fill loop this guard exists to prevent. Cold (no numeric pivot,
555
+ * or no fill side recorded — e.g. a book-seeded pivot) => disabled. The grid
556
+ * increment takes no part (kept in the signature for call-site stability).
557
+ *
558
+ * @param {number} price - Target order price
559
+ * @param {number} _size - Order size (unused, kept for compat)
560
+ * @param {string} type - ORDER_TYPES.BUY/SELL
561
+ * @param {number|null} lastPrice - Most recent fill price
562
+ * @param {string|null} lastType - Most recent fill side; null keeps the guard cold
563
+ * @param {number|any} _incrementPercent - Unused (kept for signature compat)
564
+ * @returns {{blocked: boolean, pivot: number|null, threshold?: number|null}}
565
+ */
566
+ export declare function isLastFillGuardBlocked(price: number, _size: number, type: unknown, lastPrice: number | null, lastType: string | null, _incrementPercent?: number): {
567
+ blocked: boolean;
568
+ pivot: number | null;
569
+ threshold?: number | null;
570
+ };
475
571
  /**
476
572
  * Restore the persisted bot-scoped last-market-fill reference into the
477
573
  * manager. Deliberately independent of the boundary and the genesis: this is
@@ -4,45 +4,75 @@
4
4
  * Price derivation, persistence, grid correction, and UI/interactive utilities.
5
5
  *
6
6
  * ===============================================================================
7
- * TABLE OF CONTENTS (21 exported functions)
7
+ * TABLE OF CONTENTS (43 exported functions + 11 structural view types)
8
8
  * ===============================================================================
9
9
  *
10
- * SECTION 1: PRICE DERIVATION (10 functions)
10
+ * SECTION 1: PRICE DERIVATION (9 functions + 1 internal)
11
11
  * - lookupAsset(BitShares, symbol) - Lookup asset metadata from blockchain
12
+ * - resolveAssetByRef(BitShares, ref) - Resolve a full asset object from id/symbol
12
13
  * - deriveMarketPrice(BitShares, symA, symB) - Derive price from order book
13
14
  * - derivePoolPrice(BitShares, symA, symB) - Derive price from liquidity pool
15
+ * - setDerivePriceTestHook(hook) - Test-only seam for derivePrice
14
16
  * - derivePrice(BitShares, symA, symB, mode) - Derive price with fallback chain
15
17
  * - derivePriceViaBridges(BitShares, symA, symB, bridges, mode) - Multi-hop price via bridge assets
16
18
  * - derivePriceWithBridges(BitShares, symA, symB, bridges, mode) - Direct price, else bridge hops
17
- * - resolveLiquidityPoolByShareAsset(BitShares, shareAsset) - Resolve LP by share asset
18
19
  * - deriveLiquidityPoolTokenValue(BitShares, symA, symB) - Derive LP token value
19
- * - loadAmaCenterPrice(manager) - Load AMA center price
20
- * - loadAmaCenterSnapshot(manager) - Load AMA center snapshot
20
+ * - resolveLiquidityPoolByShareAsset(BitShares, shareAsset) - Resolve LP by share asset (internal)
21
21
  *
22
- * SECTION 2: FEE MANAGEMENT (1 function)
22
+ * SECTION 2: AMA CENTER SNAPSHOT (2 functions)
23
+ * - loadAmaCenterSnapshot(manager) - Load the full dynamic-grid snapshot
24
+ * - loadAmaCenterPrice(manager) - Load the AMA center price
25
+ *
26
+ * SECTION 3: FEE MANAGEMENT (1 function)
23
27
  * - initializeFeeCache(botsConfig, BitShares) - Initialize fee cache from blockchain
24
28
  *
25
- * SECTION 3: GRID STATE MANAGEMENT (3 functions)
29
+ * SECTION 4: GRID STATE MANAGEMENT (5 functions)
26
30
  * - persistGridSnapshot(manager, accountOrders) - Persist grid to storage
31
+ * - restoreGapEvacStreaks(manager) - Restore persisted gap-evacuation streaks
27
32
  * - retryPersistenceIfNeeded(manager) - Retry persistence if previous failed
28
33
  * - applyGridDivergenceCorrections(manager, ...) - Apply grid divergence corrections
29
- *
30
- * SECTION 4: UI & INTERACTIVE UTILITIES (7 functions)
34
+ * - applyPersistedPendingCrawls(...) - Apply persisted-but-uncommitted fill crawls
35
+ *
36
+ * SECTION 5: SPREAD-CORRECTION READINESS (7 functions)
37
+ * - resolveSpreadFreshnessMs(manager) - The single freshness window for spread trust
38
+ * - resolveSpreadCrossingFloor(manager) - Crossing floor spread correction must not trade through
39
+ * - refreshLiveMarketPrice(manager) - Refresh the cached live market price
40
+ * - maybeRefreshLiveMarketPrice(manager) - Refresh if stale, paced to one attempt per window
41
+ * - evaluateSpreadCorrectionReadiness(manager) - Evaluate whether spread correction may act
42
+ * - resolveSpreadMarketReference(manager) - Resolve the last real FILL price
43
+ * - resolveLastFillGuardReference(manager) - Resolve the reference the LAST-FILL-GUARD judges
44
+ *
45
+ * SECTION 6: LAST-FILL / MARKET-FILL PERSISTENCE (6 functions)
46
+ * - restoreLastMarketFill(manager) - Restore the persisted last-market-fill reference
47
+ * - normalizeLastFillPivot(row) - Normalize a persisted LAST-FILL-GUARD pivot row
48
+ * - normalizeLastMarketFill(row) - Normalize a persisted last-market-fill row
49
+ * - setLastFillPivot(manager, ...) - Write the LAST-FILL-GUARD pivot scalar family
50
+ * - resetLastFillPivot(manager) - Clear the pivot to cold state
51
+ * - restoreLastFillPivot(manager) - Restore the persisted pivot into the manager
52
+ *
53
+ * SECTION 7: UI & INTERACTIVE UTILITIES (6 functions)
31
54
  * - ensureProfilesDirectory(profilesDir) - Ensure profiles directory exists
32
55
  * - sleep(ms) - Pause execution for specified duration
33
56
  * - readInput(prompt, options) - Read user input from stdin
34
57
  * - readPassword(prompt) - Read password with masked echo
35
58
  * - withRetry(fn, options) - Execute async function with exponential backoff
36
- * - withTimeout(promise, timeoutMs, options) - defined in ./timeout
37
59
  * - withBlockchainRetry(fn, label, options) - Blockchain op with timeout + retry + node failover
60
+ * (withTimeout lives in ./timeout)
38
61
  *
39
- * SECTION 6: GENERAL UTILITIES (5 functions)
62
+ * SECTION 8: GENERAL UTILITIES (7 functions)
40
63
  * - resolveAccountRef(manager, account) - Resolve best account reference
41
64
  * - deepFreeze(obj) - Recursively freeze object for immutability
42
65
  * - cloneMap(map) - Create shallow clone of Map
43
66
  * - ensureDir(dirPath) - Ensure directory exists, creating recursively
67
+ * - nowIso() - Current time as an ISO string
68
+ * - fireStructuralResync(manager, ...) - Fire-and-forget structural grid resync
44
69
  * - parseJsonWithComments(raw) - Parse JSON with comment stripping
45
70
  *
71
+ * STRUCTURAL VIEW TYPES:
72
+ * AssetMeta, PoolReserve, PoolEntry, BitSharesClient, AmaCenterSnapshot,
73
+ * FeeCacheEntryData, SpreadCorrectionRefusalReason, SpreadCorrectionReadiness,
74
+ * UnmatchedChainOrderLike, GridResizeResult, CowResult
75
+ *
46
76
  * ===============================================================================
47
77
  */
48
78
  import { createRequire } from 'node:module';
@@ -1246,6 +1276,102 @@ export function resolveSpreadMarketReference(manager) {
1246
1276
  * @param {Object} manager - OrderManager instance
1247
1277
  * @returns {{price: number|null, type: string|null}} Effective pivot (both null when cold)
1248
1278
  */
1279
+ /**
1280
+ * Re-anchor the boundary so the newest REAL fill sits outside its own window.
1281
+ *
1282
+ * A boundary crawl is ±1 slot per committed fill, so a window that ended up
1283
+ * behind the fill (a sweep filled several slots while the commit dropped the
1284
+ * owed crawls, or the crawl was capped) cannot catch up by crawling: every
1285
+ * tightening slot on that side is then at/through the last fill and the
1286
+ * last-fill guard refuses all of them, while the funds sit in the resting
1287
+ * (stranded) inventory — the 2026-10-25 deadlock (7 sells swept slots 147-153,
1288
+ * the boundary ended at 146 and stayed there; `last-fill-blocked` thereafter).
1289
+ *
1290
+ * The fill itself is the anchor, so place it outside its window:
1291
+ * SELL fill at slot f -> boundary >= f - gapSlots (sellStart = f + 1)
1292
+ * BUY fill at slot f -> boundary <= f - 1 (buy window ends below f)
1293
+ *
1294
+ * Only a genuine on-ladder fill price is accepted (same one-increment drift
1295
+ * bound as `resolveOnGridPivot`), and the candidate must pass the same
1296
+ * placed-order-aware validation the boundary commit gate uses, so a re-anchor
1297
+ * can never strand a live order inside the re-typed band.
1298
+ *
1299
+ * @param {Object} manager - OrderManager (pivot + genesis)
1300
+ * @param {number|null} boundaryIdx - Boundary the derivation would commit
1301
+ * @param {Array<Object>} slots - Grid slots (current generation)
1302
+ * @param {number} gapSlots - Gap band width
1303
+ * @returns {{boundaryIdx: number|null, reanchored: boolean, from?: number|null, to?: number, side?: string, fillSlot?: number, reason?: string}}
1304
+ */
1305
+ export function reanchorBoundaryFromLastFill(manager, boundaryIdx, slots, gapSlots) {
1306
+ // NB: Number(null) === 0 and Number('') === 0 — a boundary-less manager must
1307
+ // not be re-anchored onto slot 0 (same absent-value trap as
1308
+ // consumePendingFillCrawls).
1309
+ if (boundaryIdx === null || boundaryIdx === undefined || boundaryIdx === '') {
1310
+ return { boundaryIdx: boundaryIdx ?? null, reanchored: false, reason: 'no-boundary' };
1311
+ }
1312
+ const boundary = Number(boundaryIdx);
1313
+ if (!Number.isFinite(boundary))
1314
+ return { boundaryIdx: boundaryIdx ?? null, reanchored: false, reason: 'no-boundary' };
1315
+ const ref = resolveLastFillGuardReference(manager);
1316
+ const price = Number(ref?.price);
1317
+ if (!Number.isFinite(price) || price <= 0)
1318
+ return { boundaryIdx: boundary, reanchored: false, reason: 'cold-pivot' };
1319
+ const side = ref.type === ORDER_TYPES.SELL ? ORDER_TYPES.SELL : ref.type === ORDER_TYPES.BUY ? ORDER_TYPES.BUY : null;
1320
+ if (!side)
1321
+ return { boundaryIdx: boundary, reanchored: false, reason: 'no-fill-side' };
1322
+ const genesis = manager?._genesis;
1323
+ const levels = genesis?.priceLevels;
1324
+ if (!genesis || !Array.isArray(levels) || levels.length === 0) {
1325
+ return { boundaryIdx: boundary, reanchored: false, reason: 'no-genesis' };
1326
+ }
1327
+ let idx;
1328
+ try {
1329
+ idx = Number(MathUtils.slotIndexForPrice(price, genesis));
1330
+ }
1331
+ catch {
1332
+ return { boundaryIdx: boundary, reanchored: false, reason: 'unresolvable-price' };
1333
+ }
1334
+ if (!Number.isFinite(idx) || idx < 0)
1335
+ return { boundaryIdx: boundary, reanchored: false, reason: 'unresolvable-price' };
1336
+ // Only a genuine ladder level: an off-ladder (orphan/adopted) fill price
1337
+ // must not be snapped into geometry. One increment is the caller's drift
1338
+ // bound everywhere else (resolveOnGridPivot), so reuse it here.
1339
+ const levelPrice = Number(MathUtils.priceForSlot(idx, genesis));
1340
+ const incrementPct = Math.abs(Number(manager?.config?.incrementPercent));
1341
+ const maxDrift = Number.isFinite(incrementPct) && incrementPct > 0 ? incrementPct / 100 : 0.005;
1342
+ if (!Number.isFinite(levelPrice) || levelPrice <= 0 || Math.abs(levelPrice - price) / price > maxDrift) {
1343
+ return { boundaryIdx: boundary, reanchored: false, reason: 'off-ladder-fill' };
1344
+ }
1345
+ const gap = Number.isFinite(Number(gapSlots)) && Number(gapSlots) >= 0 ? Math.floor(Number(gapSlots)) : 0;
1346
+ const slotCount = Array.isArray(slots) ? slots.length : 0;
1347
+ if (slotCount === 0)
1348
+ return { boundaryIdx: boundary, reanchored: false, reason: 'no-slots' };
1349
+ const ceiling = (slotCount - gap - 1) >= 0 ? (slotCount - gap - 1) : (slotCount - 1);
1350
+ const required = side === ORDER_TYPES.SELL ? idx - gap : idx - 1;
1351
+ if (side === ORDER_TYPES.SELL ? boundary >= required : boundary <= required) {
1352
+ return { boundaryIdx: boundary, reanchored: false, reason: 'already-outside' };
1353
+ }
1354
+ const candidate = Math.max(0, Math.min(ceiling, required));
1355
+ if (candidate === boundary)
1356
+ return { boundaryIdx: boundary, reanchored: false, reason: 'no-op' };
1357
+ let check = { ok: true };
1358
+ try {
1359
+ check = MathUtils.validatePersistedBoundary(candidate, slots ?? [], gap);
1360
+ }
1361
+ catch (err) {
1362
+ check = { ok: false, reason: getErrorMessage(err) };
1363
+ }
1364
+ if (!check || check.ok !== true) {
1365
+ return { boundaryIdx: boundary, reanchored: false, reason: `unsafe: ${check?.reason ?? 'unknown'}` };
1366
+ }
1367
+ try {
1368
+ manager.logger?.log?.(`[BOUNDARY] Re-anchored from the last fill: ${side} filled at slot ${idx} ` +
1369
+ `(${price.toFixed(6)}); boundary ${boundary} -> ${candidate} so the fill sits outside ` +
1370
+ `its own window (crawl alone cannot recover a window behind the fill)`, 'warn');
1371
+ }
1372
+ catch { /* logging is best-effort */ }
1373
+ return { boundaryIdx: candidate, reanchored: true, from: boundary, to: candidate, side, fillSlot: idx };
1374
+ }
1249
1375
  export function resolveLastFillGuardReference(manager) {
1250
1376
  const livePrice = Number(manager?._lastFilledPrice);
1251
1377
  const liveType = manager?._lastFilledType;
@@ -1259,6 +1385,45 @@ export function resolveLastFillGuardReference(manager) {
1259
1385
  }
1260
1386
  return { price: null, type: null };
1261
1387
  }
1388
+ /**
1389
+ * LAST-FILL-GUARD — DIRECTION ONLY, relative to the last fill price.
1390
+ *
1391
+ * BUY blocked if price >= pivot (never place a higher BUY)
1392
+ * SELL blocked if price <= pivot (never place a lower SELL)
1393
+ *
1394
+ * Lives here (not in the COW runtime) so the spread-correction PLANNER and the
1395
+ * broadcast guard judge candidates with literally the same predicate: a batch
1396
+ * must never be built from a create the guard will drop, and a dropped batch
1397
+ * must never be reported as an unexplained "prepared but not executed".
1398
+ *
1399
+ * A placement on the permitted side is always profitable against the last trade
1400
+ * we actually did: a BUY below the last sell, a SELL above the last buy. Equal
1401
+ * price counts as blocked — that is a re-place at the just-filled level, the
1402
+ * immediate re-fill loop this guard exists to prevent. Cold (no numeric pivot,
1403
+ * or no fill side recorded — e.g. a book-seeded pivot) => disabled. The grid
1404
+ * increment takes no part (kept in the signature for call-site stability).
1405
+ *
1406
+ * @param {number} price - Target order price
1407
+ * @param {number} _size - Order size (unused, kept for compat)
1408
+ * @param {string} type - ORDER_TYPES.BUY/SELL
1409
+ * @param {number|null} lastPrice - Most recent fill price
1410
+ * @param {string|null} lastType - Most recent fill side; null keeps the guard cold
1411
+ * @param {number|any} _incrementPercent - Unused (kept for signature compat)
1412
+ * @returns {{blocked: boolean, pivot: number|null, threshold?: number|null}}
1413
+ */
1414
+ export function isLastFillGuardBlocked(price, _size, type, lastPrice, lastType, _incrementPercent) {
1415
+ const numPrice = Number(price);
1416
+ if (!Number.isFinite(numPrice))
1417
+ return { blocked: false, pivot: null };
1418
+ if (lastPrice == null || !Number.isFinite(Number(lastPrice)) || lastType == null)
1419
+ return { blocked: false, pivot: null };
1420
+ const pivot = Number(lastPrice);
1421
+ if (type === ORDER_TYPES.BUY && numPrice >= pivot)
1422
+ return { blocked: true, pivot, threshold: pivot };
1423
+ if (type === ORDER_TYPES.SELL && numPrice <= pivot)
1424
+ return { blocked: true, pivot, threshold: pivot };
1425
+ return { blocked: false, pivot: null, threshold: null };
1426
+ }
1262
1427
  /**
1263
1428
  * Restore the persisted bot-scoped last-market-fill reference into the
1264
1429
  * manager. Deliberately independent of the boundary and the genesis: this is
@@ -12,14 +12,17 @@
12
12
  * SECTION 2: VALIDATION
13
13
  * - validateOrder()
14
14
  * - validateGridForPersistence()
15
- * - calculateRequiredFunds()
15
+ * - calculateRequiredFunds() (internal)
16
16
  * - validateWorkingGridFunds()
17
17
  * - checkFundDrift()
18
18
  *
19
19
  * SECTION 3: GRID RECONCILIATION (COW Pipeline)
20
20
  * - reconcileGrid()
21
21
  * - optimizeRebalanceActions()
22
- * - summarizeActions()
22
+ * - summarizeActions() (internal)
23
+ * - hasExecutableActions()
24
+ * - validateCreateTargetSlots()
25
+ * - stampGapEvacuationRotation()
23
26
  * - hasActionForOrder()
24
27
  * - removeActionsForOrder()
25
28
  * - projectTargetToWorkingGrid()
@@ -286,15 +289,17 @@ declare function buildAbortedResult(reason: string | null | undefined): {
286
289
  * @param {Object} params - Result parameters
287
290
  * @returns {Object} Success result object
288
291
  */
289
- declare function buildSuccessResult({ actions, stateUpdates, workingGrid, workingBoundary, planningDuration, refillSlotIds }: {
292
+ declare function buildSuccessResult({ actions, stateUpdates, workingGrid, workingBoundary, planningDuration, refillSlotIds, consumedCrawlIds }: {
290
293
  actions: CowAction[];
291
294
  stateUpdates: ManagedOrder[];
292
295
  workingGrid: WorkingGrid;
293
296
  workingBoundary: number | null;
294
297
  planningDuration: number;
295
298
  refillSlotIds?: unknown;
299
+ consumedCrawlIds?: unknown;
296
300
  }): {
297
301
  aborted: boolean;
302
+ consumedCrawlIds?: {} | null | undefined;
298
303
  refillSlotIds?: {} | null | undefined;
299
304
  actions: CowAction[];
300
305
  stateUpdates: ManagedOrder[];
@@ -12,14 +12,17 @@
12
12
  * SECTION 2: VALIDATION
13
13
  * - validateOrder()
14
14
  * - validateGridForPersistence()
15
- * - calculateRequiredFunds()
15
+ * - calculateRequiredFunds() (internal)
16
16
  * - validateWorkingGridFunds()
17
17
  * - checkFundDrift()
18
18
  *
19
19
  * SECTION 3: GRID RECONCILIATION (COW Pipeline)
20
20
  * - reconcileGrid()
21
21
  * - optimizeRebalanceActions()
22
- * - summarizeActions()
22
+ * - summarizeActions() (internal)
23
+ * - hasExecutableActions()
24
+ * - validateCreateTargetSlots()
25
+ * - stampGapEvacuationRotation()
23
26
  * - hasActionForOrder()
24
27
  * - removeActionsForOrder()
25
28
  * - projectTargetToWorkingGrid()
@@ -1134,7 +1137,7 @@ function buildAbortedResult(reason) {
1134
1137
  * @param {Object} params - Result parameters
1135
1138
  * @returns {Object} Success result object
1136
1139
  */
1137
- function buildSuccessResult({ actions, stateUpdates, workingGrid, workingBoundary, planningDuration, refillSlotIds }) {
1140
+ function buildSuccessResult({ actions, stateUpdates, workingGrid, workingBoundary, planningDuration, refillSlotIds, consumedCrawlIds }) {
1138
1141
  return {
1139
1142
  actions,
1140
1143
  stateUpdates,
@@ -1147,6 +1150,10 @@ function buildSuccessResult({ actions, stateUpdates, workingGrid, workingBoundar
1147
1150
  // planned boundary shift. May be absent/empty => executor treats as
1148
1151
  // empty (guarded default, never fail-open).
1149
1152
  ...(refillSlotIds !== undefined ? { refillSlotIds } : {}),
1153
+ // Crawl-ledger wire: the owed fill-crawl records this plan's derivation
1154
+ // actually folded. The commit clears only these; anything it could not
1155
+ // apply stays owed for the next derivation.
1156
+ ...(consumedCrawlIds !== undefined ? { consumedCrawlIds } : {}),
1150
1157
  aborted: false
1151
1158
  };
1152
1159
  }
@@ -38,7 +38,15 @@ export type OrderState = 'virtual' | 'active' | 'partial';
38
38
  * ('stale-snapshot' is degraded-ok, not a stall: the planner still acts, it
39
39
  * only withholds the LAST-FILL-GUARD bypass.)
40
40
  */
41
- export type SpreadCorrectionStall = 'no-free-funds' | 'unfunded' | 'no-candidates' | 'cold-book' | 'unmatched-orders' | 'readiness-gate' | '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'
42
+ /**
43
+ * Every tightening slot on the corrected side is at/through the last fill
44
+ * (SELL at/below it, BUY at/above it), so placement cannot repair the side:
45
+ * the bind is the grid WINDOW (a sell slot below the last sale means the
46
+ * boundary/crawl is behind the fill), not a missing candidate. Escalates on
47
+ * the short geometry window instead of the structural one.
48
+ */
49
+ | 'last-fill-blocked';
42
50
  /**
43
51
  * Dict with unknown values. The canonical replacement for
44
52
  * `Record<string, any>`; callers must narrow a value before using it.
@@ -223,6 +231,12 @@ export interface BotLike {
223
231
  _outOfSpreadSince: number;
224
232
  _outOfSpreadStaleWarned: boolean;
225
233
  _outOfSpreadTransientCount: number;
234
+ /**
235
+ * Timestamp when the spread first read within tolerance. Cleared on any
236
+ * out-of-tolerance cycle. A single good reading no longer clears the
237
+ * persistence clock — it must hold for SPREAD_STALE_IN_TOLERANCE_RESET_MS.
238
+ */
239
+ _outOfSpreadToleranceSince: number;
226
240
  _strandedHoldSince: Map<string, number>;
227
241
  _recoverySyncInFlight: number;
228
242
  _batchInFlight: number;
@@ -235,7 +249,14 @@ export interface BotLike {
235
249
  _marketAdapterWatchdogInFlight: boolean;
236
250
  _blockchainFetchInFlight: number;
237
251
  _blockchainFetchIntervalMin: number;
238
- _spreadFundsExhausted: boolean;
252
+ /**
253
+ * A spread-correction stall was mirrored this cycle. ANY cause arms the
254
+ * targeted chain refresh (a missed fill can hide the tightening slot, a stale
255
+ * hold can zero the funds), so the flag is cause-agnostic — the cause itself
256
+ * is carried in `_spreadCorrectionStall`. Formerly `_spreadFundsExhausted`,
257
+ * which mislabelled geometry stalls as fund stalls.
258
+ */
259
+ _spreadStallArmed: boolean;
239
260
  _spreadCorrectionStall: SpreadCorrectionStall | null;
240
261
  _skipEmptyReadConfirmDelay: boolean;
241
262
  _testPollIntervalMs?: number;
@@ -950,6 +971,18 @@ export interface CreditRuntimeLike {
950
971
  }
951
972
  export interface OrderManagerLike {
952
973
  _consecutiveBoundaryHolds?: number;
974
+ /**
975
+ * Set by the spread-correction planner when the corrected side's rail reserves
976
+ * more than the chain free balance (virtual > free). Cleared when a correction
977
+ * becomes fundable again. The out-of-spread watchdog escalates on its short
978
+ * fund window when this is fresh.
979
+ */
980
+ _spreadRailOversubscribed?: {
981
+ side: string;
982
+ virtual: number;
983
+ free: number;
984
+ at: number;
985
+ } | null;
953
986
  _boundaryShiftBudgetBase?: number;
954
987
  _lastBoundaryHoldInfo?: unknown;
955
988
  _lastHeldPlanSignature?: {
@@ -3,11 +3,11 @@
3
3
  *
4
4
  * BitShares stores asset symbols canonically UPPERCASE, so the assetA and
5
5
  * assetB symbols of a bot pair are always UPPERCASE on chain.
6
- * Nodes accept a lowercase lookup and answer it without error, so a lowercase
7
- * symbol never fails — it just travels on as lowercase into everything built
8
- * from it: the `symbol` field we attach to resolved assets, chart titles,
9
- * cache-file names, Kibana query terms, and strict in-process comparisons such
10
- * as the core-asset side check `assetA === 'CORE'`. That is a
6
+ * `lookup_asset_symbols` is case-sensitive: a lowercase symbol resolves to
7
+ * null (not an error), so a lowercase input silently drops the asset. Casing
8
+ * also leaks into everything built from a resolved symbol: the `symbol` field
9
+ * we attach to assets, chart titles, cache-file names, Kibana query terms, and
10
+ * strict in-process comparisons such as `assetA === 'CORE'`. That is a
11
11
  * silent-wrong-answer class of bug, not a loud
12
12
  * one, so the conversion is done ONCE here and applied at every boundary that
13
13
  * accepts a pair from a human (CLI prompts, `dexbot tv`/`dw` targets) or hands
@@ -3,11 +3,11 @@
3
3
  *
4
4
  * BitShares stores asset symbols canonically UPPERCASE, so the assetA and
5
5
  * assetB symbols of a bot pair are always UPPERCASE on chain.
6
- * Nodes accept a lowercase lookup and answer it without error, so a lowercase
7
- * symbol never fails — it just travels on as lowercase into everything built
8
- * from it: the `symbol` field we attach to resolved assets, chart titles,
9
- * cache-file names, Kibana query terms, and strict in-process comparisons such
10
- * as the core-asset side check `assetA === 'CORE'`. That is a
6
+ * `lookup_asset_symbols` is case-sensitive: a lowercase symbol resolves to
7
+ * null (not an error), so a lowercase input silently drops the asset. Casing
8
+ * also leaks into everything built from a resolved symbol: the `symbol` field
9
+ * we attach to assets, chart titles, cache-file names, Kibana query terms, and
10
+ * strict in-process comparisons such as `assetA === 'CORE'`. That is a
11
11
  * silent-wrong-answer class of bug, not a loud
12
12
  * one, so the conversion is done ONCE here and applied at every boundary that
13
13
  * accepts a pair from a human (CLI prompts, `dexbot tv`/`dw` targets) or hands
@@ -43,7 +43,8 @@ export declare function sleepMs(ms: number): Promise<void>;
43
43
  * queries) must throw immediately — retrying those only burns time.
44
44
  *
45
45
  * Single home for the predicate previously triplicated across
46
- * kibana_client.ts / kibana_candles.ts / kibana_feed_source.ts.
46
+ * market_adapter/core/kibana_client.ts / market_adapter/core/kibana_candles.ts
47
+ * / market_adapter/inputs/kibana_feed_source.ts.
47
48
  */
48
49
  export declare function isTransientNetworkError(err: unknown): boolean;
49
50
  //# sourceMappingURL=errors.d.ts.map
@@ -70,7 +70,8 @@ export function sleepMs(ms) {
70
70
  * queries) must throw immediately — retrying those only burns time.
71
71
  *
72
72
  * Single home for the predicate previously triplicated across
73
- * kibana_client.ts / kibana_candles.ts / kibana_feed_source.ts.
73
+ * market_adapter/core/kibana_client.ts / market_adapter/core/kibana_candles.ts
74
+ * / market_adapter/inputs/kibana_feed_source.ts.
74
75
  */
75
76
  export function isTransientNetworkError(err) {
76
77
  const msg = String(getErrorMessage(err) || '');