dexbot 1.6.12 → 1.6.13

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 (170) hide show
  1. package/CHANGELOG.md +33 -1
  2. package/analysis/README.md +9 -11
  3. package/analysis/ama_fitting/README.md +5 -3
  4. package/claw/README.md +1 -0
  5. package/claw/docs/AI_BOT_LIBRARY_API.md +2 -0
  6. package/claw/modules/claw_bridge.ts +0 -3
  7. package/claw/modules/claw_skill_md.ts +1 -0
  8. package/claw/package.json +3 -3
  9. package/claw/runtimes/openclaw-plugin/openclaw.plugin.json +1 -1
  10. package/claw/runtimes/openclaw-plugin/package.json +1 -1
  11. package/claw/tsconfig.json +2 -2
  12. package/dist/analysis/ama_fitting/analyze_lambda_vs_slow.js +1 -14
  13. package/dist/analysis/ama_fitting/fetch_lp_candles.js +51 -41
  14. package/dist/analysis/ama_fitting/generate_unified_comparison_chart.d.ts +1 -24
  15. package/dist/analysis/ama_fitting/generate_unified_comparison_chart.js +36 -18
  16. package/dist/analysis/ama_fitting/optimizer_high_resolution.js +18 -66
  17. package/dist/analysis/analyze_args.d.ts +12 -0
  18. package/dist/analysis/analyze_args.js +20 -0
  19. package/dist/analysis/bot_fitting/backtest_ama_sweep.d.ts +1 -16
  20. package/dist/analysis/bot_fitting/backtest_ama_sweep.js +20 -101
  21. package/dist/analysis/bot_fitting/backtest_bot_fitting.js +26 -92
  22. package/dist/analysis/bot_fitting/backtest_lookback_drawdown.js +19 -34
  23. package/dist/analysis/bot_fitting/shared_utils.d.ts +71 -3
  24. package/dist/analysis/bot_fitting/shared_utils.js +124 -8
  25. package/dist/analysis/chart_ui.d.ts +30 -1
  26. package/dist/analysis/chart_ui.js +37 -1
  27. package/dist/analysis/fills_cache.d.ts +3 -23
  28. package/dist/analysis/fills_cache.js +3 -84
  29. package/dist/analysis/fills_source.d.ts +31 -1
  30. package/dist/analysis/fills_source.js +69 -1
  31. package/dist/analysis/grid_correction_check.d.ts +1 -23
  32. package/dist/analysis/grid_correction_check.js +15 -58
  33. package/dist/analysis/math_utils.d.ts +85 -1
  34. package/dist/analysis/math_utils.js +116 -1
  35. package/dist/analysis/price_sources.d.ts +22 -1
  36. package/dist/analysis/price_sources.js +23 -0
  37. package/dist/analysis/resolve_source.js +31 -10
  38. package/dist/analysis/trade_profitability.d.ts +6 -0
  39. package/dist/analysis/trade_profitability.js +23 -97
  40. package/dist/analysis/tradingview/analyze_tradingview.d.ts +1 -17
  41. package/dist/analysis/tradingview/analyze_tradingview.js +1 -1
  42. package/dist/analysis/tradingview/tradingview_uplot_chart_generator.js +2 -15
  43. package/dist/analysis/trend_detection/backtest_ama_slope_huber.d.ts +1 -101
  44. package/dist/analysis/trend_detection/backtest_ama_slope_huber.js +22 -80
  45. package/dist/analysis/trend_detection/dynamic_weight_chart_generator.js +11 -37
  46. package/dist/analysis/trend_detection/volatility_chart_generator.js +9 -10
  47. package/dist/analysis/worker_pool.d.ts +38 -0
  48. package/dist/analysis/worker_pool.js +67 -0
  49. package/dist/dexbot.js +67 -48
  50. package/dist/market_adapter/ama_signal_runner.js +21 -54
  51. package/dist/market_adapter/candle_utils.d.ts +7 -1
  52. package/dist/market_adapter/candle_utils.js +11 -1
  53. package/dist/market_adapter/cli_args.d.ts +22 -0
  54. package/dist/market_adapter/cli_args.js +30 -0
  55. package/dist/market_adapter/core/config_normalizers.js +11 -6
  56. package/dist/market_adapter/core/kibana_candles.d.ts +3 -1
  57. package/dist/market_adapter/core/kibana_candles.js +3 -2
  58. package/dist/market_adapter/core/market_adapter_service.d.ts +85 -85
  59. package/dist/market_adapter/core/market_adapter_service.js +93 -158
  60. package/dist/market_adapter/core/signals/hurst_analyzer.d.ts +1 -6
  61. package/dist/market_adapter/core/signals/hurst_analyzer.js +1 -1
  62. package/dist/market_adapter/core/signals/permutation_entropy_analyzer.d.ts +1 -11
  63. package/dist/market_adapter/core/signals/permutation_entropy_analyzer.js +1 -1
  64. package/dist/market_adapter/inputs/fetch_book_data.js +0 -1
  65. package/dist/market_adapter/inputs/fetch_cex_synthetic_data.js +63 -107
  66. package/dist/market_adapter/inputs/fetch_lp_data.d.ts +8 -1
  67. package/dist/market_adapter/inputs/fetch_lp_data.js +25 -7
  68. package/dist/market_adapter/inputs/kibana_feed_source.js +4 -26
  69. package/dist/market_adapter/inputs/window_cache.d.ts +4 -72
  70. package/dist/market_adapter/inputs/window_cache.js +52 -177
  71. package/dist/market_adapter/interval_utils.d.ts +11 -1
  72. package/dist/market_adapter/interval_utils.js +16 -1
  73. package/dist/market_adapter/lp_chart_runner.d.ts +3 -0
  74. package/dist/market_adapter/lp_chart_runner.js +37 -19
  75. package/dist/market_adapter/market_adapter.js +27 -72
  76. package/dist/market_adapter/utils/data_discovery.d.ts +45 -1
  77. package/dist/market_adapter/utils/data_discovery.js +220 -27
  78. package/dist/market_adapter/utils/month_shards.d.ts +84 -0
  79. package/dist/market_adapter/utils/month_shards.js +237 -0
  80. package/dist/modules/account_bots.d.ts +1 -0
  81. package/dist/modules/account_bots.js +102 -121
  82. package/dist/modules/account_orders.d.ts +13 -0
  83. package/dist/modules/account_orders.js +38 -44
  84. package/dist/modules/bitshares-native/chain_client.d.ts +1 -1
  85. package/dist/modules/bitshares-native/chain_client.js +14 -13
  86. package/dist/modules/bitshares-native/resolvers.js +22 -25
  87. package/dist/modules/bitshares-native/serial/types.js +22 -50
  88. package/dist/modules/bitshares-native/signing_client.d.ts +1 -1
  89. package/dist/modules/bot_defaults.d.ts +2 -1
  90. package/dist/modules/bot_settings.d.ts +1 -1
  91. package/dist/modules/broadcast_failure.d.ts +2 -1
  92. package/dist/modules/chain_orders.d.ts +1 -1
  93. package/dist/modules/chain_orders.js +51 -96
  94. package/dist/modules/cli_start_onboarding.d.ts +2 -1
  95. package/dist/modules/constants.d.ts +7 -1
  96. package/dist/modules/constants.js +20 -1
  97. package/dist/modules/cr_planner.d.ts +1 -1
  98. package/dist/modules/cr_planner.js +1 -5
  99. package/dist/modules/credit_pricing.d.ts +2 -1
  100. package/dist/modules/credit_pricing.js +36 -40
  101. package/dist/modules/credit_runtime.d.ts +7 -0
  102. package/dist/modules/credit_runtime.js +45 -73
  103. package/dist/modules/daemon_node_health.d.ts +4 -3
  104. package/dist/modules/dexbot_class.d.ts +28 -17
  105. package/dist/modules/dexbot_class.js +105 -58
  106. package/dist/modules/dexbot_cow_runtime.d.ts +0 -7
  107. package/dist/modules/dexbot_cow_runtime.js +54 -28
  108. package/dist/modules/dexbot_credential_client.d.ts +0 -7
  109. package/dist/modules/dexbot_credential_client.js +1 -2
  110. package/dist/modules/dexbot_fill_runtime.d.ts +1 -2
  111. package/dist/modules/dexbot_fill_runtime.js +5 -6
  112. package/dist/modules/dexbot_maintenance_runtime.d.ts +20 -3
  113. package/dist/modules/dexbot_maintenance_runtime.js +84 -69
  114. package/dist/modules/dexbot_startup_runtime.d.ts +0 -1
  115. package/dist/modules/dexbot_startup_runtime.js +13 -14
  116. package/dist/modules/general_settings.d.ts +1 -1
  117. package/dist/modules/graceful_shutdown.js +17 -11
  118. package/dist/modules/key_store.js +0 -1
  119. package/dist/modules/lazy_shim.d.ts +11 -0
  120. package/dist/modules/lazy_shim.js +16 -0
  121. package/dist/modules/node_connect_policy.d.ts +3 -2
  122. package/dist/modules/node_failure_ledger.d.ts +6 -5
  123. package/dist/modules/order/format.d.ts +12 -3
  124. package/dist/modules/order/format.js +15 -3
  125. package/dist/modules/order/genesis_policy.d.ts +3 -3
  126. package/dist/modules/order/genesis_policy.js +5 -2
  127. package/dist/modules/order/grid.d.ts +4 -2
  128. package/dist/modules/order/grid.js +91 -35
  129. package/dist/modules/order/index.d.ts +1 -0
  130. package/dist/modules/order/logger.d.ts +1 -8
  131. package/dist/modules/order/logger.js +0 -9
  132. package/dist/modules/order/manager.d.ts +9 -13
  133. package/dist/modules/order/manager.js +33 -50
  134. package/dist/modules/order/utils/order.js +39 -35
  135. package/dist/modules/order/utils/system.d.ts +9 -29
  136. package/dist/modules/order/utils/system.js +17 -2
  137. package/dist/modules/order/utils/validate.js +2 -2
  138. package/dist/modules/order/utils/withPoolRef.d.ts +2 -1
  139. package/dist/modules/paths.js +32 -34
  140. package/dist/modules/runtime_settings.d.ts +2 -4
  141. package/dist/modules/settings_merge.d.ts +2 -2
  142. package/dist/modules/socket_json_client.d.ts +2 -1
  143. package/dist/modules/types.d.ts +42 -27
  144. package/dist/modules/utils/errors.js +1 -3
  145. package/dist/modules/version_notice.d.ts +11 -10
  146. package/dist/pm2.d.ts +0 -1
  147. package/dist/pm2.js +56 -35
  148. package/dist/scripts/analyze-git.js +2 -15
  149. package/dist/scripts/chart_command.js +2 -2
  150. package/dist/scripts/check_any.d.ts +4 -0
  151. package/dist/scripts/check_any.js +53 -21
  152. package/dist/scripts/diagnose-pool-history.js +1 -6
  153. package/dist/scripts/run-tests.js +0 -1
  154. package/dist/scripts/sync-version.js +0 -10
  155. package/docs/BITSHARES_ONBOARDING.md +8 -12
  156. package/docs/COPY_ON_WRITE_MASTER_PLAN.md +1 -1
  157. package/docs/DEXBOT_COMPARISON.md +6 -6
  158. package/docs/EVOLUTION.md +9 -8
  159. package/docs/FUND_MOVEMENT_AND_ACCOUNTING.md +1 -1
  160. package/docs/README.md +1 -1
  161. package/docs/WORKFLOW.md +1 -0
  162. package/docs/architecture.md +19 -10
  163. package/market_adapter/README.md +6 -4
  164. package/package.json +6 -9
  165. package/scripts/README.md +43 -38
  166. package/tests/README.md +25 -10
  167. package/dist/scripts/diagnose-kibana-candles.d.ts +0 -3
  168. package/dist/scripts/diagnose-kibana-candles.js +0 -82
  169. package/scripts/git-viewer.sh +0 -489
  170. package/scripts/postinstall.js +0 -16
