dexbot 1.6.12 → 1.6.14

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 (213) hide show
  1. package/CHANGELOG.md +65 -1
  2. package/README.md +2 -2
  3. package/analysis/README.md +9 -11
  4. package/analysis/ama_fitting/README.md +5 -3
  5. package/claw/README.md +1 -0
  6. package/claw/docs/AI_BOT_LIBRARY_API.md +3 -1
  7. package/claw/docs/DEXBOT2_TUNING_CHEAT_SHEET.md +4 -4
  8. package/claw/modules/claw_bridge.ts +0 -3
  9. package/claw/modules/claw_catalog.ts +8 -4
  10. package/claw/modules/claw_skill_md.ts +1 -0
  11. package/claw/modules/dexbot_profiles.ts +59 -15
  12. package/claw/modules/types.ts +2 -1
  13. package/claw/package.json +3 -3
  14. package/claw/runtimes/openclaw-plugin/openclaw.plugin.json +1 -1
  15. package/claw/runtimes/openclaw-plugin/package.json +1 -1
  16. package/claw/skills/margin-trading/SKILL.md +1 -1
  17. package/claw/skills/margin-trading/references/position-management.md +1 -1
  18. package/claw/tsconfig.json +2 -2
  19. package/dist/analysis/ama_fitting/analyze_lambda_vs_slow.js +1 -14
  20. package/dist/analysis/ama_fitting/fetch_lp_candles.js +51 -41
  21. package/dist/analysis/ama_fitting/generate_unified_comparison_chart.d.ts +1 -24
  22. package/dist/analysis/ama_fitting/generate_unified_comparison_chart.js +36 -18
  23. package/dist/analysis/ama_fitting/optimizer_high_resolution.js +18 -66
  24. package/dist/analysis/analyze_args.d.ts +12 -0
  25. package/dist/analysis/analyze_args.js +20 -0
  26. package/dist/analysis/bot_fitting/backtest_ama_sweep.d.ts +1 -16
  27. package/dist/analysis/bot_fitting/backtest_ama_sweep.js +20 -101
  28. package/dist/analysis/bot_fitting/backtest_bot_fitting.js +26 -92
  29. package/dist/analysis/bot_fitting/backtest_lookback_drawdown.js +19 -34
  30. package/dist/analysis/bot_fitting/shared_utils.d.ts +71 -3
  31. package/dist/analysis/bot_fitting/shared_utils.js +124 -8
  32. package/dist/analysis/chart_ui.d.ts +30 -1
  33. package/dist/analysis/chart_ui.js +37 -1
  34. package/dist/analysis/fills_cache.d.ts +3 -23
  35. package/dist/analysis/fills_cache.js +3 -84
  36. package/dist/analysis/fills_source.d.ts +31 -1
  37. package/dist/analysis/fills_source.js +69 -1
  38. package/dist/analysis/grid_correction_check.d.ts +1 -23
  39. package/dist/analysis/grid_correction_check.js +15 -58
  40. package/dist/analysis/math_utils.d.ts +85 -1
  41. package/dist/analysis/math_utils.js +116 -1
  42. package/dist/analysis/price_sources.d.ts +22 -1
  43. package/dist/analysis/price_sources.js +23 -0
  44. package/dist/analysis/resolve_source.js +31 -10
  45. package/dist/analysis/trade_profitability.d.ts +6 -0
  46. package/dist/analysis/trade_profitability.js +23 -97
  47. package/dist/analysis/tradingview/analyze_tradingview.d.ts +1 -17
  48. package/dist/analysis/tradingview/analyze_tradingview.js +1 -1
  49. package/dist/analysis/tradingview/tradingview_uplot_chart_generator.js +27 -40
  50. package/dist/analysis/trend_detection/backtest_ama_slope_huber.d.ts +1 -101
  51. package/dist/analysis/trend_detection/backtest_ama_slope_huber.js +22 -80
  52. package/dist/analysis/trend_detection/dynamic_weight_chart_generator.js +11 -37
  53. package/dist/analysis/trend_detection/volatility_chart_generator.js +9 -10
  54. package/dist/analysis/worker_pool.d.ts +38 -0
  55. package/dist/analysis/worker_pool.js +67 -0
  56. package/dist/dexbot.js +67 -48
  57. package/dist/market_adapter/ama_signal_runner.js +21 -54
  58. package/dist/market_adapter/candle_utils.d.ts +7 -1
  59. package/dist/market_adapter/candle_utils.js +11 -1
  60. package/dist/market_adapter/cli_args.d.ts +22 -0
  61. package/dist/market_adapter/cli_args.js +30 -0
  62. package/dist/market_adapter/core/config_normalizers.js +11 -6
  63. package/dist/market_adapter/core/kibana_candles.d.ts +3 -1
  64. package/dist/market_adapter/core/kibana_candles.js +3 -2
  65. package/dist/market_adapter/core/market_adapter_service.d.ts +85 -85
  66. package/dist/market_adapter/core/market_adapter_service.js +93 -158
  67. package/dist/market_adapter/core/signals/hurst_analyzer.d.ts +1 -6
  68. package/dist/market_adapter/core/signals/hurst_analyzer.js +1 -1
  69. package/dist/market_adapter/core/signals/permutation_entropy_analyzer.d.ts +1 -11
  70. package/dist/market_adapter/core/signals/permutation_entropy_analyzer.js +1 -1
  71. package/dist/market_adapter/inputs/fetch_book_data.js +0 -1
  72. package/dist/market_adapter/inputs/fetch_cex_synthetic_data.js +63 -107
  73. package/dist/market_adapter/inputs/fetch_lp_data.d.ts +8 -1
  74. package/dist/market_adapter/inputs/fetch_lp_data.js +25 -7
  75. package/dist/market_adapter/inputs/kibana_feed_source.js +4 -26
  76. package/dist/market_adapter/inputs/window_cache.d.ts +4 -72
  77. package/dist/market_adapter/inputs/window_cache.js +52 -177
  78. package/dist/market_adapter/interval_utils.d.ts +11 -1
  79. package/dist/market_adapter/interval_utils.js +16 -1
  80. package/dist/market_adapter/lp_chart_runner.d.ts +3 -0
  81. package/dist/market_adapter/lp_chart_runner.js +37 -19
  82. package/dist/market_adapter/market_adapter.js +27 -72
  83. package/dist/market_adapter/utils/data_discovery.d.ts +45 -1
  84. package/dist/market_adapter/utils/data_discovery.js +220 -27
  85. package/dist/market_adapter/utils/month_shards.d.ts +84 -0
  86. package/dist/market_adapter/utils/month_shards.js +237 -0
  87. package/dist/modules/account_bots.d.ts +8 -6
  88. package/dist/modules/account_bots.js +112 -131
  89. package/dist/modules/account_orders.d.ts +49 -4
  90. package/dist/modules/account_orders.js +114 -49
  91. package/dist/modules/bitshares-native/chain_client.d.ts +1 -1
  92. package/dist/modules/bitshares-native/chain_client.js +14 -13
  93. package/dist/modules/bitshares-native/crypto/ecc_core.d.ts +1 -2
  94. package/dist/modules/bitshares-native/crypto/ecc_core.js +1 -1
  95. package/dist/modules/bitshares-native/resolvers.js +22 -25
  96. package/dist/modules/bitshares-native/serial/chain_constants.d.ts +1 -2
  97. package/dist/modules/bitshares-native/serial/chain_constants.js +1 -2
  98. package/dist/modules/bitshares-native/serial/types.js +22 -50
  99. package/dist/modules/bitshares-native/signing_client.d.ts +1 -1
  100. package/dist/modules/bot_defaults.d.ts +18 -3
  101. package/dist/modules/bot_defaults.js +34 -8
  102. package/dist/modules/bot_settings.d.ts +5 -1
  103. package/dist/modules/bot_settings.js +55 -21
  104. package/dist/modules/broadcast_failure.d.ts +2 -1
  105. package/dist/modules/chain_orders.d.ts +1 -1
  106. package/dist/modules/chain_orders.js +51 -96
  107. package/dist/modules/cli_start_onboarding.d.ts +2 -1
  108. package/dist/modules/config.js +6 -1
  109. package/dist/modules/constants.d.ts +14 -6
  110. package/dist/modules/constants.js +32 -6
  111. package/dist/modules/cr_planner.d.ts +1 -1
  112. package/dist/modules/cr_planner.js +1 -5
  113. package/dist/modules/credit_pricing.d.ts +2 -1
  114. package/dist/modules/credit_pricing.js +36 -40
  115. package/dist/modules/credit_runtime.d.ts +7 -0
  116. package/dist/modules/credit_runtime.js +45 -73
  117. package/dist/modules/daemon_node_health.d.ts +4 -3
  118. package/dist/modules/dexbot_class.d.ts +33 -17
  119. package/dist/modules/dexbot_class.js +113 -61
  120. package/dist/modules/dexbot_cow_runtime.d.ts +62 -181
  121. package/dist/modules/dexbot_cow_runtime.js +380 -69
  122. package/dist/modules/dexbot_credential_client.d.ts +1 -23
  123. package/dist/modules/dexbot_credential_client.js +2 -3
  124. package/dist/modules/dexbot_fill_runtime.d.ts +2 -3
  125. package/dist/modules/dexbot_fill_runtime.js +17 -7
  126. package/dist/modules/dexbot_maintenance_runtime.d.ts +36 -81
  127. package/dist/modules/dexbot_maintenance_runtime.js +137 -133
  128. package/dist/modules/dexbot_startup_runtime.d.ts +0 -1
  129. package/dist/modules/dexbot_startup_runtime.js +25 -14
  130. package/dist/modules/dexbot_state_recovery.js +16 -0
  131. package/dist/modules/general_settings.d.ts +1 -1
  132. package/dist/modules/graceful_shutdown.js +17 -11
  133. package/dist/modules/key_store.d.ts +0 -5
  134. package/dist/modules/key_store.js +1 -2
  135. package/dist/modules/lazy_shim.d.ts +11 -0
  136. package/dist/modules/lazy_shim.js +16 -0
  137. package/dist/modules/node_connect_policy.d.ts +3 -2
  138. package/dist/modules/node_failure_ledger.d.ts +6 -5
  139. package/dist/modules/order/accounting.js +11 -11
  140. package/dist/modules/order/export.js +2 -2
  141. package/dist/modules/order/format.d.ts +26 -3
  142. package/dist/modules/order/format.js +33 -3
  143. package/dist/modules/order/genesis_policy.d.ts +4 -4
  144. package/dist/modules/order/genesis_policy.js +6 -3
  145. package/dist/modules/order/grid.d.ts +26 -12
  146. package/dist/modules/order/grid.js +468 -80
  147. package/dist/modules/order/grid_reconcile.d.ts +1 -1
  148. package/dist/modules/order/grid_reconcile.js +5 -5
  149. package/dist/modules/order/grid_reconcile_internal.js +48 -40
  150. package/dist/modules/order/index.d.ts +35 -8
  151. package/dist/modules/order/logger.d.ts +1 -8
  152. package/dist/modules/order/logger.js +2 -11
  153. package/dist/modules/order/manager.d.ts +18 -15
  154. package/dist/modules/order/manager.js +91 -74
  155. package/dist/modules/order/strategy.d.ts +2 -2
  156. package/dist/modules/order/strategy.js +51 -21
  157. package/dist/modules/order/sync_engine.js +4 -0
  158. package/dist/modules/order/utils/math.d.ts +3 -3
  159. package/dist/modules/order/utils/math.js +38 -27
  160. package/dist/modules/order/utils/order.d.ts +58 -58
  161. package/dist/modules/order/utils/order.js +158 -137
  162. package/dist/modules/order/utils/system.d.ts +202 -35
  163. package/dist/modules/order/utils/system.js +409 -31
  164. package/dist/modules/order/utils/validate.js +28 -6
  165. package/dist/modules/order/utils/withPoolRef.d.ts +2 -1
  166. package/dist/modules/paths.js +32 -34
  167. package/dist/modules/runtime_settings.d.ts +3 -5
  168. package/dist/modules/runtime_settings.js +3 -3
  169. package/dist/modules/settings_merge.d.ts +2 -2
  170. package/dist/modules/socket_json_client.d.ts +2 -1
  171. package/dist/modules/types.d.ts +89 -30
  172. package/dist/modules/utils/errors.js +1 -3
  173. package/dist/modules/version_notice.d.ts +11 -10
  174. package/dist/pm2.d.ts +0 -1
  175. package/dist/pm2.js +56 -35
  176. package/dist/scripts/analyze-git.js +2 -15
  177. package/dist/scripts/analyze-orders.d.ts +1 -1
  178. package/dist/scripts/analyze-orders.js +4 -4
  179. package/dist/scripts/chart_command.js +2 -2
  180. package/dist/scripts/check_any.d.ts +4 -0
  181. package/dist/scripts/check_any.js +53 -21
  182. package/dist/scripts/diagnose-pool-history.js +1 -6
  183. package/dist/scripts/divergence-calc.js +6 -6
  184. package/dist/scripts/run-tests.js +0 -1
  185. package/dist/scripts/sync-version.js +0 -10
  186. package/dist/scripts/validate_bots.d.ts +1 -1
  187. package/dist/scripts/validate_bots.js +3 -3
  188. package/dist/unlock.js +7 -2
  189. package/docs/BITSHARES_ONBOARDING.md +8 -12
  190. package/docs/COPY_ON_WRITE_MASTER_PLAN.md +2 -3
  191. package/docs/COW_INVARIANTS.md +6 -6
  192. package/docs/DEXBOT_COMPARISON.md +7 -7
  193. package/docs/EVOLUTION.md +10 -8
  194. package/docs/FUND_MOVEMENT_AND_ACCOUNTING.md +8 -6
  195. package/docs/GRID_PRICE_INVARIANT.md +3 -3
  196. package/docs/GRID_RECALCULATION.md +4 -1
  197. package/docs/GRID_RECONCILE.md +4 -4
  198. package/docs/LIFECYCLE.md +11 -11
  199. package/docs/LOGGING.md +14 -0
  200. package/docs/MPA_CREDIT_USAGE.md +1 -1
  201. package/docs/ORDER_ENGINE_POST_1.0_RETROSPECTIVE.md +12 -4
  202. package/docs/README.md +3 -3
  203. package/docs/WORKFLOW.md +1 -0
  204. package/docs/architecture.md +25 -16
  205. package/docs/developer_guide.md +7 -2
  206. package/market_adapter/README.md +6 -4
  207. package/package.json +6 -9
  208. package/scripts/README.md +43 -38
  209. package/tests/README.md +26 -11
  210. package/dist/scripts/diagnose-kibana-candles.d.ts +0 -3
  211. package/dist/scripts/diagnose-kibana-candles.js +0 -82
  212. package/scripts/git-viewer.sh +0 -489
  213. package/scripts/postinstall.js +0 -16
