dexbot 1.6.8 → 1.6.10

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 (70) hide show
  1. package/CHANGELOG.md +42 -0
  2. package/analysis/README.md +1 -1
  3. package/analysis/tradingview/README.md +14 -9
  4. package/claw/modules/chain_queries.ts +9 -4
  5. package/claw/modules/claw_bridge.ts +9 -9
  6. package/claw/package.json +1 -1
  7. package/claw/runtimes/openclaw-plugin/openclaw.plugin.json +1 -1
  8. package/claw/runtimes/openclaw-plugin/package.json +1 -1
  9. package/dist/analysis/ama_fitting/optimizer_high_resolution.js +2 -1
  10. package/dist/analysis/bot_fitting/backtest_ama_sweep.js +2 -2
  11. package/dist/analysis/bot_fitting/backtest_bot_fitting.js +4 -4
  12. package/dist/analysis/bot_key_utils.js +14 -4
  13. package/dist/analysis/tradingview/analyze_tradingview.d.ts +0 -3
  14. package/dist/analysis/tradingview/analyze_tradingview.js +3 -14
  15. package/dist/analysis/tradingview/grid_reset_sim.d.ts +11 -1
  16. package/dist/analysis/tradingview/grid_reset_sim.js +22 -9
  17. package/dist/analysis/tradingview/tradingview_uplot_chart_generator.js +178 -32
  18. package/dist/analysis/trend_detection/dynamic_weight_chart_generator.js +8 -3
  19. package/dist/dexbot.js +57 -29
  20. package/dist/market_adapter/core/market_adapter_service.d.ts +81 -1
  21. package/dist/market_adapter/core/market_adapter_service.js +225 -18
  22. package/dist/market_adapter/core/signals/hurst_analyzer.d.ts +10 -1
  23. package/dist/market_adapter/core/signals/hurst_analyzer.js +40 -18
  24. package/dist/market_adapter/core/signals/permutation_entropy_analyzer.d.ts +26 -2
  25. package/dist/market_adapter/core/signals/permutation_entropy_analyzer.js +132 -29
  26. package/dist/market_adapter/core/strategies/ama_slope_model.d.ts +2 -2
  27. package/dist/market_adapter/core/strategies/ama_slope_model.js +12 -10
  28. package/dist/market_adapter/core/strategies/dynamic_weight_series.d.ts +41 -14
  29. package/dist/market_adapter/core/strategies/dynamic_weight_series.js +138 -30
  30. package/dist/market_adapter/core/strategies/regime_gate.d.ts +61 -3
  31. package/dist/market_adapter/core/strategies/regime_gate.js +207 -7
  32. package/dist/market_adapter/interval_utils.d.ts +18 -1
  33. package/dist/market_adapter/interval_utils.js +31 -1
  34. package/dist/market_adapter/lp_chart_strategy_loader.js +2 -1
  35. package/dist/market_adapter/market_adapter.d.ts +151 -2
  36. package/dist/market_adapter/market_adapter.js +378 -62
  37. package/dist/market_adapter/test_helpers.d.ts +2 -2
  38. package/dist/market_adapter/test_helpers.js +2 -2
  39. package/dist/market_adapter/utils/chain.d.ts +1 -1
  40. package/dist/market_adapter/utils/chain.js +8 -6
  41. package/dist/market_adapter/utils/file_json_cache.d.ts +29 -0
  42. package/dist/market_adapter/utils/file_json_cache.js +106 -0
  43. package/dist/modules/account_bots.js +5 -4
  44. package/dist/modules/bitshares-native/resolvers.js +5 -0
  45. package/dist/modules/bot_settings.js +13 -1
  46. package/dist/modules/chain_orders.js +2 -1
  47. package/dist/modules/config.d.ts +6 -0
  48. package/dist/modules/config.js +1 -0
  49. package/dist/modules/constants.d.ts +11 -1
  50. package/dist/modules/constants.js +64 -15
  51. package/dist/modules/credential_policy.js +4 -1
  52. package/dist/modules/credit_runtime.js +5 -1
  53. package/dist/modules/order/grid.js +95 -25
  54. package/dist/modules/order/utils/system.js +11 -1
  55. package/dist/modules/utils/asset_symbols.d.ts +59 -0
  56. package/dist/modules/utils/asset_symbols.js +128 -0
  57. package/dist/modules/version_notice.d.ts +166 -20
  58. package/dist/modules/version_notice.js +401 -56
  59. package/dist/pm2.js +9 -2
  60. package/dist/scripts/analyze-credit.js +10 -7
  61. package/dist/scripts/chart_command.js +12 -4
  62. package/dist/scripts/verify-browser-bundle.js +8 -0
  63. package/dist/unlock.js +7 -7
  64. package/docs/DEXBOT_COMPARISON.md +3 -3
  65. package/docs/EVOLUTION.md +14 -12
  66. package/docs/FUND_MOVEMENT_AND_ACCOUNTING.md +1 -1
  67. package/docs/GRID_RECALCULATION.md +28 -5
  68. package/docs/README.md +2 -2
  69. package/market_adapter/README.md +30 -2
  70. package/package.json +1 -1
package/CHANGELOG.md CHANGED
@@ -2,8 +2,50 @@
2
2
 
3
3
  All notable changes to this project will be documented in this file.
4
4
 