package/CHANGELOG.md CHANGED
@@ -2,6 +2,36 @@
2
2
 
3
3
  All notable changes to this project will be documented in this file.
4
4
 
5
+ ## [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
6
+
7
+ ### 2026-10-10
8
+
9
+ - **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).
10
+
11
+ - **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.
12
+
13
+ - **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.
14
+
15
+ - **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.
16
+
17
+ - **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.
18
+
19
+ - **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.
20
+
21
+ - **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.
22
+
23
+ - **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`.
24
+
25
+ - **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.
26
+
27
+ - **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.
28
+
29
+ - **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).
30
+
31
+ - **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`.
32
+
33
+ - **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.
34
+
5
35
  ## [1.6.12] - 2026-10-08 - Type-Safety Ratchet, Shared ECC & Scrypt Correctness, Fresh-Placement Cancel Grace, Worker Drain & Partial Credit Renewal
6
36
 
7
37
  ### 2026-10-08
@@ -12,7 +42,9 @@ All notable changes to this project will be documented in this file.
12
42
 
13
43
  - **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
44
 
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.
45
+ - **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.
46
+
47
+ - **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
48
 
17
49
  - **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
50
 
@@ -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
  ```
@@ -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)).
@@ -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';
@@ -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
  '```',
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.13",
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.13",
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.13",
5
5
  "type": "module",