package/CHANGELOG.md CHANGED
@@ -2,6 +2,68 @@
2
2
 
3
3
  All notable changes to this project will be documented in this file.
4
4
 
5
+ ## [1.6.14] - 2026-10-12 - Spread-Correction Last-Fill Guard & Live Market Floor, Committed-Size Drift Resize, COW Pre-Broadcast Guards & P2 Counters, Fail-Closed Unknown Geometry, Order-Key Rename
6
+
7
+ ### 2026-10-12
8
+
9
+ - **Fix(order-engine)**: never let spread correction trade through the last real fill — after a stop/start regenerated the grid, the genesis-bound LAST-FILL-GUARD pivot was wiped with the generation, and spread correction bypassed the guard, so it could place a SELL at/below (or a BUY at/above) the last real trade price. A bot-scoped last-market-fill reference (price/type/fillsAt) now survives `clearGrid()`/regeneration and is restored at startup under a 24h TTL; spread-correction candidates are filtered against it (planner + boundary promotion), failing open when no real fill is known; the LAST-FILL-GUARD bypass is denied whenever a real market reference exists, keeping the heuristic bypass only while the local snapshot is fresh; a cold book (no live order either side) skips correction and reports a structural stall so the targeted chain sync arms; and a timestamped pre-reject snapshot copy is kept before `clearGrid()`. Reference resolution is consolidated into one predicate shared by the planner and the COW bypass gate. Covered by the SMR-1..6 suite.
10
+
11
+ - **Refactor(order-engine)**: unify spread-correction trust decisions behind one readiness gate and a live market floor — the planner, the crossing filter and the COW bypass could otherwise reason from different state. `evaluateSpreadCorrectionReadiness()` is now the single pure verdict: a cold book is a hard refuse, while a stale snapshot or known-unmatched orders degrade to plan-but-withhold-the-LAST-FILL-GUARD-bypass; it returns the crossing floor and collision-filter input alongside the verdict. The coarse "is this anchor stale?" distance cap is replaced by a live order-book/ticker read on a bounded cadence, and the NEWER of the live read and the fill anchor is used as the floor so staleness is prevented at the source; candidates are filtered against known-unmatched chain price levels keyed off the data rather than the priority-ranked reason. A gate failure now refuses the cycle (correct-by-refusal) instead of planning with no floor and no collision filter. `config.timing.SPREAD_CORRECTION_SYNC_FRESH_MS` is the single trust window for both snapshot staleness and live-price refresh pacing. Covered by the SMR-1..10 suite.
12
+
13
+ - **Fix(grid)**: resize the full side when a deposit slips past the fund ratio — the 3% available-funds trigger measures `chainFree - virtual`, but the fill/rotation sizing pipeline re-derives VIRTUAL slot sizes from the live budget, so an external deposit is folded into the virtual reservation on the first rotation after it lands, the ratio stays pinned at the unallocated remainder, and the on-chain orders keep their pre-deposit sizes without ever tripping the trigger. A new `checkCommittedSizeDrift` computes each side's geometric ideal from the current budget, replays the resize's free-balance growth cap against the on-chain orders, and flags the side when the committed delta reaches `GRID_REGENERATION_PERCENTAGE` of the committed size (denominator is the committed total, not the whole allocation, so a genuine full-side undersize is not understated). Wire it into `monitorDivergence` so the maintenance runtime routes it to the COW resize path. Impact: an external deposit/withdrawal that shifts a side's budget by >=3% now resizes all of its on-chain orders on the next pipeline-empty maintenance tick instead of only the fill-generated replacements.
14
+
15
+ - **Fix(grid)**: harden committed-size drift and unify the fund trigger — each slot's counted drift is now gated on the same blockchain-integer comparison the resize uses to emit an on-chain UPDATE, so a flagged side can never drive the COW resize to a no-op and re-trigger every tick (the free-balance replay still evolves identically). The drift core is folded into `checkAndUpdateGridIfNeeded`, which becomes the complete fund trigger (available-funds ratio + over-allocation + committed drift) so the legacy ratio legs cannot be consumed or regress in isolation; `monitorDivergence` refreshes funds once and calls only the unified entry, with `_getSizingContext` split into a pure sync core shared by both legs. Partial-fill behaviour is pinned: a >=3%-of-committed remainder on an on-chain slot triggers the self-correcting full-side resize, a sub-threshold remainder stays silent.
16
+
17
+ - **Feat(order-engine)**: harden COW pre-broadcast guards and add P2 observability counters — `runPreBroadcastGuards` re-reads every UPDATE action's tracked orderId before op-building; a target already gone on chain refuses the whole batch (`UPDATE_TARGET_MISSING`), pops the working grid and requests a structural resync instead of letting `limit_order_update` abort a chunk mid-broadcast and leave a partially-applied grid (fails open on a non-Map/errored read; each candidate is re-verified once via `readSingleOrder`). A non-spread-correction CREATE/UPDATE destination inside the plan's gap band is counted and warned (never blocked — spread correction legitimately places into the band). New counter-only P2 metrics (never gating placement): `refusedCommitCount`, `orphanFillCreditedCount`, `restampBuyAboveAnchorCount`, `boundaryDriftExceedsWindowCount` (surfaced via a manager-metrics overlay in `getMetrics()`) and `gapBandPlacementShadowCount`. Covered by `tests/test_p2_observability_counters.ts` and COW-COMMIT-013..016.
18
+
19
+ - **Fix(order-engine)**: fail closed on unknown boundary/gap across gap-evacuation and COW shadow paths — an unknown boundary or gap width (`null`/`undefined`/`''`) was read as the valid value 0 via `Number(...)`, casting real geometry around slot 0 across the plan/evacuation/guard paths. Unknown geometry is now treated as unknown in `detectGapEvacuationCandidates`, `geometryTypeForSlotIndex`, `isEvacuationStampStillValid`, `stampGapEvacuationRotation`, `optimizeRebalanceActions` (and its `applyGridDivergenceCorrections` call site), `planVacatedRailRefill`, `buildCowResultFromPlan` and the `runPreBroadcastGuards` boundary fallback; a genuine boundary 0 is preserved. Covered by EVAC-005/007/016/021 (the EVAC-007 fixture is now non-vacuous).
20
+
21
+ - **Fix(order)**: close the missed 1.6.13 regressions in absent geometry and the rebuild guard — an absent geometry value was coerced by `Number()` to the valid-looking 0; the new `Format.toKnownNumber` (null/undefined/'' => NaN; a genuine 0 stays 0) backs the shadow gap, plan boundary and evac-stamp reads, `validate.reconcileGrid` no longer B-stamps a gap-0 evac on an absent plan gap, `order.consumePendingFillCrawls` falls back to the config-derived gap, and the geometry helpers keep absence detectable (SELL rail fails open). The generic LAST-FILL-GUARD no longer silently un-arms on grid regeneration while the last real fill price is still known: `resolveLastFillGuardReference` falls back to the bot-scoped last-market-fill row (read-time only, so the genesis-bound pivot/persist contract is unchanged) and is used by `runLastFillGuardCheck`, the batch freeze, `runFinalPivotGate` and the batch summary. Covered by EVAC-022 and LFP-9.
22
+
23
+ - **Fix(math)**: keep `validateBoundaryCommit` fail-closed for garbage boundaries — only `null`/`undefined`/`''` mean "no proposal" (ok); every other non-numeric value (`'abc'`, `NaN`, `Infinity`) is rejected as `non_integer_boundary` again. The 1.6.13 absent-aware rewrite had silently widened this into "garbage = no proposal", the wrong failure mode for `validatePersistedBoundary` (the disk-trust gate, where a corrupt persisted value must surface as a rejection/rebuild, never pass as absence). Contract pinned in `tests/test_boundary_restore_validation.ts`; no current caller passes a non-numeric value.
24
+
25
+ - **Refactor(config)**: rename `activeOrders` → `coreOrders` and `reserveOrders` → `edgeOrders` — aligns the persisted bot-config keys with the editor labels (CoreOrder / EdgeOrder) and finishes the edge vocabulary, which previously mixed reserve/edge/active for the same concepts, across modules, claw, tests, scripts, analysis and docs (export keys become `core_orders`/`edge_orders`; internal identifiers renamed accordingly). Pre-rename user settings are supported at a single read boundary (`migrateLegacyOrderKeys`): `loadSettingsFile` rewrites `bots.json` to canonical keys on first read, and the maintenance fingerprint/live-apply paths canonicalize raw entries. `tests/test_reserve_orders.ts` → `tests/test_edge_orders.ts` with legacy-alias, validation and on-disk-migration coverage. Behavior-preserving.
26
+
27
+ - **Refactor(modules)**: drop dead exports and trim runtime default objects — remove the unused `GRAPHENE_100_PERCENT` constant and stop exporting internal-only symbols (`equalsBytes`, `sendCredentialDaemonRequest`, `ReplayMessageFn`, `DaemonKeyStore`, `reconcileAfterUncertainBroadcastImpl`, `pollChainForConfirmation`); cut the `dexbot_cow_runtime` and `dexbot_maintenance_runtime` default export objects down to the members actually consumed by `dexbot_class` (plus `_internalDeferredHold` for tests). No runtime logic changed.
28
+
29
+ - **Perf(unlock)**: lazy-load the bot editor and chain client — `unlock`/`start` eagerly imported `account_bots` and `bitshares_client`, pulling the native chain-client module graph (~80ms) into every invocation even when the interactive onboarding path is never taken; both are now loaded only when that path is reached.
30
+
31
+ - **Fix(config)**: tolerate `process.umask` failure in worker threads — worker threads cannot set the process-wide umask (`process.umask()` throws `ERR_WORKER_UNSUPPORTED_OPERATION`), which crashed config load; the call is now skipped gracefully (matching `Runtime.umask()`'s guard) so config stays loadable in a worker.
32
+
33
+ - **Chore(tests)**: cut suite wall time and make the ESM-mock runner deterministic — ESM-mock stages now run in `worker_threads` Workers (own module registry, shared parent PID; stub files keyed by PID+threadId so concurrent stages cannot clobber one another; default concurrency `min(availableParallelism, 8)`; `runEsmMockStagesShared`/`runEsmMockStagesGrouped` consolidate same-mock stages, e.g. `test_credit_runtime`'s 55 stages in ~264ms vs ~4057ms). Sleep-dominated tests poll the real condition instead, redundant heavy crypto is dropped (`native_ecc_equivalence` 32→8 iterations, browser scrypt cross-checks at N=1024), and the market-adapter JSON cache-invalidation test forces a strictly past stamp via `utimesSync` instead of relying on mtime granularity. Full suite remains 312/312 (14 skipped live).
34
+
35
+ - **Docs**: sync linked guides with the code after a staleness audit — `COPY_ON_WRITE_MASTER_PLAN` (drop the removed `Accountant.validateTargetGrid` dry-run guardrail and describe the real planning-time budget chokepoint), `LIFECYCLE`/`FUND_MOVEMENT`/`COW_INVARIANTS` (refreshed line anchors), `architecture` (replace removed `calculateCurrentSpreadGap`/`calculateTargetSpread` with the live `calculateCurrentSpread` + `shouldFlagOutOfSpread` path), `GRID_PRICE_INVARIANT` (code-review baseline to v1.6.13), and `docs/README` (index the memu-memory/trend-detection skill packs; align the `GRID_RECALCULATION` bullet with the available-funds-resize naming). Docs-only.
36
+
37
+ ## [1.6.13] - 2026-10-10 - Spread-Stall Cause Reporting & Chain Sync, Resync-Cascade Guards, Month-Shard Candle Cache, Dedup & Dead-Code Purge, npm 12 Install & PM2 Fixes
38
+
39
+ ### 2026-10-10
40
+
41
+ - **Fix(order-engine)**: report spread-correction stall causes and sync with the chain on every stall — `checkSpreadCondition` reported a single `fundsExhausted` boolean on any zero-placement, so a purely structural "no tightening slot exists" grid re-read account totals + open orders every cooldown (a refresh that cannot change it) and the log always blamed free funds. It now returns a `SpreadCorrectionStall` cause (`no-free-funds` | `unfunded` | `no-candidates` | `batch-not-executed` | `apply-error`) and `prepareSpreadCorrectionOrders` reports `plannedCount`, so "no candidates" is distinguishable from "candidates existed but unfunded"; the TOCTOU re-plan zero-placement branch now carries a cause like every sibling (placed-nothing ⇒ carry-a-cause holds on all paths) and `tightensSpread` rejects null/non-finite prices at the single chokepoint so a price-less rail orphan cannot consume a slice quota seat. Follow-up: the arm is no longer suppressed for `no-candidates` — that cause is derived from LOCAL grid state, and a missed fill leaves a window-edge slot ACTIVE while its chain order is gone, making the phantom the `bestLiveOnRail` and every real tightening slot look non-tightening. `mirrorSpreadStall` now arms the targeted balances + open-orders refresh for every cause, so a stale local snapshot recovers in ~1 tick instead of up to `SPREAD_STALE_ESCALATE_MS` (30 min); the staleness watchdog remains the backstop and a genuinely structural stall pays an account + open-orders read per cooldown while it persists. Covered by `tests/test_spread_correction_market_nearest.ts` (all five causes, the null-price orphan eviction, and the regression where an unfunded plan on one side was masked by an empty opposite side) and `tests/test_targeted_drift_reconcile.ts` (exact cause, flag + cause clear/retain together).
42
+
43
+ - **Fix(order-engine)**: break resync cascades on uncertain broadcast and suspended persistence — a transient credential-daemon ping timeout suspended grid persistence for ~6h because the watchdog never set `_credentialRecoveryNeeded`, so `_runCredentialRecoveryAfterDaemonRestored()` early-returned and `resumeGridPersistence()` was never called; every subsequent COW batch then failed its persist retry and forced a structural grid resync (14 in one window), each clearing the LAST-FILL-GUARD pivot and rebuilding the grid. `resyncIfUnreconciled` now subtracts master-tracked order ids via `collectKnownOnChainOrderIds`, so only chain orders genuinely unknown to master request a resync (UNC-020/021); the COW persist guard treats a `suspended` retry as a deferral (marks the committed grid dirty for the end-of-tick flush, never escalates to a resync, COW-PERSIST-003); and the watchdog sets `_credentialRecoveryNeeded` on a confirmed outage, tolerating one transient timeout via `CREDENTIAL_DAEMON_WATCHDOG_FAILURE_THRESHOLD` while `ENOENT`/`ECONNREFUSED` stay immediate, and uses `TIMING.DAEMON_PING_TIMEOUT_MS` instead of a hardcoded 2s (UNC-009/009b). Impact: fewer structural resyncs and LAST-FILL pivot clears after credential outages and uncertain broadcasts.
44
+
45
+ - **Fix(lifecycle)**: route pm2 npm scripts through the launcher and harden the pm2 bootstrap — `npm run pm2:start`/`pm2:stop` ran raw `pm2 start/stop` against the generated ecosystem, bypassing the keystore unlock and credential daemon (silent no-key runtime); they now delegate to the launcher (`pm2:start` → `pm2:unlock`, `pm2:stop` → `node dist/pm2.js stop all`), and `npm run pm2:stop` also stops dexbot-cred to match `dexbot pm2 stop all`. `pm2.ts` replaces the contradictory `merge_logs: false` + `combine_logs: true` with the canonical `merge_logs: true`, `installPM2` accepts `n`/`no`, resolves npm next to `process.execPath` (version-manager installs land in the right prefix) and verifies `pm2` reachability on all platforms, and dead code (`require.resolve('pm2')` branch, unused `logReuse`, stale comment) is removed.
46
+
47
+ - **Fix(install)**: drop the postinstall hook so npm 12 global installs are clean — npm 12+ blocks dependency lifecycle scripts by default (npm/rfcs#868), so the informational banner never ran and every `npm i -g dexbot` emitted an unsilenceable install-scripts warning (`allowScripts` cannot be self-declared by a package). The hook and `scripts/postinstall.js` are removed; the CLI already prints the same getting-started guidance on first run when no profiles/keyring exist, and `prepare` is untouched. The only loss is two informational banners under npm ≤ 11.
48
+
49
+ - **Refactor(order-engine)**: centralize COW plan-origin labels in `COW_ORIGINS` — the LAST-FILL-GUARD bypass keyed off `origin` strings (`'spread-correction'`, `'gap-evacuation'`) written and read as bare literals in 8 places, so a rename or typo on either side would silently disable a bypass with no compile error. A frozen `COW_ORIGINS` in `modules/constants.ts` is now routed through every producer (`modules/order/grid.ts` planner exits, `stampGapEvacuationRotation`) and consumer (`modules/dexbot_cow_runtime.ts` origin striping, broadcast-loop and final-pivot-gate bypasses). String values are byte-identical; no behavioral change.
50
+
51
+ - **Refactor(cache)**: centralize candle caching on month shards — LP/book/feed fetchers, month-shard naming, query-coverage bookkeeping and LP-series assembly were spread across `window_cache`, `fills_cache`, `data_discovery` and a second LP fetcher. New `market_adapter/utils/month_shards.ts` is the single source for shard key/bounds/range/path/stem naming and coverage-span primitives, imported by both the candle cache and the fills cache so they can no longer disagree on a month boundary; `window_cache` scoped loads enumerate only overlapping calendar-month shards (no directory listing, O(1) per-shard flush lookup, windows aligned to UTC month starts); `data_discovery` gains `loadLatestLpSeries`/`loadLpSeriesFromPath`/`loadLpSeriesFromBasePath` for shard-family assembly; `analysis/ama_fitting/fetch_lp_candles.ts` is now a thin CLI over `fetchCandlesSequentially`; and whole-history exports are derived from assembled shards so a later narrow re-run cannot overwrite them with a subset. `dexbot tv`/`dw`, the optimizer and the analysis loaders share one incremental cache, and `--data <shard>` now yields the full series.
52
+
53
+ - **Refactor(market-adapter)**: deduplicate interval tables, cycle fields and arg parsing — `fetch_cex_synthetic_data.ts` replaces eight near-identical per-exchange interval maps with shape tables plus one `intervalFormatter` (interval output verified identical for every exchange) and fixes the broken `../market_adapter/market_adapter` require so the seed-generator CLI can start; `market_adapter_service.ts` shares the candle-cycle state/result fields via `buildCandleCycleFields()`, the dynamic-weight base inputs and the AMA-slope/weights-meta/dynamicWeights report fragments, and extracts `fetchNativeHistory()` for the duplicated native-fetch try/catch; and a new `cli_args.ts` (`walkCliArgs`) is shared by `market_adapter.ts` and `ama_signal_runner.ts` so the source/window flags, the `--gridResetFactor` guard, `--help` and unknown-flag handling cannot drift between the two entry points. Behavior-preserving.
54
+
55
+ - **Refactor(dedup)**: single-source duplicated helpers and drop dead exports/code — `order/utils/order` gets one `readFillProcessingNumber()` behind the five `resolveCorrection*` readers; `account_orders` replaces 20 inlined read-modify-write preambles with `_reload()`/`_ensureLoaded()`; credit-debt/collateral totals, chain account resolvers, `order/utils/system.sleep()`, `order/format.positiveOrNull()`, shutdown handlers, seam-ms resolution, chain-client caller factories and 56 hand-written lazy require wrappers (via `modules/lazy_shim.ts`) are each collapsed to one home; `analysis/` and `market_adapter/` merge duplicated Kibana sort keys, volatility normalizers, `higherVolumeWins`, `parseChainTimeToMs`, `geometricRange`/`median` and `loadAmaStrategies`, parameterizing the two that legitimately diverged (rounding/quantum, validation/naming) while deliberately NOT merging confirmed-diverged copies (percentile round-vs-floor, `resolveAma`, the classic classifyFills/exportJson pair); a parallel analysis pass extracts `classifyFill`/`matchesAssetRef` into `fills_source`, an option-driven `percentile()`/`fmtNum()` and `loadCandleSeries()` into `math_utils`, a new `analysis/worker_pool.ts` (`runModuleWorker`/`splitIntoShards`, which rejects instead of hanging on a clean worker exit with no result) shared by the optimizer and AMA sweep, shared fee/slope constants plus `consumeBacktestArg()`/`slopeResetThresholdPct()` into bot-fitting `shared_utils`, and `formatTimeLabelFn()`/`refreshChartsPreservingZoomFn()` into `chart_ui` — the last switches TradingView month labels from locale-dependent `toLocaleString()` to a fixed English month table (identical on en locales, deterministic everywhere else), and both bot-fitting backtests now also accept `--reposition`/`--reposition-pct` (additive; no existing flag changed meaning); and dead types (`JsonArray`, `DustCancelResult`, `MissingGenesisReason`), the ignored `fallbackNodes` option, the `quietUnderPm2` opt-in, the single `_onBroadcastRegionEnd` slot and 60 internal-only type exports are removed. Behavior-preserving; covered by `tests/test_chain_orders_account_resolution.ts`.
56
+
57
+ - **Feat(cli)**: add `dexbot git` repository statistics and streamline help — `scripts/analyze-git.ts` is exposed as a source-checkout-only `dexbot git` command (needs `.git`) matching the order/credit/tv dispatch pattern, and the flooding "All Tracked Files" console table is dropped (the HTML chart still renders per-file stats). CLI help is shortened: the multi-line pm2 summary collapses to `| pm2`, a new "Runtime flags (dexbot start)" block keeps `--foreground`/`--isolated`/`--dryrun`/`--headless` discoverable, `pm2 [<sub>]` points at `dexbot pm2 help`, full flag references stay for `tv`/`pnl`/`order`/`dw`, and dev-only `dexbot git` is kept out of the help surfaces (documented in `docs/WORKFLOW.md`). Text-only help diff; no behavior change.
58
+
59
+ - **Chore(tests)**: remove dead and vacuous tests and enforce runner honesty — dropped `test_fee_backwards_compat`/`test_market_fee_deduction` (asserted against local mocks, never imported production), `test_market_adapter_modular`/`test_privatekey_sanitize` (no assertions), `test_color_palette` (ANSI demo), `test_account_selection` (always skipped) and a live-only fee-cache demo, plus two README-only helpers and the removed live runner entry. `test_paths.ts` failure counting now affects the exit code (it previously reported PASS while printing ✗), `walkCliArgs` throws `"Flag X expects a value"` for a missing/flag-shaped value instead of storing `NaN` (negative numerics still accepted), profile-layout-dependent suites (autoderive, analyze-orders, pending-fill-crawls, claw regressions) use temp profile roots or `PATHS.*`, and credential-controller suites replace inert `require.cache` stubbing with the ESM mock loader (they previously passed vacuously). Also dropped the legacy analyzer test build wiring and the stale `analysis/trend_detection/package.json` + its two Kalman suites.
60
+
61
+ - **Chore(claw)**: ratchet claw explicit-`any` and fix plugin paths — the 1.6.12 program claimed the claw subtree was cleaned but it still carried 593 explicit `any` outside the ratchet; `scripts/check_any.ts` now counts root scopes and `claw/` as independent budgets (`any-budget.json` root:4, claw:593) so neither can regress. Claw gains `noUnusedLocals`/`noUnusedParameters` with the revealed dead locals/imports removed, a dead `createRequire`/`require` in `claw_bridge` is dropped, and the OpenClaw plugin's `main`/`openclaw.extensions` now resolve to the compiled `dist/claw` outputs (the source `.js` files were removed in the TS migration).
62
+
63
+ - **Chore(scripts)**: drop stale tools and document the credit analyzer — delete the one-off, pool-hardcoded `scripts/diagnose-kibana-candles.ts` and the dev-only `scripts/git-viewer.sh` (also dropped from the published `files` list); document the previously-unreferenced `analyze-credit.ts` (`dexbot credit`) in `scripts/README.md`.
64
+
65
+ - **Docs**: fix stale references after the month-shard and COW refactors — `analysis/README.md` (fetch_lp_candles is now a thin CLI sharing the month-shard cache; fills-cache shard naming lives in `market_adapter/utils/month_shards.ts`), `docs/COPY_ON_WRITE_MASTER_PLAN.md` (`_currentWorkingGrid` → `_currentWorkingGridStack` + ref-stack API), `market_adapter/README.md` and `scripts/README.md` (any ratchet, analysis scripts, `update_layout.ts`). Docs-only.
66
+
5
67
  ## [1.6.12] - 2026-10-08 - Type-Safety Ratchet, Shared ECC & Scrypt Correctness, Fresh-Placement Cancel Grace, Worker Drain & Partial Credit Renewal
6
68
 
7
69
  ### 2026-10-08
@@ -12,7 +74,9 @@ All notable changes to this project will be documented in this file.
12
74
 
13
75
  - **Fix(order-engine)**: defer cancels of freshly placed orders in COW reconcile and divergence paths — the reconcile/COW planner and divergence correction both run on target snapshots that can lag a just-placed order, so a surplus sweep on that snapshot canceled the fresh order (fee bleed, empty level) only for the next cycle to re-place it. `COWRebalanceEngine.execute` now accepts the owning manager and drops the whole slot action group (CANCEL paired with a CREATE) for orders inside `SURPLUS_CANCEL_GRACE_MS`, then re-syncs deferred slots from master via `workingGrid.syncFromMaster`; `applyGridDivergenceCorrections` drops any queued committed-size UPDATE for a not-desired/size-0 slot before skipping the cancel inside the window. The parameter stays optional so tests can drive the engine agelessly, and existing fixtures are aged via `_placedAt.clear()`. Also fixes an orphan double-count: `SyncEngine.synchronizeWithChain`'s createOrder branch kept the deferred-orphan record in `_lastUnmatchedChainOrders` after successful linkage, which fund accounting counts as committed on-chain funds, so a surviving record double-counted the order the slot now sees — the record is now pruned by chain id on successful linkage and kept on rejection or thrown errors. Covered by `tests/test_fresh_placement_cancel_grace_paths.ts` and `tests/test_sync_createorder_unmatched_prune.ts`.
14
76
 
15
- - **Fix(order-engine)**: keep spread correction funded by repairing what it places — spread correction on an out-of-spread grid could plan candidates but place nothing. The edge-partial top-up target was always a PARTIAL slot, so `clampPostFillUpdateSize` clamped it to a no-op COW update yet it ran first and consumed the whole budget, leaving the following creates rejected as dust; the target is removed (spread repair is create-only, a top-up cannot move bestBuy/bestSell) and creates are funded exclusively from `funds.available[side]` and the cached `accountTotals[side]Free`, so no resting order is ever shrunk. Candidate ordering now sorts a windowed rail by distance to the live-window anchor instead of raw price, so the correction bridges contiguously from the window and cannot leave an interior hole or over-tighten. `checkSpreadCondition` reports `fundsExhausted` whenever a correction places nothing and the targeted-sync refresh clears it after a successful re-read, so it only reconciles on a concrete fund-drift or counted-shortfall signal instead of churning every cycle.
77
+ - **Fix(order-engine)**: keep spread correction funded by repairing what it places — spread correction on an out-of-spread grid could plan candidates but place nothing. The edge-partial top-up target was always a PARTIAL slot, so `clampPostFillUpdateSize` clamped it to a no-op COW update yet it ran first and consumed the whole budget, leaving the following creates rejected as dust; the target is removed (spread repair is create-only, a top-up cannot move bestBuy/bestSell) and creates are funded exclusively from `funds.available[side]` and the cached `accountTotals[side]Free`, so no resting order is ever shrunk. Candidate ordering now sorts a windowed rail by distance to the live-window anchor instead of raw price, so the correction bridges contiguously from the window and cannot leave an interior hole or over-tighten. `checkSpreadCondition` reports a `stall` cause whenever a correction places nothing — `no-free-funds`/`unfunded`/`no-candidates`/`batch-not-executed`/`apply-error`, merged across the starvation fallback so an unfunded plan on one side is not masked by an empty opposite side — and the targeted-sync refresh arms on the stall, clearing after a successful re-read so it only reconciles on a concrete fund-drift or counted-shortfall signal instead of churning every cycle.
78
+
79
+ - **Fix(order-engine)**: sync with the chain on every spread-correction stall — the previous gate armed the targeted balances + open-orders refresh only for the fund/batch causes and deliberately left a `no-candidates` stall to the out-of-spread staleness watchdog, which can be up to `SPREAD_STALE_ESCALATE_MS` (30 min). But `no-candidates` is derived from the LOCAL grid: a missed fill leaves a slot at the window edge locally ACTIVE while its chain order is gone, so `_getOnChainOrders` makes that phantom the `bestLiveOnRail` and every real tightening slot looks non-tightening. The maintenance mirror (`mirrorSpreadStall`) now arms the refresh for every stall cause, so the next tick re-reads account totals + open orders and virtualizes the phantom; the watchdog remains the backstop. Covered by `tests/test_spread_correction_market_nearest.ts` (a phantom ACTIVE slot reports `no-candidates`, and virtualizing it — what `synchronizeWithChain` does — restores placement) and `tests/test_targeted_drift_reconcile.ts` (the mirror arms every cause; the gate names `no-candidates`).
16
80
 
17
81
  - **Fix(lifecycle)**: drain monolithic workers on stale and absent pid-file stop paths — `stop` returned as soon as the monolithic wrapper exited, but the supervisor pid file is wiped on wrapper exit and the `/proc` worker-drain loop ran only after a clean wrapper exit, so a racing `start` could spawn a SECOND worker over live orders (duplicate trades). `drainMonolithicWorkers` (same 15s deadline, 250ms poll, same warn-on-exhaustion; a failed `/proc` scan yields 0 so it stays a no-op off Linux) is extracted and also run when the pid file is stale (except on `status`) and when there is no wrapper pid file at all for targeted stop/delete and stop-all/delete/restart-all/reload-all. Cost is up to 15s block while a worker lingers, intentional best-effort. Covered by `tests/test_unlock_worker_drain.ts`.
18
82
 
package/README.md CHANGED
@@ -246,8 +246,8 @@ Grouped exactly as the bot editor shows them (`dexbot bot` → `2) Modify bot`
246
246
  | Parameter | Type | Description |
247
247
  | :--- | :--- | :--- |
248
248
  | **`botFunds`** | object | `Sell`/`Buy` — capital allocation: `{ sell: "100%", buy: "100%" }`. Numbers or percentage strings |
249
- | **`activeOrders`** | object | `MarketOrder` — target active orders per side, counted closest to the market: `{ sell: 20, buy: 20 }` |
250
- | **`reserveOrders`** | object | `EdgeOrder` — edge-pinned insurance orders resting live outside the active window, to catch fat fingers: `{ buy: 0, sell: 0 }` (`buy` pins the grid floor, `sell` the grid ceiling; `0` disables per side) |
249
+ | **`coreOrders`** | object | `CoreOrder` — target active orders per side, counted closest to the market: `{ sell: 20, buy: 20 }` |
250
+ | **`edgeOrders`** | object | `EdgeOrder` — edge-pinned insurance orders resting live outside the active window, to catch fat fingers: `{ buy: 0, sell: 0 }` (`buy` pins the grid floor, `sell` the grid ceiling; `0` disables per side) |
251
251
 
252
252
  **`6) Adapter`**
253
253
 
@@ -91,7 +91,7 @@ Most runners expect candle data. Two paths to get it:
91
91
  # Via the market adapter LP exporter (recommended for blockchain-backed candles)
92
92
  node dist/market_adapter/inputs/fetch_lp_data.js --pool 133 --precA 4 --precB 5 --interval 1h --lookback 26280h
93
93
 
94
- # Via the analysis fetcher (uses Kibana source directly)
94
+ # Via the analysis fetcher (shares the month-shard candle cache with dexbot tv/dw)
95
95
  node dist/analysis/ama_fitting/fetch_lp_candles.js --pool 1.19.133 \
96
96
  --assetA <ASSET_A> --assetAId <asset_a_id> --assetAPrecision <n> \
97
97
  --assetB <ASSET_B> --assetBId <asset_b_id> --assetBPrecision <n>
@@ -434,21 +434,19 @@ Shared analyzers and chart renderers for the dynamic-weight signal path. Core en
434
434
  | Module | Purpose |
435
435
  |--------|---------|
436
436
  | `dynamic_weight_chart_generator.ts` | 4-panel uPlot chart with interactive knobs for dynamic weight tuning |
437
- | `kalman_trend_analyzer.ts` | Kalman filter with tactical (velocity) and modal (displacement) states |
438
- | `kalman_velocity_smoothing.ts` | Adaptive EMA smoothing for Kalman velocity (kf/kfd/kdt/kfs knobs) |
437
+ | `kalman_trend_analyzer.ts` | Re-export shim → `market_adapter/core/signals/kalman_trend_analyzer.ts` |
438
+ | `kalman_velocity_smoothing.ts` | Re-export shim → `market_adapter/core/signals/kalman_velocity_smoothing.ts` |
439
439
  | `kalman_chart_generator.ts` | Kalman signal chart generator |
440
- | `hurst_analyzer.ts` | Hurst Exponent via R/S analysis (rolling 256-bar window) |
441
- | `permutation_entropy_analyzer.ts` | Permutation Entropy via ordinal pattern counting (m=5, window=54) |
440
+ | `hurst_analyzer.ts` | Re-export shim → `market_adapter/core/signals/hurst_analyzer.ts` |
441
+ | `permutation_entropy_analyzer.ts` | Re-export shim → `market_adapter/core/signals/permutation_entropy_analyzer.ts` |
442
442
  | `volatility_chart_generator.ts` | ATR volatility / symmetric shift chart generator |
443
443
  | `regime_chart_generator.ts` | Regime classification chart generator |
444
444
 
445
445
  </details>
446
446
 
447
- **Tests:**
448
-
449
- ```bash
450
- npm run test:legacy
451
- ```
447
+ The four signal analyzers are canonical in `market_adapter/core/signals/`; the
448
+ files here are thin re-export shims so analysis tooling keeps a local import
449
+ path.
452
450
 
453
451
  **Note:** `trend_detection/` has no external dependencies — runs directly from the compiled build (`node dist/...`).
454
452
 
@@ -530,7 +528,7 @@ Details: [bot_fitting/README.md](bot_fitting/README.md)
530
528
  | `account_resolver.ts` | Account resolution for all tools: `preferredAccount` / `--account` → `1.2.x`, stamping the result into `profiles/bots.json` |
531
529
  | `chain_pool.ts` | Ephemeral read-only chain client over the built-in node pool (account + asset lookups) |
532
530
  | `fills_source.ts` | Shared `fill_order` Kibana fetch/query and the static asset-precision table + on-chain cache |
533
- | `fills_cache.ts` | Per-account month-shard cache for `fill_order` fetches (settled months reused, unsettled tail refreshed) |
531
+ | `fills_cache.ts` | Per-account month-shard cache for `fill_order` fetches (settled months reused, unsettled tail refreshed); month-shard naming comes from `market_adapter/utils/month_shards.ts` |
534
532
  | `pnl_report.ts` | Self-contained HTML PnL renderer: hero, card blocks, metrics grid, realized-lots table |
535
533
 
536
534
  On-chain account and asset lookups in the fill-based tools go through `account_resolver.ts` / `fills_source.ts` (both built on `chain_pool.ts`): tool scripts must not open their own read-only clients or carry their own node list. The batch backfill `resolve_bot_accounts.ts` is the exception — it reuses the production chain client over one connection.
@@ -21,9 +21,11 @@ parameters into `profiles/market_profiles.json` for the market adapter.
21
21
 
22
22
  ## Step 1 — Fetch LP Candles
23
23
 
24
- `fetch_lp_candles.ts` fetches bidirectional LP swap data from Kibana and saves
25
- a full uncut candle file. Uses the same `kibana_source` as the market adapter
26
- bootstrap (gaps filled via `candle_utils.fillCandleGaps`), but without pruning.
24
+ `fetch_lp_candles.ts` fetches bidirectional LP swap data from Kibana through
25
+ the shared month-shard cache — the same cache `dexbot tv`/`dexbot dw` write —
26
+ then exports a full uncut candle file. Re-runs reuse the cached months and
27
+ query only the missing buckets; the whole-history file is a convenience
28
+ snapshot of the assembled shards.
27
29
 
28
30
  **Known asset details:**
29
31
 
package/claw/README.md CHANGED
@@ -233,6 +233,7 @@ Install the native plugin bundle from this repository:
233
233
  ```bash
234
234
  CLAW_ROOT="$(pwd)"
235
235
  DEXBOT_ROOT="$(cd .. && pwd)"
236
+ npm run build
236
237
  openclaw plugins install -l "$CLAW_ROOT"
237
238
  openclaw plugins enable bitshares-claw
238
239
  ```
@@ -282,7 +282,7 @@ The bot-specific state Claw already owns and passes through the infrastructure l
282
282
  type BotState = {
283
283
  botId: string;
284
284
  name: string;
285
- activeOrders?: number;
285
+ coreOrders?: number;
286
286
  incrementPercent?: number;
287
287
  targetSpreadPercent?: number;
288
288
  weightDistribution?: { sell: number; buy: number };
@@ -319,6 +319,8 @@ type ConstraintSet = {
319
319
 
320
320
  All functions below are implemented in the modules cited under "Core Types" or their headers and are reachable through the adapters/factories they document. Standalone names are exported from the cited modules; methods like `getBotSettings`, `previewBotSettingsUpdate`, `applyBotSettingsPatch`, and `getClawProfileContext` are closures returned by `createDexbotProfileAdapter` (not module-level exports). Signatures reflect the runtime types; see [../modules/types.ts](../modules/types.ts) for the authoritative TypeScript interfaces.
321
321
 
322
+ Internal-only modules that are intentionally **not** re-exported from [../index.ts](../index.ts): `modules/claw_launcher.ts`, `modules/launcher_mode_detector.ts`, `modules/launcher_paths.ts`, `modules/mcp_utils.ts`, `modules/mpa_utils.ts`, `modules/skill_utils.ts`, `modules/utils.ts`, and the type-only `modules/types.ts`. Import them directly when building inside `claw/`; they are not part of the public bridge surface.
323
+
322
324
  ### 1. `createRuntimeContext(options)`
323
325
 
324
326
  Creates a shared runtime object for Claw ([../modules/claw_infra.ts](../modules/claw_infra.ts)).
@@ -15,7 +15,7 @@ Keep these structural settings static in normal operation:
15
15
 
16
16
  - `incrementPercent`
17
17
  - `targetSpreadPercent`
18
- - `activeOrders`
18
+ - `coreOrders`
19
19
 
20
20
  These settings define ladder geometry and order-size distribution, so changing them is a retune, not a tactical response.
21
21
 
@@ -99,7 +99,7 @@ This is how much of each side's available balance gets committed.
99
99
  - leaving reserve gives you flexibility for fees, manual intervention, and regime changes
100
100
  - if orders get too small, reduce commitment or reduce order count
101
101
 
102
- ### `activeOrders`
102
+ ### `coreOrders`
103
103
 
104
104
  This is the number of live orders kept near the market on each side.
105
105
 
@@ -147,7 +147,7 @@ The clean mental model is:
147
147
  - `targetSpreadPercent` controls the empty buffer
148
148
  - `weightDistribution` controls size concentration
149
149
  - `botFunds` controls risk budget
150
- - `activeOrders` controls depth
150
+ - `coreOrders` controls depth
151
151
 
152
152
  ## When to adjust
153
153
 
@@ -210,7 +210,7 @@ For a conservative starting point:
210
210
 
211
211
  - `incrementPercent: 0.5`
212
212
  - `targetSpreadPercent: 2.0`
213
- - `activeOrders: 20 / 20`
213
+ - `coreOrders: 20 / 20`
214
214
  - `weightDistribution: 0.5 / 0.5`
215
215
  - `minPrice` and `maxPrice`: as narrow as the expected drift allows, not blindly `3x`
216
216
 
@@ -1,7 +1,4 @@
1
1
 
2
- import { createRequire } from 'node:module';
3
- const require = createRequire(import.meta.url);
4
-
5
2
  import { createClawInfrastructure } from './claw_infra.js';
6
3
  import { describeClawBridge } from './claw_manifest.js';
7
4
  import { describeMemuBridge, runMemuCommand } from './memu_bridge.js';
@@ -103,10 +103,14 @@ function botSettingsPatchSchema(description: string | null = null) {
103
103
  return objectSchema({
104
104
  patch: strictObjectSchema({
105
105
  active: booleanSchema('Whether the bot is active'),
106
- activeOrders: strictObjectSchema({
107
- buy: integerSchema('Buy-side active order count'),
108
- sell: integerSchema('Sell-side active order count')
109
- }, [], 'Per-side active order counts'),
106
+ coreOrders: strictObjectSchema({
107
+ buy: integerSchema('Buy-side core order count'),
108
+ sell: integerSchema('Sell-side core order count')
109
+ }, [], 'Per-side core window order counts'),
110
+ edgeOrders: strictObjectSchema({
111
+ buy: integerSchema('Buy-side edge order count'),
112
+ sell: integerSchema('Sell-side edge order count')
113
+ }, [], 'Per-side edge-pinned reserve order counts'),
110
114
  assetA: stringSchema('Base asset symbol'),
111
115
  assetAId: stringSchema('Base asset id'),
112
116
  assetB: stringSchema('Quote asset symbol'),
@@ -177,6 +177,7 @@ function buildRuntimeSetup(runtime: any, repoRoot: string, profileRoot: string)
177
177
  'Install the native plugin from this repository:',
178
178
  '',
179
179
  '```bash',
180
+ 'npm run build',
180
181
  `openclaw plugins install -l ${repoRoot}`,
181
182
  'openclaw plugins enable bitshares-claw',
182
183
  '```',
@@ -8,6 +8,7 @@ import { PATHS } from '../../modules/paths.js';
8
8
  import { writeJsonFileAtomic as baseWriteJsonFileAtomic } from '../../modules/bots_file_lock.js';
9
9
  import { acquireFileLock } from '../../market_adapter/utils/file_lock.js';
10
10
  import { assertNoDuplicateBotKeys, normalizeBotEntry } from '../../modules/bot_settings.js';
11
+ import { migrateLegacyOrderKeys } from '../../modules/bot_defaults.js';
11
12
  import { BOT_LIVE_CONFIG_KEYS } from '../../modules/runtime_settings.js';
12
13
  import { clone } from './utils.js';
13
14
  import { createBotKey, sanitizeKey } from '../../modules/account_orders.js';
@@ -24,7 +25,7 @@ const DEFAULT_MARKET_PROFILES_FILE = 'market_profiles.json';
24
25
  const DEFAULT_ORDERS_DIR = 'orders';
25
26
 
26
27
  const KNOWN_BOT_KEYS = new Set([
27
- 'active', 'activeOrders', 'assetA', 'assetAId', 'assetB', 'assetBId',
28
+ 'active', 'coreOrders', 'edgeOrders', 'assetA', 'assetAId', 'assetB', 'assetBId',
28
29
  'botFunds', 'debtPolicy', 'dryRun', 'gridPrice',
29
30
  'incrementPercent', 'maxPrice',
30
31
  'minPrice', 'name', 'preferredAccount', 'startPrice', 'strategy',
@@ -35,7 +36,8 @@ const KNOWN_BOT_KEYS = new Set([
35
36
  const BOT_SETTINGS_READ_ONLY_KEYS = new Set(['botIndex', 'botKey']);
36
37
  const BOT_SETTINGS_TRIGGER_KEYS = new Set([
37
38
  'active',
38
- 'activeOrders',
39
+ 'coreOrders',
40
+ 'edgeOrders',
39
41
  'assetA',
40
42
  'assetAId',
41
43
  'assetB',
@@ -59,7 +61,8 @@ const REQUIRED_BOT_KEY_ALIASES = {
59
61
  };
60
62
 
61
63
  const BOT_SETTINGS_NESTED_KEYS = Object.freeze({
62
- activeOrders: new Set(['buy', 'sell']),
64
+ coreOrders: new Set(['buy', 'sell']),
65
+ edgeOrders: new Set(['buy', 'sell']),
63
66
  botFunds: new Set(['buy', 'sell']),
64
67
  weightDistribution: new Set(['buy', 'sell'])
65
68
  });
@@ -211,7 +214,7 @@ function cloneBotSettings(value: any) {
211
214
  * Fills missing fields from DEFAULT_CONFIG and clamps values within bounds.
212
215
  */
213
216
  function normalizeBotSettings(bot: Partial<BotSettings> = {}) {
214
- const normalized = cloneBotSettings(bot) || {};
217
+ const normalized = migrateLegacyOrderKeys(cloneBotSettings(bot) || {});
215
218
 
216
219
  normalized.active = normalizeBooleanField(normalized.active, DEFAULT_CONFIG.active);
217
220
  normalized.dryRun = normalizeBooleanField(normalized.dryRun, DEFAULT_CONFIG.dryRun);
@@ -233,15 +236,25 @@ function normalizeBotSettings(bot: Partial<BotSettings> = {}) {
233
236
  ...cloneBotSettings(DEFAULT_CONFIG.botFunds),
234
237
  ...(isPlainObject(normalized.botFunds) ? normalized.botFunds : {})
235
238
  };
236
- normalized.activeOrders = {
237
- ...cloneBotSettings(DEFAULT_CONFIG.activeOrders),
238
- ...(isPlainObject(normalized.activeOrders) ? normalized.activeOrders : {})
239
+ normalized.coreOrders = {
240
+ ...cloneBotSettings(DEFAULT_CONFIG.coreOrders),
241
+ ...(isPlainObject(normalized.coreOrders) ? normalized.coreOrders : {})
242
+ };
243
+ // Legacy numeric form migrates to `{ buy: n, sell: 0 }` before the default
244
+ // merge (mirrors the shared runtime resolver).
245
+ if (typeof normalized.edgeOrders === 'number') {
246
+ normalized.edgeOrders = { buy: Math.max(0, Math.floor(normalized.edgeOrders)), sell: 0 };
247
+ }
248
+ normalized.edgeOrders = {
249
+ ...cloneBotSettings(DEFAULT_CONFIG.edgeOrders),
250
+ ...(isPlainObject(normalized.edgeOrders) ? normalized.edgeOrders : {})
239
251
  };
240
252
  return normalized;
241
253
  }
242
254
 
243
255
  function mergeBotSettingsPatch(currentBot: Record<string, any> = {}, patch: Record<string, any> = {}) {
244
- const next = cloneBotSettings(currentBot) || {};
256
+ const next = migrateLegacyOrderKeys(cloneBotSettings(currentBot) || {});
257
+ patch = migrateLegacyOrderKeys({ ...patch });
245
258
  const patchKeys = Object.keys(patch || {});
246
259
 
247
260
  for (const key of patchKeys) {
@@ -250,7 +263,7 @@ function mergeBotSettingsPatch(currentBot: Record<string, any> = {}, patch: Reco
250
263
  continue;
251
264
  }
252
265
 
253
- if (['weightDistribution', 'botFunds', 'activeOrders'].includes(key) && isPlainObject(value)) {
266
+ if (['weightDistribution', 'botFunds', 'coreOrders', 'edgeOrders'].includes(key) && isPlainObject(value)) {
254
267
  next[key] = {
255
268
  ...(isPlainObject(next[key]) ? next[key] : {}),
256
269
  ...value
@@ -410,22 +423,48 @@ function validateBotSettingsValue(field: any, value: any, errors: any[]) {
410
423
  }
411
424
  break;
412
425
 
413
- case 'activeOrders':
426
+ case 'coreOrders':
414
427
  if (!isPlainObject(value)) {
415
- push('activeOrders must be an object with sell and buy');
428
+ push('coreOrders must be an object with sell and buy');
416
429
  break;
417
430
  }
418
- validateNestedBotSettingKeys('activeOrders', value, errors);
431
+ validateNestedBotSettingKeys('coreOrders', value, errors);
419
432
  for (const side of ['sell', 'buy']) {
420
433
  const sideValue = value[side];
421
434
  if (sideValue === undefined) {
422
435
  continue;
423
436
  }
424
437
  if (!Number.isInteger(Number(sideValue)) || Number(sideValue) < 0) {
425
- push(`activeOrders.${side} must be an integer greater than or equal to 0`);
438
+ push(`coreOrders.${side} must be an integer greater than or equal to 0`);
439
+ }
440
+ }
441
+ break;
442
+
443
+ case 'edgeOrders': {
444
+ // Legacy numeric form is accepted and migrated at read time.
445
+ const edgeValue = typeof value === 'number'
446
+ ? { buy: value, sell: 0 }
447
+ : value;
448
+ if (typeof value === 'number' && (!Number.isInteger(value) || value < 0)) {
449
+ push('edgeOrders numeric form must be a non-negative integer');
450
+ break;
451
+ }
452
+ if (!isPlainObject(edgeValue)) {
453
+ push('edgeOrders must be an object with sell and buy');
454
+ break;
455
+ }
456
+ validateNestedBotSettingKeys('edgeOrders', edgeValue, errors);
457
+ for (const side of ['sell', 'buy']) {
458
+ const sideValue = edgeValue[side];
459
+ if (sideValue === undefined) {
460
+ continue;
461
+ }
462
+ if (!Number.isInteger(Number(sideValue)) || Number(sideValue) < 0) {
463
+ push(`edgeOrders.${side} must be an integer greater than or equal to 0`);
426
464
  }
427
465
  }
428
466
  break;
467
+ }
429
468
 
430
469
  case 'debtPolicy':
431
470
  if (value !== undefined && value !== null && typeof value !== 'object') {
@@ -470,6 +509,9 @@ function validateBotSettingsValue(field: any, value: any, errors: any[]) {
470
509
  function validateBotSettingsState(bot: Record<string, any> = {}) {
471
510
  const errors: string[] = [];
472
511
  const warnings = [];
512
+ // Legacy key aliases collapse before validation so a pre-rename entry is
513
+ // neither rejected nor reported as an unrecognized key.
514
+ bot = migrateLegacyOrderKeys({ ...bot });
473
515
 
474
516
  for (const field of Object.keys(BOT_SETTINGS_NESTED_KEYS)) {
475
517
  if (bot[field] !== undefined) {
@@ -539,7 +581,6 @@ function validateBotSettingsState(bot: Record<string, any> = {}) {
539
581
  function validateBotSettingsPatch(patch: Record<string, any> = {}, currentBot: Record<string, any> = {}, options: Partial<ProfileOptions> = {}) {
540
582
  const errors: string[] = [];
541
583
  const warnings = [];
542
- const patchKeys = Object.keys(patch || {});
543
584
  const allowUnknownKeys = Boolean(options.allowUnknownKeys);
544
585
 
545
586
  if (!isPlainObject(patch)) {
@@ -553,6 +594,9 @@ function validateBotSettingsPatch(patch: Record<string, any> = {}, currentBot: R
553
594
  };
554
595
  }
555
596
 
597
+ patch = migrateLegacyOrderKeys({ ...patch });
598
+ const patchKeys = Object.keys(patch);
599
+
556
600
  for (const key of patchKeys) {
557
601
  if (!KNOWN_BOT_KEYS.has(key)) {
558
602
  if (allowUnknownKeys) {
@@ -563,7 +607,7 @@ function validateBotSettingsPatch(patch: Record<string, any> = {}, currentBot: R
563
607
  continue;
564
608
  }
565
609
 
566
- if (['weightDistribution', 'botFunds', 'activeOrders'].includes(key) && isPlainObject(patch[key])) {
610
+ if (['weightDistribution', 'botFunds', 'coreOrders', 'edgeOrders'].includes(key) && isPlainObject(patch[key])) {
567
611
  validateNestedBotSettingKeys(key, patch[key], errors);
568
612
  const mergedField = {
569
613
  ...(isPlainObject(currentBot[key]) ? currentBot[key] : {}),
@@ -97,7 +97,8 @@ export interface ClawBridgeOptions {
97
97
 
98
98
  export interface BotSettings {
99
99
  active?: boolean;
100
- activeOrders?: { sell?: number; buy?: number };
100
+ coreOrders?: { sell?: number; buy?: number };
101
+ edgeOrders?: number | { sell?: number; buy?: number };
101
102
  assetA?: string;
102
103
  assetAId?: string;
103
104
  assetB?: string;
package/claw/package.json CHANGED
@@ -1,10 +1,10 @@
1
1
  {
2
2
  "name": "dexbot2-claw",
3
- "version": "1.6.12",
3
+ "version": "1.6.14",
4
4
  "private": true,
5
5
  "description": "Claw bridge and runtime integration layer for BitShares and DEXBot2.",
6
6
  "type": "module",
7
- "main": "index.js",
7
+ "main": "../dist/claw/index.js",
8
8
  "peerDependencies": {
9
9
  "openclaw": ">=2026.3.27"
10
10
  },
@@ -15,7 +15,7 @@
15
15
  },
16
16
  "openclaw": {
17
17
  "extensions": [
18
- "./runtimes/openclaw-plugin/index.js"
18
+ "../dist/claw/runtimes/openclaw-plugin/index.js"
19
19
  ]
20
20
  },
21
21
  "scripts": {
@@ -2,7 +2,7 @@
2
2
  "id": "bitshares-claw",
3
3
  "name": "BitShares Claw",
4
4
  "description": "Native BitShares and DEXBot2 tools from the DEXBot2 claw integration",
5
- "version": "1.6.12",
5
+ "version": "1.6.14",
6
6
  "skills": [
7
7
  "skills"
8
8
  ],
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "bitshares-claw-openclaw-plugin",
3
3
  "private": true,
4
- "version": "1.6.12",
4
+ "version": "1.6.14",
5
5
  "type": "module",
6
6
  "main": "index.js"
7
7
  }
@@ -11,7 +11,7 @@ Covers the trading concepts available through the claw bridge, the mechanics of
11
11
 
12
12
  The practical control model is split into:
13
13
 
14
- - structural settings that are usually kept fixed (`incrementPercent`, `targetSpreadPercent`, `activeOrders`)
14
+ - structural settings that are usually kept fixed (`incrementPercent`, `targetSpreadPercent`, `coreOrders`)
15
15
  - adaptive settings layered on top of AMA (`weightDistribution`, min/max range ratio, debt/collateral actions)
16
16
 
17
17
  ## Reference Files
@@ -75,7 +75,7 @@ These should stay static unless you intentionally retune the bot for a different
75
75
 
76
76
  - `incrementPercent`
77
77
  - `targetSpreadPercent`
78
- - `activeOrders`
78
+ - `coreOrders`
79
79
 
80
80
  These settings define the ladder geometry:
81
81
 
@@ -11,8 +11,8 @@
11
11
  "outDir": "../dist",
12
12
  "rootDir": "..",
13
13
  "strict": true,
14
- "noUnusedLocals": false,
15
- "noUnusedParameters": false,
14
+ "noUnusedLocals": true,
15
+ "noUnusedParameters": true,
16
16
  "esModuleInterop": true,
17
17
  "skipLibCheck": true,
18
18
  "forceConsistentCasingInFileNames": true,
@@ -10,6 +10,7 @@ import { PATHS } from '../../modules/paths.js';
10
10
  import { MARKET_ADAPTER } from '../../modules/constants.js';
11
11
  import { getErrorMessage } from '../../modules/utils/errors.js';
12
12
  import { uplotInlineTags } from '../chart_utils.js';
13
+ import { geometricRange } from '../math_utils.js';
13
14
  /**
14
15
  * LAMBDA vs SLOW ANALYSIS
15
16
  *
@@ -122,20 +123,6 @@ function calcTotalRelativeDistance(amaValues, candles, erPeriod) {
122
123
  }
123
124
  return total;
124
125
  }
125
- // ── Geometric range ─────────────────────────────────────────────────────────────
126
- function geometricRange(min, max, count) {
127
- const ratio = Math.pow(max / min, 1 / (count - 1));
128
- const out = [];
129
- for (let i = 0; i < count; i++) {
130
- let v = min * Math.pow(ratio, i);
131
- if (i === 0)
132
- v = min;
133
- if (i === count - 1)
134
- v = max;
135
- out.push(parseFloat(v.toFixed(10)));
136
- }
137
- return [...new Set(out)].sort((a, b) => a - b);
138
- }
139
126
  // ── Precompute (movement, distance) per slow ───────────────────────────────────
140
127
  function precomputeMetrics(closes, candles, erPeriod, fastPeriod, slowValues) {
141
128
  const cache = [];