5
+ ## [1.6.10] - 2026-10-01 - Huber-Robust AMA Slope, Asset-Pair Canonicalization, TradingView Indicator Ownership & View Preservation
6
+
7
+ ### 2026-10-01
8
+
9
+ - **Feat(market-adapter)**: derive the AMA slope as a Huber-robust regression — the slope was a two-point endpoint estimate, `(ama[i] - ama[i-lookback]) / ama[i-lookback] / lookback`, so the window-edge bar carried full weight and one anomalous hour moved the reading as much as a tenth of the window; averaging the per-bar returns cannot help because their telescoping sum is algebraically identical to the endpoint difference. It is now a Huber-robust linear regression of `ln(AMA)` over the same window (uniform weights, no kernel), reported as log-return per bar × 100 — measured at a 20-bar window, a 1/3/5/10% single-bar AMA impulse moves the old endpoint reading by 0.050/0.150/0.250/0.499 %/bar (7×–70× the 0.0072 %/bar reset gate) while the bounded-influence fit barely moves, its second-difference energy ~25× lower than an order-statistic median's because its influence function is continuous rather than a discrete order statistic. Parameters live once in `modules/constants.ts` (`MARKET_ADAPTER.DYNAMIC_WEIGHT_AMA_HUBER`: C 1.345, 5 IRLS passes, scale floor 1e-6, zero epsilon 1e-9, aliased `AMA_SLOPE_HUBER`) and the definition once in `dynamic_weight_series.ts` (`computeHuberWindowSlopePct`), read by the dynamic-weight series, the AMA slope model, both clip paths, the grid-reset replay, the backtests and the browser charts (the generated HTML injects the same constant, so page and runtime cannot drift). Two fixes fall out of the shared definition: the estimator rejects non-positive values anywhere in the window (`Number(null) === 0` made a pre-warmup hole read as a zero price and produce a bogus −100% return), and `simulateGridResetSeries` keeps its optional `cfg.slopeEstimator` seam defaulting to the canonical estimator, so the plotted tilt and the replayed Δs trigger measure one quantity by construction. Operational note: `slopePct` is a different quantity from any pre-Huber reading, so the first post-deploy cycle compares Huber against the persisted baseline; magnitudes agree closely (delta below the reset gate on 98% of bars, p50 0.00043, p90 0.00277), i.e. roughly one whitelisted bot in fifty costs one extra recenter, once, and no version marker suppresses it. Tests were converted, not weakened (geometric-ramp fixtures in place of the 0 %/bar order-statistic fixtures, a browser-execution guard asserting the generated estimator matches the Node module bar for bar). Validation: `tsc` src+tests clean, `node dist/scripts/run-tests.js` exit 0, `verify:browser-bundle` 40/40 (`market_adapter/core/strategies/ama_slope_model.ts`, `market_adapter/core/strategies/dynamic_weight_series.ts`, `modules/constants.ts`, `analysis/tradingview/grid_reset_sim.ts`, `docs/GRID_RECALCULATION.md`, `tests/test_ama_slope_model.ts`, `tests/test_backtest_bot_fitting_logic.ts`).
10
+
11
+ - **Feat(asset-symbols)**: centralize uppercase canonicalization of asset pairs — BitShares stores symbols UPPERCASE but a node answers a lowercase lookup without error, so a mis-cased `assetA`/`assetB` is a silent-wrong-answer bug rather than a loud one: the lowercase spelling travels on into the resolved symbol, cache keys, Kibana query terms, chart titles and the exported HTML. Two real defects came out of this: `dexbot tv`/`dw` forwarded the raw CLI string as the asset symbol, and the market-profile lookup in `analysis/bot_key_utils` compared `assetA`/`assetB` with a strict `===`, so a case-only difference between `bots.json` and `market_profiles.json` silently dropped the whole AMA/grid config. New `modules/utils/asset_symbols.ts` is the single definition of the rule (`normalizeAssetSymbol`/`normalizeAssetRef`, `isAssetObjectId`, `isSameAssetSymbol`, `splitPairTarget`, `canonicalizeBotAssetSymbols`); object ids (`1.3.x`) pass through verbatim so ref-routing callers keep their `get_assets` vs `lookup_asset_symbols` branch and only real symbols are rewritten. Applied at every boundary that accepts a pair from a human or hands a symbol to the chain (chain/order/system resolvers, the `bot_settings.ts` and `bot_key_utils.ts` read funnels sharing `canonicalizeBotAssetSymbols`, credit/credential cache keys, `dexbot.ts` collateral, `scripts/{analyze-credit,chart_command}.ts`, `claw/modules/{claw_bridge,chain_queries}.ts`), and de-duplicates the ad-hoc uppercase copies in `optimizer_high_resolution.ts`. Behavioral impact: a lowercase pair is normalized end to end, so `assetA === 'BTS'` checks, `getBtsSide` and market-profile matching behave identically for hand-edited lowercase `bots.json`; `botKey` is unaffected (`createBotKey` already ran the case-insensitive `sanitizeKey`) and no config file is rewritten. Coverage: `tests/test_asset_symbol_normalization.ts` (uppercase-on-the-wire at every boundary, id pass-through, non-mutation, `debtPolicy` handling, claw pair contract); `npm test` 300 pass / 0 fail, `verify:browser-bundle` 39 pass, `tsc --noEmit` clean for root and claw.
12
+
13
+ - **Chore(market-adapter)**: raise the AMA-slope lookback default from 9 to 20 bars — measured over the real 1h pools, 20 vs 9 cuts the slope's bar-to-bar wobble ~34% and slope-driven grid resets ~19% at an unchanged band-tilt magnitude; the cost is freshness, with the window centre moving from ~4.5 to ~10 bars back. The whole 5–32 range was measured rather than guessed: noise and resets fall monotonically with the window and lag grows linearly, with no knee, so 20 is a deliberate point on a straight dial. Scope note: the constant is not only the grid-reset trigger window, it is also the default for the live dynamic-weight / grid-range-scaling slope (`ama_slope_model.ts`), so the directional weight shift follows the same longer average — a live trading behaviour change, not a reset-only change. Operational impact: `readyBars = erPeriod + lookbackBars`, so post-restart convergence is ~11 bars longer, and persisted slope snapshots are re-normalized through `normalizePersistedAmaSlopeDiagnostics` on the first cycle after restart — watch that first restart for one off-cycle Δs reset. The gitignored deployment override in `profiles/general.settings.json` was set to 20 as well, so the code default and the running config agree (`modules/constants.ts`).
14
+
15
+ - **Fix(tradingview)**: share one AMA-slope lookback across the band and the reset replay — the chart resolved the slope window twice: `computeRangeBand` read the embedded constant (`payload.rangeSlope.lookbackBars`) while `buildGridResetSeries` passed the bot-configured `gridSimCfg.lookbackBars` (`grid_reset_config` had already resolved it from the bot's own `amaSlope.lookbackBars`), so a bot with its own lookback got it in the replayed Δs trigger but not in the plotted range band, silently misrepresenting the bot. Both now route through one `resolveSlopeLookbackBars()` that prefers the resolved grid-sim value and falls back to the embedded constant for pool/pair charts, which carry no grid-sim data. No UI change: the untilted band stays span-symmetric, the toolbar is unchanged, and the reset panel reports exactly what it did before. Chart-only, no runtime or bot behaviour change. Verified: `typecheck` + `build:tests`, `tests/test_tradingview_chart_storage_key.ts` (16 checks), and a local Firefox check that a bot-configured 32h lookback paints the independently computed 32h geometry rather than the constant's (`analysis/tradingview/tradingview_uplot_chart_generator.ts`, `analysis/tradingview/README.md`, `tests/test_tradingview_chart_storage_key.ts`).
16
+
17
+ - **Fix(tradingview)**: keep the chart view when toggling Range / Scale — the `Scale` toggle cleared `manualYRange` and both toggles rerendered without keeping the X range, so the rerender's X restore fired the rAF price refit, which follows the band envelope (`visiblePriceRange` returns the band when Range + Scale + AMA are on); the price axis jumped to the band fit on set and back to the candle fit on unset though the data and the visible window were unchanged. New `captureView()`/`preserveView(fn)` snapshot X and Y, run the toggle, then re-assert X and restore Y through a one-shot `pendingViewY` applied inside the refit's own rAF after the autofit, so the refit cannot win the frame; `Range` on/off, `Scale` on/off and the grid-span slider are wrapped in `preserveView(...)`. It deliberately does not set `manualYRange`, so a later X pan still autofits and a user price lock is respected; the band axis-fit lands on the next autofit (reload, timeframe switch, X pan) or a double-click of the price axis. Verified (Playwright, X/Y scale + axis-pixel diffs): both axes stay byte-identical across every toggle and a span-slider drag, and a manual Y lock still blocks the autofit. Risk: low — view behaviour only, no band/AMA/order-math change (`analysis/tradingview/tradingview_uplot_chart_generator.ts`, `analysis/tradingview/README.md`).
18
+
19
+ - **Feat(tradingview)**: auto opt-in for Range/Scale and widen the span slider to 1.3x-2.1x — the band min/max are built from the live AMA price and Scale additionally sizes it by AMA slope, but the toggles were independent, so Scale-on with Range/AMA off produced a silently dead toggle (the draw hook and the axis fit both bail out on `!currentAmaEnabled`). New `autoOptInAma()` pushes the dependency one way (Range → AMA, Scale → Range + AMA; switching an indicator off never disables its dependencies) and returns whether AMA actually flipped, so the caller takes the AMA-toggle render path (`rerender(false)`, series added) instead of the keep-view one; switching AMA off takes Range and Scale down with it, and the same chain is re-applied when hydrating localStorage state, so a chart saved with Scale on and AMA off cannot silently come back with a working AMA. Behavior note: a chart generated with `--range` or `--range-scale` plus `--no-ama` now renders the AMA line (that combination was already a dead band). The span slider range moves 1.2x-2.0x → 1.3x-2.1x (default 1.55x unchanged); the bounds, previously hardcoded in six places and already drifted once, are now `RANGE_SPAN_MIN/MAX/DEFAULT` at module scope interpolated into the generated page, so slider, tooltip and every clamp share one source of truth (the 0.05 step still lands exactly on 2.10). Verified: `tsc --noEmit`, the generated page's inline script through `node --check`, a slider/clamp spot-check in a regenerated chart (`min="1.3" max="2.1"`), `tests/test_tradingview_chart_storage_key.ts` (14 checks) (`analysis/tradingview/tradingview_uplot_chart_generator.ts`, `analysis/tradingview/README.md`).
20
+
21
+ - **Refactor(tradingview)**: drop the Range/Scale/AMA on-off CLI flags — `--range`, `--no-range`, `--range-scale` and `--no-ama` only set indicator state that the in-chart toolbar owns and persists per chart (localStorage), so a chart regenerated with a different flag combination silently overrode the user's choice; worse, they could disagree (`--no-ama` with the range highlight on produced a dead band, since the band min/max are built from the AMA price). The four flags are gone from the config, the defaults, the parser and the payload in `analyze_tradingview.ts` — and no longer warn, since indicator state has exactly one owner. AMA stays auto-enabled for `gridPrice` `ama`/`ama1-4` bots as before; only the manual override is gone. `rangeEnabled`/`rangeScaleEnabled` are pinned off at generation time (already their effective default) while the payload keys stay so state hydration keeps its shape. `--range-span` and `--no-sma`/`--no-vwap` are untouched: the span has a real generation-time default derived from the bot grid ratio, and the other two are plain switches for indicators with no dependencies. Docs: `analysis/tradingview/README.md` + `analysis/README.md`; historical CHANGELOG entries keep the old flags, since they record what those releases shipped. Verified: `npx tsc --noEmit`, a regenerated chart ignores the removed flags and renders the range/ama toggles unchecked with payload `rangeEnabled`/`rangeScaleEnabled` false, the inline script through `node --check`, `tests/test_tradingview_chart_storage_key.ts` (14 checks) (`analysis/tradingview/analyze_tradingview.ts`, `analysis/tradingview/tradingview_uplot_chart_generator.ts`).
22
+
23
+ ## [1.6.9] - 2026-09-30 - Market-Adapter Cycle CPU & Off-Hour Idle, Grid Spread-Tightening Correction
24
+
25
+ ### 2026-09-29
26
+
27
+ - **Perf(market-adapter)**: cut hourly cycle CPU via regime memo, incremental analyzers and a single AMA — the hourly cycle re-created both signal analyzers and replayed the whole candle history per bot per cycle (~99.8% identical numbers), re-ran `calculateAMA` four extra times per bot for an `AMA1..AMA4` preset sweep that only fed a log line, and re-parsed ~250 KiB of candle JSON per bot per cycle that the process had just serialized itself. Measured on the production shape (capped sliding window): regime gate ~3.7 ms cold → 0.05–0.24 ms resumed (median 0.088 ms), cycle CPU ~155 ms → ~103 ms. The cross-cycle regime memo is keyed by `<botKey>:<intervalSeconds>` and resumes only when the incoming window ADVANCES the cached one (k leading bars dropped, m appended) with a leading-drop tolerance for the capped sliding window (a strict prefix check missed every steady-state cycle); exactness rests on the analyzers being rolling — resume requires the shared region to cover `bufferBars` (read from the analyzer instances, fails closed), so any verified alignment is exact by construction, and ambiguous/related-window mismatches, parameter changes and history rewrites all fall back to a cold recompute. Permutation entropy now keeps an incremental count map with factorial-number-system integer pattern keys (`update()` allocates nothing, O(1) per bar); Hurst uses preallocated rolling buffers and `computeRS` takes a `[from, to)` range instead of slicing ~30 arrays per bar. `calcAmaComparison` becomes `buildAmaRecord`, so the cycle reports the ONE AMA the bot trades on (resolved preset name + the already-computed value) instead of a 4-preset sweep; the persisted `state.bots[key].amaComparison` field keeps its key but holds a single entry (was four) — its only repo reader, the cycle log formatter, tolerates both shapes, and the log label changes `AMA compare:` → `AMA active:`. Config: `market_adapter` no longer honours `ama.enabled`; `gridPrice` is the only switch that makes a bot AMA-driven (the resolver previously disagreed with itself depending on whether a market profile matched, so a bot with `ama.enabled: false` kept trading while its published center froze) — no shipped bot sets the flag, and `docs/GRID_RECALCULATION.md` documents the single-switch rule plus the profile/keyword/defaultAmaKey/bot-block precedence. A write-through candle-JSON read cache (`market_adapter/utils/file_json_cache.ts`) is mtime/size-validated, consumed on read, and fails closed to the loader whenever the file cannot be `stat`ed. Coverage: a new entropy-equivalence suite (bar-by-bar equivalence vs verbatim pre-optimization reference algorithms, incl. sliding-window, alignment and ambiguity cases, all shown non-vacuous by defect re-injection), a file-JSON-cache suite, and AMA layering/precedence tests. Risk: the `amaComparison` shape change from four entries to one is verified to have no other repo consumer. Validation: 302/302 tests, `tsc` src+tests clean, browser bundle 39 passed (`market_adapter/core/strategies/regime_gate.ts`, `market_adapter/core/signals/permutation_entropy_analyzer.ts`, `market_adapter/core/signals/hurst_analyzer.ts`, `market_adapter/market_adapter.ts`, `market_adapter/core/market_adapter_service.ts`, `market_adapter/utils/file_json_cache.ts`, `modules/constants.ts`, `docs/GRID_RECALCULATION.md`, `tests/test_market_adapter_entropy_equivalence.ts`, `tests/test_market_adapter_file_json_cache.ts`, `tests/test_market_adapter_logic.ts`, `tests/test_market_adapter_service.ts`).
28
+
29
+ - **Perf(market-adapter)**: skip off-hour work and sleep to the candle boundary — the adapter only has work once per closed candle, but a respawn ran a full cycle immediately and an extra cycle could re-fetch, re-parse and re-serialize the same ~250 KiB candle file for zero new information. A per-bot closed-candle gate now runs before the native overlap fetch, the Kibana stale-tail check and the re-serialize: when the persisted `lastClosedCandleTs` already equals the newest closed bucket and the candle file covers that bucket (source match, no unresolved gaps, AMA warmup target met), the cycle records `lastCycleSource=off-hour-skip` and returns. One-shot entry points (`--once`, `runOnceForAma` backing `ama_signal_runner`) are exempt so they always emit a computed AMA. Daemon startup now decides before connecting whether every active AMA bot is caught up, and if so sleeps to the same poll boundary the loop uses, otherwise runs a catch-up cycle; the verdict is per bot (never max-aggregated across bots), reports every veto reason with the offending bot keys, and treats a known warmup target with an unknown candle count as outstanding. Refactor with no behavior change: the candle-grid arithmetic is centralized as `bucketStartMs`/`latestClosedBucketStartMs` in `interval_utils.ts` (shared by `sleepUntilAlignedBoundary`, `selectClosedCandles` and the startup sleep), `isCandleSourceMismatch` is shared between the off-hour gate and the full-path cache reset, and `evaluateStateRepairVeto` is shared as the state-side mirror of `candleFileCoversClosedBucket`. The socket stays open only for a working cycle; between cycles the process holds just an unref'd lock heartbeat, and the startup wait is always shorter than one poll period so no candle is ever skipped. An off-hour-skip state record is a last-known snapshot: data fields keep the last full cycle's values, only `lastCycleSource`/`lastCycleAt`/`pendingClosedCandle`/`lastTriggerSuppressedReason` are refreshed. (`market_adapter/market_adapter.ts`, `market_adapter/core/market_adapter_service.ts`, `market_adapter/interval_utils.ts`, `market_adapter/test_helpers.ts`, `market_adapter/README.md`, `tests/test_market_adapter_service.ts`).
30
+
31
+ - **Fix(grid)**: make spread correction tighten the spread instead of walking to the rail edge — spread correction chose candidates via a two-branch comparator (`windowFirst` on a live rail, `edgeFirst` otherwise) written as exact opposites, so on a SELL rail with a live window the branch sorted descending and correction picked the grid ceiling (BUY mirrored it at the rail floor). Neither placement moves bestBuy/bestSell, so the measured spread was unchanged and the next resync cancelled the orders as surplus. Both branches are replaced with one market-nearest comparator, and a spread-tightening guard anchors the placement to the live book: a SELL candidate must sit below the lowest live sell and a BUY above the highest live buy, using the same on-chain order set `calculateCurrentSpread` measures from (an empty rail has no anchor and stays open). The guard is the fix — the orphan pool is rail-wide, so market-nearest alone still resolves to the first empty slot past the live window; with the guard that pool empties, the promotion gate opens and the gap band is asked. Gap-band promotion candidates are now placed ahead of the rail pools, and a promotion that yields nothing names its binding constraint (stranding cap, spread reserve, no contiguous run) instead of skipping silently. Coverage: `tests/test_spread_correction_market_nearest.ts` (6 cases; 5 fail against pre-fix code, 1 passes both ways by design) (`modules/order/grid.ts`, `tests/test_spread_correction_market_nearest.ts`).
32
+
33
+ - **Docs(agents)**: require an explicit user request before any version bump — an agent that treats "the work is done" as "ship a release" will bump `package.json`, retag and push on its own initiative, and worse will end every task by asking whether to bump; the ask is the failure mode, turning a finished change into a decision the operator has to make twice and training a reflex that fires whether or not a release is warranted. The rule is one line: never bump, never propose, never ask; the user alone decides. The existing three-step procedure stays, scoped to a turn where the bump was explicitly requested, and that request is also the authorization for the commits/tags it needs so a real release is not gated twice. Documentation only, no runtime change (`AGENTS.md`).
34
+
35
+ ### Version-notice hardening
36
+
37
+ The `fix(version-notice)` work committed after the 1.6.8 tag (real verdict from every entry point, staged `dexbot stat` status, npm-then-GitHub probe) is documented under [1.6.8]'s `2026-09-29` section above; no additional code change ships in 1.6.9.
38
+
5
39
  ## [1.6.8] - 2026-09-28 - Correction-Drain Bounds, PM2 Log Capture, Version Notice, Genesis Refusal & Legacy Matcher Removal, TV Grid-Reset Replay & Packaging Trim
6
40
 
41
+ ### 2026-09-29
42
+
43
+ - **Fix(version-notice)**: one version check on every entry point, and never a silent one — the audit found the check was centralized but its *rendering* was not: `dexbot stat` fell back to a bare `DEXBot2 vX.Y.Z` header when the notice was switched off (`DEXBOT_SKIP_VERSION_NOTICE=1` / `UPDATER.NOTICE_ENABLED=false`) while `dexbot pm2` and `unlock` printed nothing at all, so on a node with the notice off the operator learned their build from one command and not the others; and `pm2.ts` exited 1 on a credential-daemon failure without awaiting the probe it had already started, discarding the answer it had paid for. The fallback is now the module's decision, not each entry point's: `printVersionStatusOrHeader` / `flushVersionStatusOrHeader` render the status line when there is one and the bare header when there is not, and `printVersionStatusWhenReady` (the non-awaited isolated-foreground path) uses the same contract, so `stat`, `pm2`, `start`, `restart`, `stop` and `reload` cannot disagree. `printVersionStatus(null)` stays a no-op for callers that only want the line. The `pm2` failure path now flushes before exiting. `maybePrintVersionStatus` (zero callers since `stat` went staged) is REMOVED rather than left as a second entry path, and the dead `intervalMs`-ignored option now actually drives the success window. Behavioral impact: with the notice disabled, `dexbot pm2`/`start`/`restart` now name the running build where they previously printed nothing; no wording, colour or network behaviour changes when the notice is on (`modules/version_notice.ts`, `dexbot.ts`, `pm2.ts`, `unlock.ts`, `tests/test_version_notice.ts`).
44
+
45
+ - **Feat(version-notice)**: stage the version verdict around the `dexbot stat` report, and say "no current version information" when the answer never arrives — a status command that shows a process table is the wrong place to block on the network, but printing the verdict inline under a short cap made a reachable registry read as "unknown", while deferring it unconditionally left a MISSING line that an operator can easily read as "you are up to date". `startStagedVersionStatus` now owns the escalation as two promises: a 1s grace (`UPDATER.NOTICE_STAGE_GRACE_MS`) at the top of the report, which a valid cache or a quick answer satisfies without the command ever noticing the wait; and a `settled` promise for the end, which gives the still-in-flight probe 1s more, then ASKS AGAIN with a forced, full-budget probe (`UPDATER.NOTICE_STATUS_TIMEOUT_MS`, 3s) — the first attempt may have failed fast or spent its share of the budget on a blocked source, and `force` matters because a cached FAILURE would otherwise be re-reported for the whole 15min backoff without a single request being made. When even that answers nothing, the verdict is the explicit `? No current version information (npm / github did not answer within 3000ms).` — a distinct `exhausted` state, not a failed check: the inline launcher path (`start`/`pm2`, which never escalates) keeps the more specific "could not check (reason)" wording, and neither path may ever render an unknown answer as green. The total wait is ~4s, all of it at the bottom of the report, and the report costs at most 1s up front. `case 'status'` funnels every branch through one `finish()` so no early `process.exit()` can truncate the line (`modules/version_notice.ts`, `dexbot.ts`, `modules/constants.ts`, `tests/test_version_notice.ts`).
46
+
47
+ - **Fix(version-notice)**: make the version probe answer instead of shrugging — a node that could not reach `registry.npmjs.org` reported `? Could not check for a newer version.` forever, and a single unreachable host, a too-tight timeout or a 5s network hiccup were indistinguishable from each other and from "you are current". Four defects, one symptom: (1) ONE source was a single point of failure, so the probe now queries npm's dist-tag document FIRST and falls back to the GitHub latest-release endpoint, derived from `UPDATER.REPOSITORY_URL` (`GITHUB_RELEASE_URL` pins it, `'off'` disables it, `GITHUB_API_BASE` retargets it at a mirror) — a host that cannot reach the registry now degrades to a slower probe instead of a permanent "unknown"; the total budget is split EVENLY across sources so a hanging first source cannot starve the fallback, and `compareVersions` strips a leading `v` so a `v1.6.8` GitHub tag does not parse as an ancient version and masquerade as an available update. The npm-first order is deliberate and was benchmarked, not assumed: latency is a wash (warm p50 npm 21ms / github 18ms, cold 92-102ms / 97-99ms), npm's document is 5x smaller (8KB vs 40KB), the GitHub API is 60 req/hour per IP unauthenticated (403 when spent) while npm has no comparable ceiling, and decisively, the release pipeline creates the GitHub release ~4-9 minutes BEFORE it publishes to npm (1.6.8 10:15:14Z vs 10:24:00Z) — GitHub-first would advertise a version `dexbot update` cannot yet install, which is a wrong hint rather than an early one. (2) EVERY failure path now records WHY (`ENOTFOUND`, `ECONNREFUSED`, `HTTP 403`, `timeout after Nms`, `no version in response`, `no fetch available`) and the gray verdict names it, persisted in the cache so even a throttled run can explain itself; an unnamed "?" is not actionable. (3) A FAILURE was throttled for the full 24h `NOTICE_INTERVAL_MS`, so one transient outage pinned the "?" for a day with no retry left to disprove it — a success is still cached (`UPDATER.NOTICE_INTERVAL_MS`, now 12h rather than 24h: the published version does not move, but `dexbot stat` is the command an operator runs to ask "am I current?" and a 24h window let that answer come from the previous morning), a failure now backs off for `UPDATER.NOTICE_RETRY_MS` (15min), and `DEXBOT_VERSION_CHECK_FORCE=1` bypasses the cache entirely as the diagnostic escape hatch. Every entry point consults the cache on every run; none of them re-probe on a timer of its own. (4) `dexbot stat` awaited the probe inline under a 750ms cap that a cold DNS + TLS handshake to the registry routinely exceeds; the probe is now STARTED at the top of the report and its verdict APPENDED at the end, so the process table is never delayed, the line can no longer be truncated by an early `process.exit()` (every branch in `case 'status'` now funnels through one `finish()` that flushes first), and the probe gets a real budget (`UPDATER.NOTICE_STATUS_TIMEOUT_MS` 6s) now that it is off the critical path. `UPDATER.NOTICE_TIMEOUT_MS` 2s → 4s for the same reason on the launcher path. `dexbot stat` then wraps the probe in the staged wait above. Behavioral impact: strictly more information and no new failure mode — the notice still never changes code, still never blocks a start beyond its bounded budget, and an unknown verdict is still never dressed up as "up to date". Risk: two requests instead of one when the first source fails (bounded by the same total budget), and a genuinely offline node now retries every 15min instead of once a day (`modules/version_notice.ts`, `dexbot.ts`, `modules/config.ts`, `modules/constants.ts`, `docs/README.md`, `tests/test_version_notice.ts`).
48
+
7
49
  ### 2026-09-26
8
50
 
9
51
  - **Fix(concurrency)**: bound the price-correction drain and keep timer lock-waiters out of long broadcast regions — `correctAllPriceMismatches` held `_gridLock` (no acquisition timeout) across every queued correction, running price updates sequentially with `SYNC_DELAY_MS` between each, so a large `ordersNeedingPriceCorrection` backlog could hold the lock for minutes while every concurrent actor died at the 20s fill-lock timeout. Cancel-class entries (duplicate orphans / surplus / type mismatch) are still fully drained — batched, zero-delay, fund-safety-critical — but the sequential update loop is now capped at `FILL_PROCESSING.CORRECTION_MAX_UPDATES_PER_CYCLE` (default 5); the unselected remainder stays queued durably and re-drains next cycle, keeping its queue position so newer entries cannot be starved. A rate-limited backlog alarm (`CORRECTION_QUEUE_WARN_THRESHOLD` default 10, `CORRECTION_QUEUE_WARN_RATE_LIMIT_MS` 5 min) fires even while the drain defers, which is exactly when the queue is growing. The drain also defers *before* acquiring `_gridLock` when `isBroadcastingActive()`, and the maintenance timer loops (open-orders sync, periodic blockchain fetch) get the same pre-acquire deferral via `shouldDeferMaintenanceForBroadcast`; that helper is age-bounded by `BROADCAST_STALE_CLEAR_MS` so a leaked broadcast flag still lets the periodic tick through to run `_clearStaleBroadcastFlag` (deferring on a stale flag would otherwise remove the only watchdog that clears it). `TIMING.FILL_BROADCAST_DEFER_MAX_MS` is now derived as `max(configured, BROADCAST_STALE_CLEAR_MS + 30s)` so a legitimately long startup reconcile Phase 2 cannot outlast the fill-consumer deferral and drop it into the in-lock wait, and the deferral bound re-arms whenever `manager._broadcastingStartedAt` advances (a live region) while a frozen flag still trips the fallback. Startup create-group execution yields to the event loop between groups (`setTimeout(0)`, browser-safe) so the region's timers/watchdogs (region-end reschedule, `_awaitBroadcastIdle`, stale-flag clear) are not starved. Behavioral impact: a correction backlog no longer monopolizes `_gridLock`; fills/corrections still drain, bounded per cycle; the broadcast-deferral bound now outlasts the stale-flag watchdog it depends on; a leaked broadcast flag still self-heals. Risk: only the sequential price-update loop is budgeted, so a very large update backlog drains over multiple cycles (`modules/order/utils/order.ts`, `modules/constants.ts`, `modules/dexbot_fill_runtime.ts`, `modules/dexbot_maintenance_runtime.ts`, `modules/order/grid_reconcile_internal.ts`, `modules/order/manager.ts`, `tests/test_correction_queue_staleness.ts`, `tests/test_fill_pipeline_robustness.ts`, `tests/test_lock_bypass_guards.ts`).
@@ -306,7 +306,7 @@ node dist/analysis/analyze_trade_heatmap.js \
306
306
 
307
307
  ### TradingView Chart (`tradingview/analyze_tradingview.ts`)
308
308
 
309
- Generates a standalone TradingView-style HTML chart with candle OHLC, SMA, AMA, VWMA, and volume panel. For AMA-grid bots it also replays the market adapter's grid resets (AMA-price Δ / AMA-slope Δ) using the thresholds resolved from `general.settings` / `market_adapter_settings` — see [tradingview/README.md](tradingview/README.md#grid-reset-simulation) and [docs/GRID_RECALCULATION.md](../docs/GRID_RECALCULATION.md). See [tradingview/README.md](tradingview/README.md) for full documentation.
309
+ Generates a standalone TradingView-style HTML chart with candle OHLC, SMA, AMA, VWMA, and volume panel. For AMA-grid bots it also replays the market adapter's grid resets (AMA-price Δ / AMA-slope Δ) using the thresholds resolved from `general.settings` / `market_adapter_settings` — see [tradingview/README.md](tradingview/README.md#grid-reset-simulation) and [docs/GRID_RECALCULATION.md](../docs/GRID_RECALCULATION.md). Indicator state is set in the chart toolbar, not on the command line (`SMA`, `AMA`, `VWMA`, `Range`, `Scale` checkboxes; `Range` / `Scale` opt into the AMA they are derived from), and the toolbar choice is remembered per chart in the browser. See [tradingview/README.md](tradingview/README.md) for full documentation.
310
310
 
311
311
  # Recommended one-step: bot, pool, or pair (fetches candles + renders, default 3 months)
312
312
  dexbot tv <bot-key>
@@ -38,9 +38,9 @@ The sections below cover manual usage (explicit candle files, direct runner flag
38
38
  - Pair-orientation switcher for `A/B` and `B/A`
39
39
  - SMA overlay
40
40
  - AMA preset buttons `1–4` (one-click AMA1–4, active preset highlighted); numeric inputs kept
41
- - Bot-grid range highlight, off by default (the bot's min/max around AMA with live asymmetric tilt; red above AMA, green below)
41
+ - Bot-grid range highlight, off by default (the bot's min/max around AMA with live asymmetric tilt; red above AMA, green below). `Range` and `Scale` are AMA-derived, so turning one on opts into what it needs: `Range` → `AMA`, `Scale` → `Range` + `AMA`; turning `AMA` off takes `Range` and `Scale` back down with it, so the toggles never sit in a dead state. One-way opt-in is re-applied on load, so a chart saved with `Scale` on renders its band.
42
42
  - Grid-reset simulation (AMA bots, on by default): replays the market adapter's two recentering triggers over the candle history — the accepted grid center as a step line, the simulated grid range around it, and a marker per reset (`init` = first AMA snapshot, `Δ1` = AMA-price Δ, `Δs` = AMA-slope Δ). Thresholds come from the live config chain; a bottom-left panel shows the values, where they came from, and the reset counts (see [Grid-Reset Simulation](#grid-reset-simulation))
43
- - Range-scale switch: fit the price axis to the range band
43
+ - Range-scale switch: fit the price axis to the range band. Toggling `Range` / `Scale` (or dragging the grid-span slider) keeps the current view — the price axis is not refitted under the cursor; the band-fit applies on the next autofit (reload, timeframe switch, x pan) or immediately on a double-click of the price axis. Opting into `Scale`/`Range` also opts into the indicators they need (see above)
44
44
  - VWMA overlay
45
45
  - Order overlay for bot charts (active grid buys/sells as dashed levels, reserve line at the lowest grid buy, ceiling line at the highest grid sell, spread label; pair-aware, toggle in-chart)
46
46
  - Market panel (top-right): `SELL` / `Market` / `BUY` rows with distance-to-market %
@@ -175,6 +175,8 @@ market_adapter/data/lp/<pair>/lp_pool_<id>_<interval>.json
175
175
 
176
176
  ## CLI Flags
177
177
 
178
+ Indicator on/off state is not a generation-time flag: `SMA`, `VWMA`, `AMA`, `Range` and `Scale` are in-chart toolbar toggles, persisted per chart in `localStorage`, and `Range` / `Scale` opt into the AMA they are derived from. The `--range`, `--no-range`, `--range-scale` and `--no-ama` flags were removed — they duplicated the toolbar and could disagree with it (`--no-ama` on a chart with a range band produced a dead band). Nothing in this table sets an indicator on or off; only `--range-span` sizes the band.
179
+
178
180
  | Flag | Description | Default |
179
181
  |------|-------------|---------|
180
182
  | `--source <json\|market_adapter>` | Data source type | `json` |
@@ -189,16 +191,12 @@ market_adapter/data/lp/<pair>/lp_pool_<id>_<interval>.json
189
191
  | `--ama-slow-period <n>` | AMA slow period | `83.6` |
190
192
  | `--vwap-bars <n>` | Rolling VWMA window | `500` |
191
193
  | `--no-sma` | Disable SMA | — |
192
- | `--no-ama` | Disable AMA | — |
193
194
  | `--no-vwap` | Disable VWMA | — |
194
- | `--range` | Enable range highlight (off by default; toggle in-chart) | off |
195
- | `--no-range` | Disable range highlight | — |
196
- | `--range-scale` | Range Scaling: size the band by AMA slope like the grid build + fit price axis to it | — |
197
195
  | `--no-grid-reset` | Render without the grid-reset simulation (toggle it back in the chart) | on for AMA bots |
198
196
  | `--grid-delta-pct <n>` | Override the AMA-price Δ threshold for the simulation (skips config resolution) | config |
199
197
  | `--grid-slope-delta-pct <n>` | Override the AMA-slope Δ threshold for the simulation, in %/bar | config |
200
198
  | `--grid-warmup <bars>` | Override the simulation start bar (skipped before the first accepted center) | AMA warmup |
201
- | `--range-span <mult>` | x-range around AMA, 1.2–2 (default: bot grid setting) | bot grid |
199
+ | `--range-span <mult>` | x-range around AMA, 1.3–2.1 (default: bot grid setting) | bot grid |
202
200
  | `--orders-file <path>` | Order-grid JSON override for the overlay (default: `profiles/orders/<botKey>.json`) | bot orders |
203
201
  | `--no-orders` | Disable the order overlay (levels, reserve/ceiling lines, spread label) | — |
204
202
  | `--update-marker-ts <sec>` | Draw an "updated from here" line at the given unix timestamp | — |
@@ -274,12 +272,19 @@ so the chart cannot drift from the runtime. The panel labels the winning layer;
274
272
  The replay runs in the page, so the AMA series (and therefore the trigger
275
273
  points) follows the AMA inputs and preset buttons; the gating parameters that
276
274
  would come from config (`erPeriod`, lookback, warmup, clip percentile) are fixed
277
- at generation time. The replay uses the canonical `simulateGridResetSeries()`
278
- from `analysis/tradingview/grid_reset_sim.ts`, embedded verbatim via
275
+ at generation time. One slope window is shared by every consumer: the resolved
276
+ `lookbackBars` drives both the replayed `Δs` trigger and the `Scale` band tilt,
277
+ so a bot-configured lookback can no longer leave the plotted band measuring a
278
+ different slope than the trigger does (the shared constant remains the fallback
279
+ for pool/pair charts, which carry no grid-sim data), and both average with the
280
+ chart's selected slope model (see Notes). The replay uses the
281
+ canonical `simulateGridResetSeries()` from
282
+ `analysis/tradingview/grid_reset_sim.ts`, embedded verbatim via
279
283
  `embedFunctionSources` — not a hand copy of the adapter logic.
280
284
 
281
285
  ## Notes
282
286
 
287
+ - **Slope averaging.** The AMA slope is a **Huber-robust linear regression of `ln(AMA)` over the lookback window** — `computeHuberWindowSlopePct` in `market_adapter/core/strategies/dynamic_weight_series.ts`, which is the live adapter's own definition and is embedded here verbatim, so the chart and the bot run one logic path. Its tuning (`C`, `ITERATIONS`, `SCALE_FLOOR`, `ZERO_EPSILON`) is centralized in `MARKET_ADAPTER.DYNAMIC_WEIGHT_AMA_HUBER` and injected into the page as `const AMA_SLOPE_HUBER`, so a constant change flows to both. The output is in %/bar over the same window, so the tilt scale (`clamp(slope/maxSlopePct) * maxSlopeOffset`) and the `Δs` gate (`|Δslope| >= 8% of maxSlopePct`) keep their existing units. Measured on the repo's 1h pools with the shipped AMA preset at a 20-bar window: a single-bar AMA impulse is **strongly bounded** (a 1%/3%/5%/10% one-bar spike shifts the endpoint reading by 0.050/0.150/0.250/0.499 %/bar — 7x to 70x the reset gate — while the robust fit barely moves), and the fit is the smoothest robust option measured (second-difference energy ~25x lower than the old median's). Set `CHART_SLOPE_ESTIMATOR = 'endpoint'` in the page to render the reference two-point definition instead (kept in the core for comparison); the live adapter does not use it.
283
288
  - The chart embeds the vendored `uPlot` runtime inline (no CDN, no sibling `uplot/` dir, no DEXBot2 install needed). Each export is a single self-contained HTML file that renders anywhere, even after being copied or mailed to a machine without DEXBot2.
284
289
  - The displayed indicators are computed from the 1h base candles and then sampled onto the selected timeframe.
285
290
  - The current volume-weighted overlay is a rolling `VWMA`, not a session-reset VWAP.
@@ -3,6 +3,7 @@
3
3
  import * as client from './bitshares_client.js';
4
4
  const { BitShares, waitForConnected } = client;
5
5
  import { loadDexbotOrderSystemUtils, loadDexbotOrderUtils } from './dexbot_bridge.js';
6
+ import { normalizeAssetRef } from '../../modules/utils/asset_symbols.js';
6
7
  function getDexbotSystem() {
7
8
  return loadDexbotOrderSystemUtils();
8
9
  }
@@ -40,15 +41,19 @@ async function getDynamicGlobalProperties() {
40
41
  }
41
42
 
42
43
  async function getAsset(symbolOrId: any) {
43
- if (/^1\.3\.\d+$/.test(symbolOrId)) {
44
- const assets = await dbCall('get_assets', [[symbolOrId]]);
44
+ // Symbols arrive from a user-supplied `pair: "BASE/QUOTE"` option; BitShares
45
+ // answers lowercase lookups without error, so canonicalize before the id
46
+ // test and both lookup paths.
47
+ const ref = normalizeAssetRef(symbolOrId);
48
+ if (/^1\.3\.\d+$/.test(ref)) {
49
+ const assets = await dbCall('get_assets', [[ref]]);
45
50
  return assets[0] || null;
46
51
  }
47
52
 
48
53
  try {
49
- return await getDexbotSystem().lookupAsset(BitShares, symbolOrId);
54
+ return await getDexbotSystem().lookupAsset(BitShares, ref);
50
55
  } catch {
51
- const assets = await dbCall('lookup_asset_symbols', [[symbolOrId]]);
56
+ const assets = await dbCall('lookup_asset_symbols', [[ref]]);
52
57
  return assets[0] || null;
53
58
  }
54
59
  }
@@ -6,6 +6,7 @@ import { createClawInfrastructure } from './claw_infra.js';
6
6
  import { describeClawBridge } from './claw_manifest.js';
7
7
  import { describeMemuBridge, runMemuCommand } from './memu_bridge.js';
8
8
  import { clone } from './utils.js';
9
+ import { splitPairTarget } from '../../modules/utils/asset_symbols.js';
9
10
  import { adjustMpaCollateral, borrowMpa, cancelLimitOrder, createLimitOrder, executeBatch, getMpaPosition, getOpenOrders, repayMpaDebt, buildUpdateLimitOrderOperation, updateLimitOrder, settleMpa } from './chain_actions.js';
10
11
  import { buildCloseShortPlan, buildOpenShortPlan, buildTakeProfitPlan, closeShortOnBts, openShortOnBts, placeTakeProfitBuyOrderOnBts } from './short_mpa_strategy.js';
11
12
  import { launcherRun, launcherDrystart, launcherReset, launcherDisable, launcherPm2Start, launcherPm2Stop, launcherPm2Delete, launcherPm2Restart } from './claw_launcher.js';
@@ -24,20 +25,19 @@ function stripPrivateKey(options: ClawBridgeOptions = {}): ClawBridgeOptions {
24
25
  * Split a "BASE/QUOTE" pair string into { baseSymbol, quoteSymbol }.
25
26
  * Throws if the value is not a two-segment BASE/QUOTE string — extra segments
26
27
  * are rejected instead of being silently dropped.
28
+ * Both assetA and assetB are canonicalized to UPPERCASE (BitShares' on-chain
29
+ * spelling) by the shared splitter, so a lowercase pair and its uppercase
30
+ * spelling are one pair; only the error contract is claw's own.
27
31
  */
28
32
  function splitPair(pairValue: string) {
29
- if (typeof pairValue !== 'string' || !pairValue.includes('/')) {
30
- throw new Error('pair must be provided as BASE/QUOTE');
31
- }
32
-
33
- const segments = pairValue.split('/');
34
- if (segments.length !== 2 || !segments[0] || !segments[1]) {
33
+ const segments = splitPairTarget(pairValue);
34
+ if (segments.length !== 2) {
35
35
  throw new Error('pair must be provided as BASE/QUOTE');
36
36
  }
37
37
 
38
38
  return {
39
- baseSymbol: segments[0].trim(),
40
- quoteSymbol: segments[1].trim()
39
+ baseSymbol: segments[0],
40
+ quoteSymbol: segments[1]
41
41
  };
42
42
  }
43
43
 
@@ -399,5 +399,5 @@ async function runClawCommand(command: string, options: ClawBridgeOptions = {}):
399
399
  }
400
400
  }
401
401
 
402
- export { createClawBridge, describeClawBridge, describeRuntimeManifest, runClawCommand }
402
+ export { createClawBridge, describeClawBridge, describeRuntimeManifest, runClawCommand, splitPair }
403
403
 
package/claw/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "dexbot2-claw",
3
- "version": "1.6.8",
3
+ "version": "1.6.10",
4
4
  "private": true,
5
5
  "description": "Claw bridge and runtime integration layer for BitShares and DEXBot2.",
6
6
  "type": "module",
@@ -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.8",
5
+ "version": "1.6.10",
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.8",
4
+ "version": "1.6.10",
5
5
  "type": "module",
6
6
  "main": "index.js"
7
7
  }
@@ -11,6 +11,7 @@ import { PATHS } from '../../modules/paths.js';
11
11
  import { ensureDir } from '../../modules/order/utils/system.js';
12
12
  import { range } from '../math_utils.js';
13
13
  import { getStorage } from '../../modules/storage/index.js';
14
+ import { normalizeAssetSymbol } from '../../modules/utils/asset_symbols.js';
14
15
  const { readJSON, writeJSON } = getStorage();
15
16
  import { loadLpDataFile, } from '../../market_adapter/lp_chart_runner.js';
16
17
  const AMA_PROFILES_FILE = PATHS.PROFILES.MARKET_PROFILES_JSON;
@@ -301,7 +302,7 @@ function boundaryFlags(winner, erValues, fastValues, slowValues, fixedEr = null,
301
302
  }
302
303
  // ── Data loaders ──────────────────────────────────────────────────────────────
303
304
  function normalizeSymbol(value) {
304
- return String(value || '').trim().toUpperCase();
305
+ return normalizeAssetSymbol(value);
305
306
  }
306
307
  function inferIntervalLabel(dataFile, meta) {
307
308
  const fromMeta = Number(meta?.intervalSeconds);
@@ -4,7 +4,7 @@ import os from 'node:os';
4
4
  import { pathToFileURL, fileURLToPath } from 'node:url';
5
5
  import { Worker, isMainThread, parentPort, workerData } from 'node:worker_threads';
6
6
  import { calculateAMA, getAmaWarmupBars } from '../../market_adapter/core/strategies/ama.js';
7
- import { computeAverageAmaSlopePct } from '../../market_adapter/core/strategies/ama_slope_model.js';
7
+ import { computeHuberWindowSlopePct } from '../../market_adapter/core/strategies/ama_slope_model.js';
8
8
  import { range } from '../math_utils.js';
9
9
  import { parseListOrRange, loadLpData, fmt } from './shared_utils.js';
10
10
  import { getStorage } from '../../modules/storage/index.js';
@@ -318,7 +318,7 @@ function simulatePersistentGrid(candles, amaValues, params, weightName, weightFa
318
318
  // feeds trigger B and the grid price offset when asymmetricBounds is on.
319
319
  const slopeAt = new Array(candles.length).fill(null);
320
320
  for (let j = SLOPE_LOOKBACK_BARS; j < candles.length; j++) {
321
- const s = computeAverageAmaSlopePct(amaValues[j], amaValues[j - SLOPE_LOOKBACK_BARS], SLOPE_LOOKBACK_BARS);
321
+ const s = computeHuberWindowSlopePct(amaValues, j, SLOPE_LOOKBACK_BARS);
322
322
  if (s != null && Number.isFinite(s))
323
323
  slopeAt[j] = s;
324
324
  }
@@ -3,7 +3,7 @@ import fs from 'node:fs';
3
3
  import path from 'node:path';
4
4
  import { pathToFileURL } from 'node:url';
5
5
  import { calculateAMA, getAmaWarmupBars } from '../../market_adapter/core/strategies/ama.js';
6
- import { computeAverageAmaSlopePct } from '../../market_adapter/core/strategies/ama_slope_model.js';
6
+ import { computeHuberWindowSlopePct } from '../../market_adapter/core/strategies/ama_slope_model.js';
7
7
  import { range } from '../math_utils.js';
8
8
  import { parseListOrRange, loadLpData, fmt } from './shared_utils.js';
9
9
  import { getStorage } from '../../modules/storage/index.js';
@@ -43,8 +43,8 @@ const DEFAULT_REPOSITION_PCT = MARKET_ADAPTER.AMA_DELTA_THRESHOLD_PERCENT;
43
43
  // bot): --asymmetric-bounds enables slope-delta resets AND slope-ratio offset.
44
44
  // Trigger B fires when |slopePct_now − baseline| reaches
45
45
  // (AMA_SLOPE_DELTA_THRESHOLD_PERCENT / 100) × DYNAMIC_WEIGHT_AMA_MAX_SLOPE_PCT,
46
- // where slopePct is the average per-bar AMA change over
47
- // DYNAMIC_WEIGHT_AMA_LOOKBACK_BARS (computeAverageAmaSlopePct) and the
46
+ // where slopePct is the Huber-robust per-bar AMA slope over
47
+ // DYNAMIC_WEIGHT_AMA_LOOKBACK_BARS (computeHuberWindowSlopePct) and the
48
48
  // baseline mirrors botState.gridRangeScalingAmaSlope (re-seeded every reset).
49
49
  const SLOPE_TRIGGER_FACTOR = MARKET_ADAPTER.AMA_SLOPE_DELTA_THRESHOLD_PERCENT;
50
50
  const SLOPE_MAX_PCT = MARKET_ADAPTER.DYNAMIC_WEIGHT_AMA_MAX_SLOPE_PCT;
@@ -414,7 +414,7 @@ function simulateForParams(candles, amaValues, params) {
414
414
  // Evaluated over full history like the live adapter (only bar-index guards).
415
415
  const slopeAt = new Array(candles.length).fill(null);
416
416
  for (let j = SLOPE_LOOKBACK_BARS; j < candles.length; j++) {
417
- const s = computeAverageAmaSlopePct(amaValues[j], amaValues[j - SLOPE_LOOKBACK_BARS], SLOPE_LOOKBACK_BARS);
417
+ const s = computeHuberWindowSlopePct(amaValues, j, SLOPE_LOOKBACK_BARS);
418
418
  if (s != null && Number.isFinite(s))
419
419
  slopeAt[j] = s;
420
420
  }
@@ -8,6 +8,7 @@ import { parseJsonWithComments } from '../modules/order/utils/system.js';
8
8
  import { MARKET_ADAPTER } from '../modules/constants.js';
9
9
  import { loadMarketProfiles } from './tradingview/tradingview_uplot_chart_generator.js';
10
10
  import { sanitizeKey } from '../modules/utils/sanitize_key.js';
11
+ import { isSameAssetSymbol, canonicalizeBotAssetSymbols } from '../modules/utils/asset_symbols.js';
11
12
  // Single source of truth for bot keys (named AND unnamed bots) so analysis
12
13
  // tools resolve the same files production writes.
13
14
  import { createBotKey } from '../modules/account_orders.js';
@@ -70,11 +71,17 @@ function loadBotMeta(botKey, filePath = PATHS.PROFILES.BOTS_JSON) {
70
71
  if (!botKey)
71
72
  return null;
72
73
  const normalizedKey = String(botKey).toLowerCase();
74
+ // Analysis-side twin of modules/bot_settings.normalizeBotEntry: hand out
75
+ // the pair in BitShares' canonical UPPERCASE so a hand-edited lowercase
76
+ // bots.json cannot leak into titles, overlays or symbol comparisons. The
77
+ // same single definition of the symbol-carrying keys is reused (no second
78
+ // copy of the rule), and persistBotAccountId patches the raw file by
79
+ // index, so nothing here can rewrite the operator's JSON.
73
80
  const exact = entries.find((bot, index) => computeBotKey(bot, index) === normalizedKey);
74
81
  if (exact)
75
- return exact;
82
+ return canonicalizeBotAssetSymbols(exact);
76
83
  const loose = entries.find((bot) => sanitizeKey(bot?.name) === normalizedKey.replace(/-\d+$/, ''));
77
- return loose || null;
84
+ return loose ? canonicalizeBotAssetSymbols(loose) : null;
78
85
  }
79
86
  /**
80
87
  * Locate the source span of the entryIndex-th object literal inside the
@@ -501,9 +508,12 @@ function resolveAmaConfig(botKey) {
501
508
  return cfg;
502
509
  }
503
510
  const marketProfiles = loadMarketProfiles();
511
+ // Pair match is case-insensitive: market_profiles.json and bots.json are
512
+ // hand-edited, and a case-only difference must not silently drop the
513
+ // profile (a strict === here made the AMA/grid config vanish).
504
514
  const selectedProfile = marketProfiles?.profiles
505
- ? marketProfiles.profiles.find((entry) => String(entry.assetA) === String(botMeta.assetA) &&
506
- String(entry.assetB) === String(botMeta.assetB) &&
515
+ ? marketProfiles.profiles.find((entry) => isSameAssetSymbol(entry.assetA, botMeta.assetA) &&
516
+ isSameAssetSymbol(entry.assetB, botMeta.assetB) &&
507
517
  Number(entry.intervalSeconds) === 3600)
508
518
  : null;
509
519
  if (selectedProfile?.amas) {
@@ -15,11 +15,8 @@ declare function parseArgs(): {
15
15
  amaFastPeriod: number | undefined;
16
16
  amaSlowPeriod: number | undefined;
17
17
  smaEnabled: boolean;
18
- amaEnabled: boolean;
19
18
  vwapEnabled: boolean;
20
19
  vwapBars: number;
21
- rangeEnabled: boolean;
22
- rangeScaleEnabled: boolean;
23
20
  rangeSpan: number | undefined;
24
21
  ordersFile: string | null;
25
22
  noOrders: boolean;
@@ -29,11 +29,8 @@ function parseArgs() {
29
29
  amaFastPeriod: undefined,
30
30
  amaSlowPeriod: undefined,
31
31
  smaEnabled: false,
32
- amaEnabled: true,
33
32
  vwapEnabled: false,
34
33
  vwapBars: 500,
35
- rangeEnabled: false,
36
- rangeScaleEnabled: false,
37
34
  rangeSpan: undefined,
38
35
  ordersFile: null,
39
36
  noOrders: false,
@@ -73,18 +70,10 @@ function parseArgs() {
73
70
  config.amaSlowPeriod = Math.max(0.1, parseFloat(args[++i]) || DEFAULT_AMA.slowPeriod);
74
71
  else if (arg === '--no-sma')
75
72
  config.smaEnabled = false;
76
- else if (arg === '--no-ama')
77
- config.amaEnabled = false;
78
73
  else if (arg === '--no-vwap')
79
74
  config.vwapEnabled = false;
80
75
  else if (arg === '--vwap-bars')
81
76
  config.vwapBars = Math.max(5, parseInt(args[++i], 10) || 500);
82
- else if (arg === '--range')
83
- config.rangeEnabled = true;
84
- else if (arg === '--no-range')
85
- config.rangeEnabled = false;
86
- else if (arg === '--range-scale')
87
- config.rangeScaleEnabled = true;
88
77
  else if (arg === '--range-span')
89
78
  config.rangeSpan = parseFloat(args[++i]);
90
79
  else if (arg === '--orders-file')
@@ -242,7 +231,9 @@ async function main() {
242
231
  } : null);
243
232
  const title = config.title || inferTitle(jsonMeta, path.basename(filePath || 'tradingview'));
244
233
  const hasAmaGridPrice = AMA_KEYWORDS.has(String(botMeta?.gridPrice || '').trim().toLowerCase());
245
- const amaEnabled = hasAmaGridPrice ? config.amaEnabled : false;
234
+ // AMA is auto-enabled for gridPrice "ama"/"ama1-4" bots; there is no
235
+ // CLI switch any more (the in-chart AMA toggle owns that choice).
236
+ const amaEnabled = hasAmaGridPrice;
246
237
  // Bot grid bounds for the range highlight: mirrors the runtime grid
247
238
  // (center = AMA, min "Nx" = center/N, max "Nx" = center*N) with the
248
239
  // live asymmetric tilt. Null when no bot key (width% fallback in-page).
@@ -308,8 +299,6 @@ async function main() {
308
299
  amaEnabled,
309
300
  vwapEnabled: config.vwapEnabled,
310
301
  vwapBars: config.vwapBars,
311
- rangeEnabled: config.rangeEnabled,
312
- rangeScaleEnabled: config.rangeScaleEnabled,
313
302
  rangeSpan: config.rangeSpan,
314
303
  grid,
315
304
  gridSim,
@@ -26,6 +26,16 @@ declare function gridSimSlopeSignal(slopePct: any, clipThreshold: any, cfg: any)
26
26
  trend: string;
27
27
  slopeOffset: number;
28
28
  };
29
+ /**
30
+ * Resolve the per-bar slope estimator for a replay.
31
+ *
32
+ * Default is the canonical estimator the live adapter uses
33
+ * (computeHuberWindowSlopePct), so the replay keeps tracking the runtime.
34
+ * `cfg.slopeEstimator` exists so a caller can render a different averaging
35
+ * model without touching this module — it takes the whole series plus the index
36
+ * because windowed estimators need the window, not just the two endpoints.
37
+ */
38
+ declare function gridSimResolveSlopeEstimator(cfg: any): any;
29
39
  /**
30
40
  * Replay the two market-adapter grid-recentering triggers over `amaSeries`
31
41
  * (the chart's 1h AMA series, already in display orientation).
@@ -63,5 +73,5 @@ declare function simulateGridResetSeries(amaSeries: any, cfg: any): {
63
73
  slopeTriggerArmed: boolean;
64
74
  };
65
75
  };
66
- export { simulateGridResetSeries, gridSimSlopeSignal, gridSimPositiveNumber, gridSimNonNegativeInt, GRID_RESET_NONE, GRID_RESET_BOOTSTRAP, GRID_RESET_PRICE, GRID_RESET_SLOPE, };
76
+ export { simulateGridResetSeries, gridSimSlopeSignal, gridSimPositiveNumber, gridSimNonNegativeInt, gridSimResolveSlopeEstimator, GRID_RESET_NONE, GRID_RESET_BOOTSTRAP, GRID_RESET_PRICE, GRID_RESET_SLOPE, };
67
77
  //# sourceMappingURL=grid_reset_sim.d.ts.map
@@ -43,7 +43,7 @@
43
43
  * embedded alongside them (`computeAverageAmaSlopePct`,
44
44
  * `createAmaSlopeClipTracker`, `percentileFromSorted`, `clamp`).
45
45
  */
46
- import { computeAverageAmaSlopePct, createAmaSlopeClipTracker, } from '../../market_adapter/core/strategies/dynamic_weight_series.js';
46
+ import { computeHuberWindowSlopePct, createAmaSlopeClipTracker, } from '../../market_adapter/core/strategies/dynamic_weight_series.js';
47
47
  import { clamp } from '../../modules/order/utils/math.js';
48
48
  // Reset reason codes. NONE = the accepted center is carried over unchanged
49
49
  // (this is the vast majority of bars); the other three are the runtime's
@@ -93,6 +93,21 @@ function gridSimSlopeSignal(slopePct, clipThreshold, cfg) {
93
93
  slopeOffset: clamp(clipped / maxSlopePct, -1, 1) * maxSlopeOffset,
94
94
  };
95
95
  }
96
+ /**
97
+ * Resolve the per-bar slope estimator for a replay.
98
+ *
99
+ * Default is the canonical estimator the live adapter uses
100
+ * (computeHuberWindowSlopePct), so the replay keeps tracking the runtime.
101
+ * `cfg.slopeEstimator` exists so a caller can render a different averaging
102
+ * model without touching this module — it takes the whole series plus the index
103
+ * because windowed estimators need the window, not just the two endpoints.
104
+ */
105
+ function gridSimResolveSlopeEstimator(cfg) {
106
+ const custom = cfg?.slopeEstimator;
107
+ if (typeof custom === 'function')
108
+ return custom;
109
+ return computeHuberWindowSlopePct;
110
+ }
96
111
  /**
97
112
  * Replay the two market-adapter grid-recentering triggers over `amaSeries`
98
113
  * (the chart's 1h AMA series, already in display orientation).
@@ -164,6 +179,7 @@ function simulateGridResetSeries(amaSeries, cfg) {
164
179
  };
165
180
  }
166
181
  const clipTracker = createAmaSlopeClipTracker(erPeriod, lookbackBars, clipPercentile);
182
+ const estimateSlope = gridSimResolveSlopeEstimator(cfg);
167
183
  const readyBars = erPeriod + lookbackBars;
168
184
  let acceptedCenter = null;
169
185
  let acceptedSlope = null;
@@ -185,13 +201,10 @@ function simulateGridResetSeries(amaSeries, cfg) {
185
201
  // only the range tilt, never reset timing.
186
202
  const clipThreshold = clipTracker.push(hasAma ? ama : NaN);
187
203
  let slopePct = null;
188
- if (i >= readyBars) {
189
- const past = Number(amaSeries[i - lookbackBars]);
190
- if (hasAma && Number.isFinite(past) && past !== 0) {
191
- const s = computeAverageAmaSlopePct(ama, past, lookbackBars);
192
- if (Number.isFinite(s))
193
- slopePct = s;
194
- }
204
+ if (hasAma && i >= readyBars) {
205
+ const s = estimateSlope(amaSeries, i, lookbackBars);
206
+ if (Number.isFinite(s))
207
+ slopePct = s;
195
208
  }
196
209
  slopePctSeries[i] = slopePct;
197
210
  // Bars before AMA warmup carry no accepted state (the adapter keeps
@@ -303,5 +316,5 @@ function simulateGridResetSeries(amaSeries, cfg) {
303
316
  },
304
317
  };
305
318
  }
306
- export { simulateGridResetSeries, gridSimSlopeSignal, gridSimPositiveNumber, gridSimNonNegativeInt, GRID_RESET_NONE, GRID_RESET_BOOTSTRAP, GRID_RESET_PRICE, GRID_RESET_SLOPE, };
319
+ export { simulateGridResetSeries, gridSimSlopeSignal, gridSimPositiveNumber, gridSimNonNegativeInt, gridSimResolveSlopeEstimator, GRID_RESET_NONE, GRID_RESET_BOOTSTRAP, GRID_RESET_PRICE, GRID_RESET_SLOPE, };
307
320
  //# sourceMappingURL=grid_reset_sim.js.map