6
6
  "main": "index.js"
7
7
  }
@@ -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 = [];
@@ -1,20 +1,13 @@
1
1
  #!/usr/bin/env node
2
2
  'use strict';
3
- import fs from 'node:fs';
4
- import path from 'node:path';
5
- import { normalizePoolId } from '../../market_adapter/utils/chain.js';
6
- import { toIntervalLabel, slugPart } from '../../market_adapter/interval_utils.js';
7
- import { MARKET_ADAPTER } from '../../modules/constants.js';
8
- import * as kibanaSource from '../../market_adapter/inputs/kibana_source.js';
9
- import { PATHS } from '../../modules/paths.js';
10
- import { getStorage } from '../../modules/storage/index.js';
11
- const { ensureDir, writeJSON } = getStorage();
12
- import { getErrorMessage } from '../../modules/utils/errors.js';
13
3
  /**
14
- * Fetch LP pool candles from Kibana for AMA optimizer input.
4
+ * Fetch LP pool candles from Kibana for the AMA optimizer.
15
5
  *
16
- * Uses the same kibana_source as the market_adapter bootstrap, but saves
17
- * the full uncut dataset (no pruning) for optimizer use.
6
+ * Thin CLI over the central sequential/window fetch
7
+ * (`market_adapter/inputs/fetch_lp_data.ts` → `fetchCandlesSequentially`).
8
+ * It therefore shares the SAME month-shard cache as `dexbot tv`/`dexbot dw`:
9
+ * a run re-queries only the missing buckets and reuses everything on disk,
10
+ * then exports the whole-history base file as a convenience snapshot.
18
11
  *
19
12
  * Usage:
20
13
  * node dist/analysis/ama_fitting/fetch_lp_candles.js \
@@ -26,11 +19,16 @@ import { getErrorMessage } from '../../modules/utils/errors.js';
26
19
  * Defaults: --interval 1h --hours 26280 (3 years)
27
20
  * Output: market_adapter/data/lp/<assetA>_<assetB>/lp_pool_<poolShort>_<interval>.json
28
21
  */
29
- const DATA_DIR = PATHS.MARKET_ADAPTER.LP_DATA_DIR;
22
+ import path from 'node:path';
23
+ import { pathToFileURL } from 'node:url';
24
+ import { toIntervalLabel } from '../../market_adapter/interval_utils.js';
25
+ import { MARKET_ADAPTER } from '../../modules/constants.js';
26
+ import { getErrorMessage } from '../../modules/utils/errors.js';
27
+ import { writeJsonAtomic } from '../../market_adapter/utils/atomic_write.js';
28
+ import { loadLpSeriesFromBasePath } from '../../market_adapter/utils/data_discovery.js';
29
+ import { normalizePoolId } from '../../market_adapter/utils/chain.js';
30
+ import { fetchCandlesSequentially, outputPath, } from '../../market_adapter/inputs/fetch_lp_data.js';
30
31
  const HOURS_3Y = 3 * 365 * 24; // 26280
31
- function slugPairFolder(symbolA, symbolB) {
32
- return `${slugPart(symbolA)}_${slugPart(symbolB)}`;
33
- }
34
32
  function parseArgs() {
35
33
  const args = process.argv.slice(2);
36
34
  const out = {
@@ -101,6 +99,8 @@ function parseArgs() {
101
99
  function printHelp() {
102
100
  console.log('fetch_lp_candles.ts — fetch LP pool candles from Kibana for AMA optimizer');
103
101
  console.log('');
102
+ console.log('Uses the shared month-shard candle cache (same as dexbot tv / dw).');
103
+ console.log('');
104
104
  console.log('Usage:');
105
105
  console.log(' node dist/analysis/ama_fitting/fetch_lp_candles.js --pool 1.19.133 \\');
106
106
  console.log(' --assetA IOB.XRP --assetAId 1.3.3926 --assetAPrecision 4 \\');
@@ -155,56 +155,66 @@ async function main() {
155
155
  const poolId = normalizePoolId(args.pool);
156
156
  const lookback = Math.round(args.hours);
157
157
  const yearsApprox = (lookback / (365 * 24)).toFixed(1);
158
+ if (!poolId)
159
+ throw new Error(`Invalid --pool: ${args.pool}`);
158
160
  console.log(`Fetching LP candles from Kibana`);
159
161
  console.log(` Pool: ${poolId}`);
160
162
  console.log(` Pair: ${assetA.symbol} / ${assetB.symbol}`);
161
163
  console.log(` Interval: ${intervalLabel}`);
162
164
  console.log(` Lookback: ${lookback}h (~${yearsApprox} years)`);
163
165
  console.log('');
164
- const candles = await kibanaSource.getLpCandlesForPool(poolId, assetA, assetB, {
166
+ const defaultOut = outputPath(poolId, intervalSeconds, assetA, assetB);
167
+ const outPath = args.outFile
168
+ ? (path.isAbsolute(args.outFile) ? args.outFile : path.join(path.dirname(defaultOut), args.outFile))
169
+ : defaultOut;
170
+ const candles = await fetchCandlesSequentially(poolId, assetA, assetB, {
165
171
  intervalSeconds,
166
172
  lookbackHours: lookback,
167
173
  apiKey: null,
168
- timeout: 60000,
169
- });
174
+ chunkMonths: MARKET_ADAPTER.KIBANA_FETCH_CHUNK_MONTHS,
175
+ }, outPath);
170
176
  if (!Array.isArray(candles) || candles.length === 0) {
171
177
  throw new Error('Kibana returned no candles — check pool ID, asset IDs, and Kibana connectivity');
172
178
  }
173
- const firstTs = new Date(candles[0][0]).toISOString();
174
- const lastTs = new Date(candles[candles.length - 1][0]).toISOString();
175
- console.log(` Received: ${candles.length} candles (${firstTs} → ${lastTs})`);
179
+ // Whole-history export: month shards are the cache, this is the derived
180
+ // snapshot (same meta shape as fetch_lp_data's export). Deriving it from
181
+ // the assembled shards means a narrow re-run can never shrink the file.
182
+ const assembled = loadLpSeriesFromBasePath(outPath);
183
+ const exportCandles = (assembled && assembled.candles.length > 0 ? assembled.candles : candles);
184
+ const firstTs = new Date(exportCandles[0][0]).toISOString();
185
+ const lastTs = new Date(exportCandles[exportCandles.length - 1][0]).toISOString();
186
+ console.log(` Received: ${exportCandles.length} candles (${firstTs} → ${lastTs})`);
176
187
  const payload = {
177
188
  meta: {
178
189
  fetchedAt: new Date().toISOString(),
179
- source: 'kibana',
190
+ source: `https://kibana.bitshares.dev (bitshares-*, op_type 63, pool ${poolId})`,
180
191
  pool: poolId,
181
192
  assetA,
182
193
  assetB,
194
+ pair: {
195
+ symbols: `${assetA.symbol}/${assetB.symbol}`,
196
+ ids: `${assetA.id}/${assetB.id}`,
197
+ keyBySymbols: `${assetA.symbol}|${assetB.symbol}`,
198
+ keyByIds: `${assetA.id}|${assetB.id}`,
199
+ },
183
200
  intervalSeconds,
184
201
  lookbackHours: lookback,
185
- candleCount: candles.length,
202
+ candleCount: exportCandles.length,
203
+ priceUnit: `${assetB.symbol} per ${assetA.symbol}`,
186
204
  format: '[timestamp_ms, open, high, low, close, volume_A]',
187
205
  },
188
- candles,
206
+ candles: exportCandles,
189
207
  };
190
- const poolShort = (poolId || '').replace('1.19.', '');
191
- const pairFolder = slugPairFolder(assetA.symbol, assetB.symbol);
192
- const defaultName = `lp_pool_${poolShort}_${intervalLabel}.json`;
193
- const outName = args.outFile || defaultName;
194
- const outPath = args.outFile && path.isAbsolute(args.outFile)
195
- ? args.outFile
196
- : path.join(DATA_DIR, pairFolder, outName);
197
- const outDir = path.dirname(outPath);
198
- if (!fs.existsSync(outDir))
199
- ensureDir(outDir);
200
- writeJSON(outPath, payload);
208
+ writeJsonAtomic(outPath, payload);
201
209
  console.log(` Saved: ${path.relative(process.cwd(), outPath)}`);
202
210
  console.log('');
203
211
  console.log('Run optimizer:');
204
212
  console.log(` npm run build && node dist/analysis/ama_fitting/optimizer_high_resolution.js --data ${path.relative(process.cwd(), outPath)}`);
205
213
  }
206
- main().catch((err) => {
207
- console.error('Error:', getErrorMessage(err));
208
- process.exit(1);
209
- });
214
+ if (process.argv[1] && import.meta.url === pathToFileURL(process.argv[1]).href) {
215
+ main().catch((err) => {
216
+ console.error('Error:', getErrorMessage(err));
217
+ process.exit(1);
218
+ });
219
+ }
210
220
  //# sourceMappingURL=fetch_lp_candles.js.map
@@ -13,29 +13,6 @@ declare function parseArgs(argv: string[]): {
13
13
  quiet: boolean;
14
14
  help: boolean;
15
15
  };
16
- interface GenerateChartOptions {
17
- logger?: {
18
- log: (...args: unknown[]) => void;
19
- };
20
- dataFile?: string | null;
21
- outFile?: string | null;
22
- strategies?: typeof DEFAULT_STRATEGIES;
23
- [key: string]: unknown;
24
- }
25
- declare function generateChart(options?: GenerateChartOptions): {
26
- dataFile: string;
27
- outFile: string;
28
- amaResults: (Record<string, unknown> & {
29
- values: number[];
30
- })[];
31
- meta: {
32
- assetA: {};
33
- assetB: {};
34
- intervalSeconds: {};
35
- fetchedAt: {};
36
- };
37
- candleArrays: number[][];
38
- };
39
16
  declare function run(argv?: string[]): void;
40
- export { DEFAULT_STRATEGIES, generateChart, parseArgs, run, showHelp };
17
+ export { DEFAULT_STRATEGIES, parseArgs, run, showHelp };
41
18
  //# sourceMappingURL=generate_unified_comparison_chart.d.ts.map
@@ -6,7 +6,7 @@ import { pathToFileURL } from 'node:url';
6
6
  import { calculateAMA } from '../../market_adapter/core/strategies/ama.js';
7
7
  import { generateHTML } from '../../market_adapter/lp_chart_core.js';
8
8
  import { calculateMetrics } from '../../market_adapter/lp_chart_runner.js';
9
- import { findLatestLpData } from '../../market_adapter/utils/data_discovery.js';
9
+ import { loadLatestLpSeries, loadLpSeriesFromPath } from '../../market_adapter/utils/data_discovery.js';
10
10
  import { toIntervalLabel } from '../../market_adapter/interval_utils.js';
11
11
  import { loadCandleFile, normalizeCandle } from '../math_utils.js';
12
12
  import { MARKET_ADAPTER } from '../../modules/constants.js';
@@ -46,14 +46,7 @@ function buildDefaultStrategies() {
46
46
  }
47
47
  const DEFAULT_STRATEGIES = buildDefaultStrategies();
48
48
  // ── Data loading (canonical implementations, no local copies) ────────────────
49
- function loadCandles(dataFile) {
50
- const resolved = path.resolve(dataFile);
51
- if (!fs.existsSync(resolved))
52
- throw new Error(`File not found: ${resolved}`);
53
- const { candles, meta } = loadCandleFile(resolved);
54
- if (!Array.isArray(candles) || candles.length === 0) {
55
- throw new Error('No candles found in file');
56
- }
49
+ function normalizeCandleRows(candles) {
57
50
  // normalizeCandle is the canonical accessor transform (market_adapter/
58
51
  // candle_utils.ts via math_utils re-export); it returns seconds-based time.
59
52
  const normalized = candles.map((c, i) => {
@@ -71,7 +64,21 @@ function loadCandles(dataFile) {
71
64
  volume: c.volume,
72
65
  }));
73
66
  const candleArrays = normalized.map(c => [c.time * 1000, c.open, c.high, c.low, c.close, c.volume]);
74
- return { dataFile: resolved, meta, candleObjects, candleArrays };
67
+ return { candleObjects, candleArrays };
68
+ }
69
+ function loadCandles(dataFile) {
70
+ const resolved = path.resolve(dataFile);
71
+ if (!fs.existsSync(resolved))
72
+ throw new Error(`File not found: ${resolved}`);
73
+ // Shard-aware: `--data <shard>` yields the whole family, not one month.
74
+ const series = loadLpSeriesFromPath(resolved);
75
+ if (!series || series.candles.length === 0) {
76
+ throw new Error('No candles found in file');
77
+ }
78
+ // Keep loadCandleFile's meta fallback for non-LP `{data:[...]}` shapes that
79
+ // carry fields at the top level rather than under `meta`.
80
+ const meta = series.meta ?? loadCandleFile(resolved).meta;
81
+ return { dataFile: series.path, meta, ...normalizeCandleRows(series.candles) };
75
82
  }
76
83
  function defaultChartPath(meta) {
77
84
  const intervalSeconds = Number(meta?.intervalSeconds);
@@ -103,7 +110,7 @@ Options:
103
110
  Notes:
104
111
  - If --data is omitted, the newest lp_pool_*.json under market_adapter/data/lp is used.
105
112
  - Accepts several candle JSON shapes: flat [[ts,o,h,l,c,v],...], {candles: [...]}, or {data: [...]}.
106
- - Separate from Kibana fetching — use fetch_lp_candles.ts to pull data first.
113
+ - Separate from Kibana fetching — run 'dexbot tv' (or fetch_lp_candles.ts) to pull data first.
107
114
  `);
108
115
  }
109
116
  // ── Main ───────────────────────────────────────────────────────────────────────
@@ -133,16 +140,27 @@ function parseArgs(argv) {
133
140
  }
134
141
  function generateChart(options = {}) {
135
142
  const logger = options.logger ?? console;
136
- const dataFile = options.dataFile
137
- ? path.resolve(options.dataFile)
138
- : findLatestLpData();
139
- if (!dataFile) {
140
- throw new Error(`No LP data file found. Use --data <path> or run fetch_lp_candles.ts first.`);
143
+ // Explicit --data wins; otherwise auto-discover and, when month shards are
144
+ // the newest source, assemble the complete series before charting.
145
+ let dataFile;
146
+ let meta;
147
+ let candleObjects;
148
+ let candleArrays;
149
+ if (options.dataFile) {
150
+ ({ dataFile, meta, candleObjects, candleArrays } = loadCandles(options.dataFile));
151
+ }
152
+ else {
153
+ const series = loadLatestLpSeries();
154
+ if (!series || series.candles.length === 0) {
155
+ throw new Error(`No LP data found. Use --data <path> or run \`dexbot tv\` first.`);
156
+ }
157
+ dataFile = series.path;
158
+ meta = series.meta;
159
+ ({ candleObjects, candleArrays } = normalizeCandleRows(series.candles));
141
160
  }
142
161
  const strategies = Array.isArray(options.strategies) && options.strategies.length
143
162
  ? options.strategies
144
163
  : [...DEFAULT_STRATEGIES];
145
- const { meta, candleObjects, candleArrays } = loadCandles(dataFile);
146
164
  const closes = candleObjects.map(c => c.close);
147
165
  const enrichedMeta = {
148
166
  ...(meta || {}),
@@ -202,5 +220,5 @@ function run(argv = process.argv.slice(2)) {
202
220
  if (process.argv[1] && import.meta.url === pathToFileURL(process.argv[1]).href) {
203
221
  run();
204
222
  }
205
- export { DEFAULT_STRATEGIES, generateChart, parseArgs, run, showHelp };
223
+ export { DEFAULT_STRATEGIES, parseArgs, run, showHelp };
206
224
  //# sourceMappingURL=generate_unified_comparison_chart.js.map