dexbot 1.6.16 → 1.6.18

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 (124) hide show
  1. package/CHANGELOG.md +58 -0
  2. package/analysis/README.md +10 -9
  3. package/analysis/ama_fitting/README.md +2 -2
  4. package/analysis/bot_fitting/README.md +3 -3
  5. package/analysis/tradingview/README.md +2 -2
  6. package/analysis/trend_detection/DYNAMIC_WEIGHT_RESEARCH.md +1 -1
  7. package/claw/package.json +1 -1
  8. package/claw/runtimes/openclaw-plugin/openclaw.plugin.json +1 -1
  9. package/claw/runtimes/openclaw-plugin/package.json +1 -1
  10. package/dist/analysis/ama_fitting/analyze_lambda_vs_slow.js +5 -3
  11. package/dist/analysis/analyze_args.d.ts +2 -1
  12. package/dist/analysis/fills_source.d.ts +1 -8
  13. package/dist/analysis/fills_source.js +1 -1
  14. package/dist/analysis/grid_correction_check.d.ts +9 -6
  15. package/dist/analysis/grid_correction_check.js +56 -64
  16. package/dist/analysis/math_utils.d.ts +1 -1
  17. package/dist/analysis/trade_profitability.d.ts +1 -1
  18. package/dist/analysis/tradingview/grid_reset_sim.js +1 -1
  19. package/dist/analysis/tradingview/tradingview_uplot_chart_generator.js +7 -7
  20. package/dist/analysis/trend_detection/backtest_ama_slope_huber.js +1 -1
  21. package/dist/analysis/trend_detection/huber_scale_variants.d.ts +4 -3
  22. package/dist/market_adapter/cli_args.d.ts +6 -1
  23. package/dist/market_adapter/cli_args.js +16 -2
  24. package/dist/market_adapter/core/kibana_candles.d.ts +5 -1
  25. package/dist/market_adapter/core/kibana_candles.js +3 -1
  26. package/dist/market_adapter/core/strategies/regime_gate.d.ts +7 -1
  27. package/dist/market_adapter/core/strategies/regime_gate.js +3 -1
  28. package/dist/market_adapter/inputs/cex_candle_parsing.d.ts +7 -2
  29. package/dist/market_adapter/inputs/cex_candle_parsing.js +3 -1
  30. package/dist/market_adapter/inputs/fetch_book_data.d.ts +7 -1
  31. package/dist/market_adapter/inputs/fetch_book_data.js +3 -1
  32. package/dist/market_adapter/inputs/fetch_cex_synthetic_data.js +2 -11
  33. package/dist/market_adapter/inputs/fetch_lp_data.d.ts +26 -1
  34. package/dist/market_adapter/inputs/fetch_lp_data.js +62 -52
  35. package/dist/market_adapter/inputs/kibana_feed_source.d.ts +14 -2
  36. package/dist/market_adapter/inputs/kibana_feed_source.js +14 -1
  37. package/dist/market_adapter/inputs/window_cache.d.ts +14 -3
  38. package/dist/market_adapter/inputs/window_cache.js +14 -1
  39. package/dist/market_adapter/lp_chart_runner.d.ts +12 -9
  40. package/dist/market_adapter/lp_chart_runner.js +3 -1
  41. package/dist/market_adapter/lp_chart_strategy_loader.d.ts +5 -1
  42. package/dist/market_adapter/lp_chart_strategy_loader.js +3 -1
  43. package/dist/market_adapter/market_adapter.d.ts +10 -2
  44. package/dist/market_adapter/market_adapter.js +10 -11
  45. package/dist/market_adapter/utils/chain.d.ts +2 -3
  46. package/dist/market_adapter/utils/file_json_cache.d.ts +5 -1
  47. package/dist/market_adapter/utils/file_json_cache.js +3 -1
  48. package/dist/market_adapter/utils/file_lock.js +1 -1
  49. package/dist/market_adapter/utils/native_history.d.ts +7 -3
  50. package/dist/market_adapter/utils/native_history.js +3 -1
  51. package/dist/market_adapter/utils/pair_orientation.d.ts +2 -2
  52. package/dist/modules/account_bots.d.ts +3 -0
  53. package/dist/modules/bots_file_lock.d.ts +2 -2
  54. package/dist/modules/bots_file_lock.js +2 -2
  55. package/dist/modules/chain_keys.d.ts +1 -1
  56. package/dist/modules/constants.d.ts +6 -0
  57. package/dist/modules/constants.js +37 -6
  58. package/dist/modules/credit_pricing.d.ts +20 -1
  59. package/dist/modules/credit_pricing.js +23 -1
  60. package/dist/modules/credit_runtime.js +33 -16
  61. package/dist/modules/dexbot_class.d.ts +11 -1
  62. package/dist/modules/dexbot_class.js +15 -2
  63. package/dist/modules/dexbot_cow_runtime.d.ts +90 -38
  64. package/dist/modules/dexbot_cow_runtime.js +507 -108
  65. package/dist/modules/dexbot_credential_client.d.ts +5 -0
  66. package/dist/modules/dexbot_maintenance_runtime.js +117 -12
  67. package/dist/modules/dexbot_startup_runtime.js +7 -1
  68. package/dist/modules/graceful_shutdown.d.ts +2 -2
  69. package/dist/modules/graceful_shutdown.js +2 -2
  70. package/dist/modules/launcher/credential_daemon.d.ts +14 -2
  71. package/dist/modules/launcher/credential_daemon.js +60 -26
  72. package/dist/modules/launcher/runtime_mode.d.ts +4 -3
  73. package/dist/modules/node_manager.d.ts +1 -1
  74. package/dist/modules/node_manager.js +1 -1
  75. package/dist/modules/order/accounting.js +2 -1
  76. package/dist/modules/order/export.d.ts +2 -2
  77. package/dist/modules/order/export.js +2 -2
  78. package/dist/modules/order/grid.d.ts +26 -14
  79. package/dist/modules/order/grid.js +416 -73
  80. package/dist/modules/order/grid_reconcile.js +5 -1
  81. package/dist/modules/order/grid_reconcile_internal.js +2 -1
  82. package/dist/modules/order/index.d.ts +22 -1
  83. package/dist/modules/order/manager.d.ts +40 -7
  84. package/dist/modules/order/manager.js +149 -23
  85. package/dist/modules/order/strategy.d.ts +5 -0
  86. package/dist/modules/order/strategy.js +44 -3
  87. package/dist/modules/order/sync_engine.d.ts +12 -1
  88. package/dist/modules/order/sync_engine.js +135 -20
  89. package/dist/modules/order/utils/math.d.ts +49 -10
  90. package/dist/modules/order/utils/math.js +71 -14
  91. package/dist/modules/order/utils/order.d.ts +65 -11
  92. package/dist/modules/order/utils/order.js +198 -28
  93. package/dist/modules/order/utils/system.d.ts +112 -2
  94. package/dist/modules/order/utils/system.js +338 -12
  95. package/dist/modules/order/utils/validate.d.ts +4 -1
  96. package/dist/modules/order/utils/validate.js +9 -2
  97. package/dist/modules/storage/index.d.ts +3 -2
  98. package/dist/modules/storage/index.js +3 -2
  99. package/dist/modules/types.d.ts +44 -2
  100. package/dist/scripts/analyze-credit.js +64 -23
  101. package/dist/scripts/bts_distribution.d.ts +66 -0
  102. package/dist/scripts/bts_distribution.js +2102 -0
  103. package/dist/scripts/token_distribution.d.ts +45 -0
  104. package/dist/scripts/token_distribution.js +1870 -0
  105. package/dist/unlock.js +42 -24
  106. package/docs/COPY_ON_WRITE_MASTER_PLAN.md +1 -1
  107. package/docs/COW_INVARIANTS.md +24 -8
  108. package/docs/DEXBOT_COMPARISON.md +5 -5
  109. package/docs/EVOLUTION.md +10 -8
  110. package/docs/FUND_MOVEMENT_AND_ACCOUNTING.md +13 -11
  111. package/docs/GRID_PRICE_INVARIANT.md +29 -3
  112. package/docs/GRID_RECALCULATION.md +3 -3
  113. package/docs/GRID_RECONCILE.md +5 -5
  114. package/docs/LIFECYCLE.md +11 -11
  115. package/docs/LOGGING.md +22 -0
  116. package/docs/MPA_CREDIT_USAGE.md +3 -2
  117. package/docs/ORDER_ENGINE_POST_1.0_RETROSPECTIVE.md +236 -32
  118. package/docs/README.md +1 -1
  119. package/docs/architecture.md +205 -6
  120. package/docs/developer_guide.md +12 -0
  121. package/market_adapter/README.md +11 -6
  122. package/modules/README.md +18 -14
  123. package/package.json +6 -3
  124. package/scripts/README.md +85 -148
package/CHANGELOG.md CHANGED
@@ -2,6 +2,64 @@
2
2
 
3
3
  All notable changes to this project will be documented in this file.
4
4
 
5
+ ## [1.6.18] - 2026-11-01 - Partial-Fill Re-Anchor Recovery, Rail-Derived Boundary & Live Fill Prices, Edge-Fill Pivot Exclusion, Guard Arity Pinning, CLI `--flag=value`, Export-Surface Cleanup
6
+
7
+ ### 2026-11-01
8
+
9
+ - **Fix(spread)**: harden partial-fill re-anchor and recovery — a live market-pair bot stayed out of spread after a sell sweep even though the correction loop ran; four independent gaps combined. (1) A gap-evacuation plan built against an older boundary executed as a normal update once its live-geometry stamp went stale, moving valid in-rail buys off the bid edge and re-opening the spread: the build loop now skips a stale evacuation instead of falling through to the direction-only last-fill guard, and the final pre-broadcast gate drops a stamp whose live geometry went stale after op-building, including when the fill pivot itself did not change. (2) The fill anchor could not repair a window left behind a PARTIAL fill — the residual at the fill slot is inside the implied band by construction, so `validatePersistedBoundary` refused every re-anchor; the fill's own PARTIAL residual is now explicitly allow-listed (same side, same ladder level, exact anchor slot) while ACTIVE/foreign in-band orders still refuse, plus a post-clamp check that fails closed when the grid ceiling prevents the fill from leaving its window. (3) A re-anchor is absolute, but its plan carried only the derivation's consumed-crawl subset, so older owed deltas could be applied on top of the new boundary later: a successful re-anchor now snapshots and consumes the whole plan-time crawl ledger, and records recorded after plan build survive. (4) Create-only repair cannot close a fully allocated rail (free funds read 0 forever): when free funds cannot fund every promoted gap slot, a resting same-side ACTIVE order is rotated into the unfunded slot at its booked size (no new commitment, no growth/shrink; edge and PARTIAL sources excluded, crossing/last-fill/grid-price guards unchanged), rotation destinations come from the post-dedupe/post-duplicate-price candidate list so an already-occupied price cannot receive one, and rotation-only plans count as executable. Review hardening: startup and resume/reconcile load paths pass `tolerateTransientStranding` (the re-anchor deliberately leaves the fill's own PARTIAL residual in-band, so a strict load would rebuild the boundary away on the first restart); `reanchorBoundaryFromLastFill` requires `lastFillPivotSource === 'fill'`, because a one-sided book seed is a pricing hint for the guard, never an absolute geometry anchor (the bot-scoped last-market-fill row is the fallback); exactly-zero free funds now reach the rotation-only repair on the initial check, the TOCTOU re-plan and the fresh-master re-plan when the side decision carries the structured `no-free-funds` code (an unavailable market price stays a hard skip); and `plannedCount` includes rotation candidates so `checkSpreadCondition` reports the post-guard executed count rather than the plan count. Files: `order/grid_reconcile.ts`, `order/utils/system.ts`, `order/utils/math.ts`, `order/strategy.ts`, `order/grid.ts`, `dexbot_cow_runtime.ts`, `dexbot_startup_runtime.ts`; covered by `tests/test_stale_evac_build_skip.ts` and extended re-anchor, restore-validation, crawl-ledger, final-pivot-gate, spread-correction and pure-fund-driven tests.
10
+
11
+ - **Fix(order)**: keep the boundary on the placed rails and judge geometry by live fill prices — a sell sweep places counter BUYs on the promoted rail, but the refill hold kept the old committed boundary when the opposite-side refills were guard-skipped, so the next plan reclassified those counters as in-band and rotated SELLs onto their price, collapsing a 1.5% band to 0.3%; separately, a refused-commit adoption can leave a master slot keyed at an old generation price while its chain order trades elsewhere, and the fill pivot, GAP-EVAC and the crossing guard all trusted that stale price. `deriveRailBoundary` now clamps the committed boundary to the batch's resulting rails (`maxBuy <= boundary <= minSell-gap-1`, live master + kept op destinations) so counter orders win over empty refill holes, crossed or over-ceiling rails fail closed instead of self-legalizing, and `boundaryHeld` follows the value actually committed. Fill records now carry the chain execution price (history pays/receives, pass-1 chain price, pass-2 adoption, phantom cleanup) and the queued-fill pivot refresh prefers fill economics over the slot price without rewriting slot identity prices (GRID-PRICE-INVARIANT); `reanchorBoundaryFromLastFill` anchors on the fill batch's extremum for that side (max SELL/min BUY) rather than the mutable last-processed pivot, so a chunked sweep cannot leave its furthest counter in-band; new `resolveLiveOrderLadderPosition` maps the live chain price onto the ladder before falling back to the slot id for detection, drain-time validation and the eviction teeth, and a price mismatch whose live price is in-band queues a cancel-only `gapEvacuation` and drops any plain re-price for that chain order; the crossing candidate set uses the live chain price so an emission cannot print onto an opposite-side order adopted at a stale slot price. Risk: transient decisions follow the chain price while the grid slot identity stays frozen, and rail cross/ceiling failures keep the previous boundary and defer to GAP-EVAC. Covered by new `tests/test_rail_derived_boundary.ts` and `tests/test_live_geometry_provenance.ts` plus batch-extremum cases in `test_boundary_fill_reanchor`.
12
+
13
+ - **Fix(order)**: never arm the last-fill pivot from an edge-pinned fill — an edge order (grid floor/ceiling) is static fat-finger insurance, not market movement, yet `recordLastFilledPrices` armed the pivot on every fill and the pivot doubles as the absolute geometry anchor for `reanchorBoundaryFromLastFill`, so a wick that triggered a floor insurance BUY moved the window onto the grid edge (observed: boundary 29 -> 0 on a 60-slot ladder; mirrored at the ceiling). Eligibility now lives at the single pivot writer: fill ids are classified with `collectEdgePinnedFillIds` (`modules/order/utils/order.ts`), the same window/edge classifier the placement pickers use, so "edge" cannot mean two things; PARTIAL fills still arm the pivot (a partial at a far slot is a real trade and its residual is already allow-listed by the re-anchor). Behavioural impact: an edge fill no longer vetoes its own side of the book and can no longer drive an absolute boundary move — the guard and the anchor stay on the last WINDOW trade, so that side stays vetoed relative to it until a window fill or the 24h pivot TTL (the pre-fix alternative moved the whole window). The skip is logged (`[FILL-PIVOT] ... edge-skipped=K` plus a dedicated edge-only-batch line). Covered by new `tests/test_edge_fill_pivot.ts` and REANCHOR-18/19.
14
+
15
+ - **Fix(guard)**: pin the direction-only guard arity, re-arm the pivot explicitly, and stop self-legalizing the rail clamp — review follow-ups on the v1.6.12 -> v1.6.17 order-engine arc. `isLastFillGuardBlocked` still carried two dead parameters (`size`, `increment`) left over from the removed `pivot +/- increment/2` band, and keeping them made a band-rule reintroduction a compile-time non-event: the signature is now `(price, type, lastPrice, lastType)` at every call site (COW CREATE/rotation/fallback gates, planner predicate), and LFG-5 pins `.length === 4` plus "trailing arguments cannot resurrect a band". `initializeGrid` cleared the generation-bound pivot while its comment claimed the guard re-arms on the first real fill, and the read-time fallback silently kept an old-generation value, so after a rebuild in a market that had moved away one side read `last-fill-blocked` forever while the geometry clock rebuilt the generation every cooldown with no way to succeed: `rearmLastFillPivotFromMarketFill` now writes the re-arm explicitly through the one pivot writer (provenance `fill`, original fill timestamp, logged), and the geometry-bind escalation re-centers at most ONCE per pivot value (`_lastGeometryResyncPivotKey`) before reporting that only a fill or the 24h pivot TTL restores the side. `deriveRailBoundary` clamped onto EVERY live rail order, so one stray (refused-commit adoption, stranded hold, guard straggler) 18 slots off pulled the boundary 138 -> 115 and re-typed the whole window: rail membership is now the batch's own op destinations plus master orders on their own side of the planned boundary, strays are skipped and named in the log, rail indices come from the live chain price (`resolveLiveOrderLadderPosition`) instead of a possibly stale slot id, and the result passes the shared `validatePersistedBoundary` gate (cancel/rotation sources allow-listed, skipped on a sparse ladder whose array-derived ceiling would reject everything). Crossing CREATEs are observed rather than vetoed — a hard veto would re-open the counter-order deadlock after a gap — via `warnCrossingCreate`, logged once per batch from already-cached evidence (no chain call). Same pass: one pivot resolver (two verbatim copies merged), one boundary validator shared by the re-anchor and the rail clamp, and the batch-extremum logic extracted as the pure `resolveFillAnchorIndex`. Files: `order/utils/system.ts`, `order/utils/order.ts`, `order/grid.ts`, `order/grid_reconcile*.ts`, `dexbot_cow_runtime.ts`; covered by new `tests/test_last_fill_pivot_rearm.ts` plus RAIL-10..14, SLF-11/12 and arity updates in LFG-5, FG-9, GPI-WIRE-003 and SGP-1/4.
16
+
17
+ - **Fix(spread)**: count last-fill-excluded candidates per slot — the planner's "Excluded N candidate(s)" line counted pool visits, and a slot can legitimately appear in more than one candidate pool (an empty in-rail slot normalized to SPREAD satisfies both the SPREAD pool and the orphan pool, which the merge already dedupes), so every vetoed slot was reported twice and the over-count was worst exactly when the pools overlapped most. That number decides the `last-fill-blocked` stall and is the only signal for how much of a side the pivot blocked, so inflating it overstated the geometry bind. The counter now de-duplicates by slot id (an unidentified candidate still counts, since it cannot be matched); the plan itself is unchanged, the filter being a predicate and not a side effect. SLF-13 pins the overlap (`Excluded 2`, not `4`) and was verified failing on the pre-fix tree.
18
+
19
+ - **Refactor(analysis)**: judge fills by the direction-only guard — `analysis/grid_correction_check.ts` still implemented the old `pivot +/- increment/2` band while claiming to mirror `isLastFillGuardBlocked` 1:1, so it reported exactly the tightening placements the live guard allows. The predicate now matches the runtime rule (BUY < last fill, SELL > last fill, equal price blocked) with the same four arguments; the band fields are gone from the report header, violation table and JSON payload (per-row `halfInc` stays 0 so existing consumers keep their shape); `--increment` is documented as informational (default and configured value still reported); and the guard section of `analysis/README.md` documents the offline limits — edge-pinned fills cannot be reconstructed from the fill stream, so wick/insurance fills can appear as violations, and the spread-correction bypass is invisible per fill. Offline report only: no live behaviour change.
20
+
21
+ - **Feat(analysis)**: step SMA/VWMA period controls by 10 — the chart toolbar's period steppers moved one unit per click, making broad sweeps (e.g. 500 -> 600) tedious and hold-to-repeat slow. SMA and VWMA up/down buttons now step by 10 per click and per hold tick, the SMA arrow floor rises from 1 to 10 to match the 10-unit step, and the VWMA lower clamp/arrow floor drops from 24 to 10 so the 10-step sequence is reachable across the whole allowed range (manual entry unaffected apart from the lower clamp). AMA controls and chart rendering are unchanged.
22
+
23
+ - **Refactor(market_adapter)**: remove dead paths and narrow the test surface — the adapter still carried a native-history fallback that could never run (adapter_client exposes only db/history proxies, so `history.getMarketHistory` is always present and `BitShares.tradeHistory` never existed on the client shape), the CEX seeder's `typeof`/`||` guards re-checked helpers destructured from a `require` that would already have thrown, and seven types were exported although only used inside their defining modules. 41 test-only named exports became one explicit `__test` object per module: production callers keep the same public surface, tests still reach the internal seams, and future dead-export scans no longer need to special-case white-box helpers. The LP exporter CLI drift is fixed by routing it through the shared `walkCliArgs` walker (with `--help`, unknown flags rejected instead of silently ignored, and `--chunkMonths`, `--apiKey`, `--out` documented), the README no longer claims the adapter only handles 1h candles, and the file-lock default payload no longer writes an owner UUID into `pid` — it records `runtime.pid` while keeping the unique ownerId for release checks.
24
+
25
+ - **Fix(market_adapter)**: accept `--flag=value` and validate the LP export CLI — `walkCliArgs` rejected any value token starting with `--`, so a path or API key beginning with `--` could not be passed at all, and the LP exporter had drifted onto bare `parseInt`, silently storing `NaN` for `--chunkMonths abc`. The walker now understands `--flag=value` (the escape hatch for flag-shaped values), refuses an inline value on a flag/help that takes none, and reports an unknown token exactly as typed; the exporter routes its options through validating helpers (`--chunkMonths` an integer >= 1, `--precA`/`--precB` integers >= 0 with an empty inline value no longer read as 0, `--apiKey`/`--out` non-empty) and `--help` documents the `=` form. Behavioral impact for `fetch_lp_data`: unknown flags still fail, invalid numbers now fail naming the flag instead of producing `NaN`, and a flag-shaped value must use `--flag=value`. Covered by new `tests/test_cli_args_walker.ts` and extended `tests/test_fetch_lp_data_logic.ts`.
26
+
27
+ - **Fix(build)**: export the credential response type and pin the backtest slope test — the claw credential wrapper infers `Promise<CredentialDaemonResponse>` from the imported client, but declaration emit cannot name a module-private interface there, so `npm run build --prefix claw` failed with TS4058; the type is exported again (compile-time surface only, with a comment explaining why it must stay exported). `test_backtest_bot_fitting_logic` still hardcoded the old 0.09 AMA max-slope default and failed once the canonical constant moved to 0.1, so the full/half/sub-strength inputs are derived from `MARKET_ADAPTER.DYNAMIC_WEIGHT_AMA_MAX_SLOPE_PCT` and track the production knob instead of drifting on the next tune. Both restore a green `npm test` (331/331 files, 14 live tests skipped) and `build --prefix claw` on this branch.
28
+
29
+ - **Test(guards)**: enforce the `__test` seam and run the analysis typecheck in `npm test` — the `__test` convention replaced 41 named exports with one seam object per module, but nothing prevented production code from importing that object, so a future caller could quietly build on a test-only surface; and the standalone analysis tsconfig (stricter: `noUnusedLocals`/`noUnusedParameters`) was reachable only through `npm run typecheck:analysis`, so it could rot unnoticed. `tests/test_public_surface_guard.ts` scans every production `.ts` file (modules, market_adapter, analysis, scripts, claw and the root entrypoints) and fails if `__test` is referenced without defining a seam or if a seam is touched more than once inside its defining module, and `npm test` / `npm run test:live` now run `typecheck:analysis` before the suite.
30
+
31
+ - **Refactor(analysis)**: drop dead exports and correct stale docs — the analysis surface is aligned with its real callers and output locations: the README states that shared chart/bot-key helpers are imported by the production market adapter and that `--source market_adapter` prefers the bot candle cache before the centers file; the AMA optimizer/backtest docs point at `analysis/results/` (`PATHS.ANALYSIS.RESULTS_DIR`), not `analysis/ama_fitting/`; zero-consumer exports are narrowed back to internal types; the inert `analysis/.npmignore` is removed (the package `files` allowlist already ships only the analysis READMEs plus uplot); and `analysis/tsconfig.json` is wired into `typecheck:analysis` so the standalone config is actually used. **Removed CLI surface**: the deprecated `--tolerance` alias of `grid_correction_check` is gone — its band no longer exists and `--increment` already carries the report label.
32
+
33
+ - **Refactor(modules)**: remove dead exports, params and the slot-helper shim — an audit of `modules/` found no unreachable files or unused locals, but a layer of vestigial surface: ten symbols are de-exported (the remaining over-export candidates stay exported because declaration emit needs them named across modules, TS4023/TS4058), the `parseSlotIndex` forwarding wrapper and re-export in `order/utils/order.ts` are dropped so all callers import the canonical helper from `order/utils/slot.ts` and the two copies cannot drift again, the `calculateOrderCreationFees` JSDoc is corrected, and `lazy_shim.ts` / `launcher/runtime_mode.ts` are documented in `modules/README.md`. **Breaking for out-of-tree `dist/` consumers**: `allocateFundsByWeights`, `calculateOrderSizes` and `calculateRotationOrderSizes` lose their unused trailing `minSize`/`minSellSize`/`minBuySize` parameters (every in-repo caller passed 0, so behaviour is unchanged); in-tree call sites and tests are updated positionally.
34
+
35
+ - **Docs**: symbol-name citations and export-surface rules replace drifted line numbers, and the module map is corrected — 36 of 64 `file.ts:LINE` references in `docs/` no longer pointed at the code they described, so every one is now a symbol name plus filename, which also removed three outright-wrong claims (a deleted `computeOutOfToleranceDriftTag` listed as a live `priceForSlot` consumer, a non-existent `ANCHOR.PROJECTION_ENABLED` asserted dead three times, and a misnamed maintenance entry point); two documented symbols were corrected and deliberately removed ones keep only the filename. `modules/README.md` moves `runtime_mode.ts` into the `launcher/` block (it was the only tree entry resolving to nothing), fixes descriptions that sent readers to the wrong subsystem (`chain_keys` as the master-password vault plus signing-key retrieval, `credential_runtime` as socket/path helpers, `daemon_node_health` as a failure ledger with no health checking, `socket_json_client` as newline-delimited JSON rather than JSON-RPC, `storage/browser_adapter` as an IndexedDB-persisted Map), unwraps two markdown links that sat inside a fenced tree, names the real crypto split and fill wiring in the principles, and re-aligns three one-column-off rows; module-header usage snippets that used CommonJS `require()` in a `"type": "module"` package now use static imports with `.js` specifiers. `developer_guide` gains an "Export Surface & Test Seams" section (declaration emit is a real consumer, shipped `dist/` is a public API, test-only helpers live in one `__test` object enforced by `tests/test_public_surface_guard.ts`), and `ORDER_ENGINE_POST_1.0_RETROSPECTIVE` is reconciled with the code: §0/§6/§7 described the offline checker with old band semantics, §9.1/§9.7/§9.9 carried pre-fix statements, the header/TOC/snapshot/footer said v1.6.14, the §9.5 ledger gained rows for the whole 1.6.15/1.6.17 arc and the post-1.6.17 work, §9.6 gained four invariants (only a window trade may become the pivot, one boundary validator, a rail clamp cites only its own evidence, the pivot has a lifetime), and R2-R5 record the "one rule, several implementations" meta-pattern plus lessons 8-11. `COW_INVARIANTS`, `architecture`, `GRID_PRICE_INVARIANT` and `LOGGING` document the new rail-clamp membership, re-anchor eligibility, explicit re-arm, once-per-pivot re-center, `[COW-CROSS-GUARD]` line, capped re-center warning and the per-slot "Excluded N" count. Docs/comments only; `npm test` 331/331.
36
+
37
+ ## [1.6.17] - 2026-10-30 - Last-Fill Direction Guard, Spread-Correction Stall Naming & Chain-Truth Funding, Owed-Crawl Consumption, Restart Auth-Before-Stop, Pool-Priced LP Collateral, Supply Distribution Analyzers
38
+
39
+ ### 2026-10-30
40
+
41
+ - **Feat(scripts)**: add a BTS supply distribution analyzer — `scripts/bts_distribution.ts` (`npm run distribution`) is a read-only live-chain report that buckets the core asset into call-order collateral, global and individual settlement funds (with individual debt and force-settlement parameters), governance tickets, vesting and legacy balances, liquidity pools, SameT/credit funds, HTLC escrow and asset fee pools, then reports the leftover as a derived liquid residual compared against total supply and a derived circulating float (optional external reference). It also pulls the liquid rich list from `asset_api::get_asset_holders` (retrying on a node without that API), tags exchange-like account names as a heuristic, and can page the full holder list to split the residual into account balances, blinded balances and order books with concentration and balance bands. Output is a colorized terminal report plus a self-contained HTML donut report under the gitignored `analysis/charts/`. Documented in `scripts/README.md`; verified with a clean build, `check:any`, and live runs in default and full-rich-list modes.
42
+
43
+ - **Feat(scripts)**: add a per-token companion analyzer — `scripts/token_distribution.ts` (`npm run token-distribution`) buckets a single asset into free balances, limit orders, liquidity pools, vesting balances, P2P credit offers and deal collateral, SameT funds, HTLC escrow, accumulated market fees and blinded supply, reconciling every bucket against `current_supply`. Liquidity is grouped by counterpart asset and reported as a separate donut, and a 3% price-change table combines orderbook and constant-product pool depth per market (token sellable at −3%, buyable at +3%, each as a share of total supply), with pool depth net of the taker fee and capped orderbook rows marked. Read-only, with `--json` and `--no-orders` modes; documented in `scripts/README.md`.
44
+
45
+ - **Tune(ama)**: make the slowPeriod ladder exact −9% response steps — AMA2–AMA4 are now derived from AMA1 (62.1) so each preset lowers the effective smoothing coefficient by ~9% at the typical ER (`AMA_CONVERGENCE_ER_AVG` 0.151), where the old fixed +16% period ladder shrank the response difference toward the slow end (−9.4/−8.7/−7.8%). AMA2 72.0 → 71.5, AMA3 83.6 → 83.5, AMA4 96.9 → 99.3 (unrounded 62.10/71.48/83.46/99.27); AMA4 is the only material change (~4.7% lower ER→0 noise floor, ~1.25% less responsive at ER 0.151, ~16 extra warmup bars), AMA1–AMA3 are effectively unchanged. Docs, chart preset annotations and the Huber backtest default (now derived from `MARKET_ADAPTER.AMAS` instead of hardcoded) are aligned. Covered by `test_bot_defaults_parity`, `test_market_adapter_logic` and `test_lp_chart`.
46
+
47
+ - **Tune(ama)**: raise the AMA slope ceiling default from 0.09 to 0.1 — `DYNAMIC_WEIGHT_AMA_MAX_SLOPE_PCT` now needs a stronger per-bar trend before reaching full influence, de-sensitizing range asymmetry, grid price offset and buy/sell weight tilt to the same slope magnitude; the AMA-slope grid-reset trigger threshold scales with the ceiling, so it rises proportionally. TradingView/grid-reset simulator fallbacks and the research-doc default follow the canonical constant; per-bot `amaSlope.maxSlopePct` overrides still win. Behavioral default change for bots without an explicit override. Covered by `test_grid_reset_sim`, `test_ama_slope_model` and `test_market_adapter_logic`.
48
+
49
+ - **Fix(guard)**: last-fill guard blocks only higher buys and lower sells — the guard judged placements against a price band around the last fill and never read the fill's side, so it blocked profitable placements within half an increment of the fill (exactly where spread correction places) and blocked buy-backs *below* a SELL fill. It is replaced by the direction rule `BUY blocked at/above the pivot`, `SELL blocked at/below the pivot` in `modules/order/utils/system.ts` (equal price stays blocked to prevent the immediate re-fill loop; a cold pivot or unrecorded fill side still disables the guard). The increment no longer participates but stays in the signature so call sites and logs are unchanged, and `LastFillGuardResult` drops `halfInc`. Live impact: a sweep no longer freezes spread repair for the rest of the band. Covered by a rewritten `tests/test_last_fill_guard.ts` plus re-solved invariants in `tests/test_grid_price_invariant_wiring.ts`.
50
+
51
+ - **Fix(spread)**: plan only placeable tightening slots and name the stalls — the correction planned candidates the broadcast guard was guaranteed to drop, because its crossing floor preferred a fresh live read over the fill anchor and had no planner-side last-fill filter. `passesLastFill` (exported next to `resolveLastFillGuardReference` and reused by the COW runtime, so planner and guard cannot resolve different pivots) is now applied to every candidate pool and boundary promotion before the quota slice; an empty side is reported as the `last-fill-blocked` stall and survives the starvation-fallback merge instead of collapsing to no-candidates; a rail reservation above the chain free balance is named and flagged `OVERSUBSCRIBED`; and the out-of-spread clock is cleared only after sustained tolerance or a placement, with the fund and geometry escalations on their own windows. The crawl-ledger drop log now carries side split, net, age and boundary delta. Files: `order/utils/system.ts`, `order/grid.ts`, `dexbot_cow_runtime.ts`, `dexbot_maintenance_runtime.ts`, `order/manager.ts`, `constants.ts`, `types.ts`, `dexbot_class.ts`; covered by new `tests/test_spread_last_fill_planning.ts` and updated `test_spread_market_reference`, `test_stale_grid_hardening`, `test_dexbot_maintenance_runtime_dynamic_weights`, `test_targeted_drift_reconcile`.
52
+
53
+ - **Fix(spread)**: fund from chain truth and re-anchor the boundary from the fill — two self-referential calculations could only be broken from outside. (1) The budget vetoed its own placement: `available = chainFree − virtual` then spends it on that same projection, so a rail sized from a larger balance (or from resting inventory) can leave `available` at 0 forever; `deriveChainTruthFundBudget` (`order/utils/math.ts`) re-derives the budget for a known candidate set as `min(chainFree, min(virtual, Σ candidate ideals))`, bounded on both sides and still rejected at broadcast if over-committed, while a zero caused by fees or an empty balance is honoured unchanged. (2) A boundary crawl is ±1 slot per committed fill, so once a sweep leaves the window behind the fill no tightening slot can be placed and the stranded orders cannot rotate down either; `reanchorBoundaryFromLastFill` (`order/utils/system.ts`, applied from `calculateTargetGrid`) anchors the fill (`SELL` fill at slot f → boundary ≥ f − gapSlots; `BUY` fill at slot f → boundary ≤ f − 1), fail-closed on fill provenance, on-ladder price and `validatePersistedBoundary`. A per-fill pair ledger was rejected on purpose: sizes must follow the side budget, and a SELL fill returns quote while the same-side repair needs base. Covered by `tests/test_chain_truth_funding.ts` and `tests/test_boundary_fill_reanchor.ts`; documented in the architecture, COW invariant and fund-movement docs plus retrospective §9.9.
54
+
55
+ - **Fix(crawls)**: consume only the owed fill crawls a derivation applied — the pending-crawl ledger records one relative boundary delta per shift-eligible fill because the batch that sees a fill may not commit a boundary, but the derivation folds only a subset (own-batch slots are deduped, edge slots never crawl, the cross-chunk cap bounds one plan) while the commit cleared *all* of it, so an owed record the derivation could not apply vanished. Live signature: seven fills swept slots and two commits each dropped owed crawls, leaving the boundary seven levels behind and the sell window below the last sale. `deriveTargetBoundary` now returns `consumedCrawlIds` (applied records plus the ones deliberately never counted; a capped fold consumes a same-side prefix so the remainder stays owed exactly once), the plan carries it through `buildSuccessResult` → `CowResult` → both `_commitWorkingGrid` call sites, and `_consumePendingFillCrawls` drops exactly those records (matched by `slotId` + `ts`) while logging `Dropped N … kept=M`. A commit without the wire consumes nothing; `_clearPendingFillCrawls` keeps its explicit allowed-loss meaning. The recorder still dedupes per slot and caps the ledger at 500, so no age cap is needed. Covered by new `tests/test_crawl_ledger_consumption.ts` plus updated pending-fill and market-scenario tests.
56
+
57
+ - **Fix(restart)**: verify the master password before stopping the credential daemon — a failed `dexbot restart` used to stop the live daemon first and then abort on a wrong or cancelled password, leaving every bot without key access until a later successful start. Both restart-all paths (monolithic and isolated supervisor) now authenticate first and only stop the existing daemon once the secret is verified, handing the verified secret to `ensureCredentialDaemon` so it does not prompt twice; a failed authentication exits non-zero without touching the daemon or signalling the runtime. Files: `unlock.ts`, `modules/launcher/credential_daemon.ts` (`authenticateCredential`, optional pre-verified `vaultSecret`); covered by `tests/test_restart_password_gate.ts`.
58
+
59
+ - **Refactor(restart)**: type the vault secret and clear it after daemon handoff — the pre-verified secret was typed `unknown` and the launcher-side reference stayed live until the restart block ended. `VaultSecret` is now exported from `chain_keys` and used by the restart/daemon-start APIs, and `clearVaultSecret` is called in a `finally` covering every startup path (successful bootstrap handoff, spawn/startup failure, bootstrap server creation failure, bootstrap path-file write failure), with both restart paths clearing the caller's reference even if daemon startup throws. A caller-supplied `vaultSecret` is documented as consumed and must not be reused. Nothing is persisted: the secret stays in process memory, is never logged or written to disk, and hex strings cannot be zeroed in place in V8, so the helper nulls the fields and lets GC reclaim them. Covered by `test_restart_password_gate` and `test_credential_daemon_controller_output`.
60
+
61
+ - **Fix(credit)**: value LP-share collateral at the pool market price — `dexbot credit` and the runtime's conversion-rate resolver used the offer's fixed `acceptable_collateral` price for liquidity-pool share collateral, which is a contract haircut and can go stale, so the reported CR was false for LP shares (e.g. 1.111 instead of the pool-based 1.399). New `selectCollateralConversionRate()` (`modules/credit_pricing.ts`) prefers the live pool value for LP shares and otherwise keeps the offer price first with the pool rate as fallback; `scripts/analyze-credit.ts` uses it and tags `Avar. CR` rows with `pool`/`offer` while keeping the active deal's offer for `Curr. CR`, and `_resolveCreditConversionRate()` (`modules/credit_runtime.ts`) is pool-first for LP shares so collateral distribution matches the borrow gate. LP-share CR uses pure pool reserves/supply with no fee or slippage deduction; non-LP collateral is unchanged, and multi-item groups sharing an LP collateral now split at market-value CR. Covered by `test_credit_pricing`, `test_analyze_credit`, `test_credit_conversion_fallback` and `test_credit_runtime`.
62
+
5
63
  ## [1.6.16] - 2026-10-18 - Monolithic Per-Bot Control Routing, Candle-Cache Orientation Sharing, Chart Redraw Performance, Adapter Whitelist Sync, `dexbot rich` Symbol Canonicalization
6
64
 
7
65
  ### 2026-10-18
@@ -1,6 +1,6 @@
1
1
  # Analysis
2
2
 
3
- Tools that inspect DEXBot trading behavior and the market data it operates on. Output is interactive HTML charts written to `charts/` (regenerated on each run, not committed); none of this runs in production.
3
+ Tools that inspect DEXBot trading behavior and the market data it operates on. Output is mostly interactive HTML charts written to `charts/` (regenerated on each run, not committed) and JSON results under `results/`; the trade analyzers can also export CSV/JSON to a caller-supplied path. The runners are research-only, but their shared chart and bot-key helpers are imported by the production market adapter.
4
4
 
5
5
  ## Contents
6
6
 
@@ -22,7 +22,7 @@ Tools that inspect DEXBot trading behavior and the market data it operates on. O
22
22
  |------|----------------|------------------|
23
23
  | [`trade_profitability.ts`](#trade-profitability-analyzer-trade_profitabilityts) | "Is my bot making money?" — PnL, R-multiples, drawdown | `npm run analysis:trade-pnl -- <account-id>` |
24
24
  | [`dexbot pnl`](#pnl-html-report-dexbot-pnl) | "Give me a readable PnL report" — self-contained HTML with a lot table | `dexbot pnl <bot\|account> --month 3` |
25
- | [`grid_correction_check.ts`](#last-fill-guard-check-grid_correction_checkts) | "Are fills respecting the pivot ± half-increment guard?" | `npm run analysis:grid-check -- --bot-key <bot-key>` |
25
+ | [`grid_correction_check.ts`](#last-fill-guard-check-grid_correction_checkts) | "Are fills respecting the direction-only last-fill guard?" | `npm run analysis:grid-check -- --bot-key <bot-key>` |
26
26
  | [`analyze_risk_profile.ts`](#risk-profile-analyzer-analyze_risk_profilets) | "How wide should my Safe Range clamps be?" | `node dist/analysis/analyze_risk_profile.js --bot-key <bot-key>` |
27
27
  | [`analyze_trade_heatmap.ts`](#trade-heatmap-analyze_trade_heatmapts) | "Where did trade volume cluster vs the AMA?" | `node dist/analysis/analyze_trade_heatmap.js --bot-key <bot-key>` |
28
28
  | [`tradingview/analyze_tradingview.ts`](#tradingview-chart-tradingviewanalyze_tradingviewts) | "Just give me a candle chart" | `dexbot tv <bot-key>` |
@@ -76,14 +76,14 @@ node dist/analysis/analyze_dynamic_weight.js --bot-key <bot-key>
76
76
  npm run analysis:trade-pnl -- 1.2.123456 --hours 168
77
77
  ```
78
78
 
79
- > The market adapter source reads from `market_adapter/state/market_adapter_centers.json` — run the bot first to populate state.
79
+ > The market adapter source prefers the bot's cached candle file and falls back to `market_adapter/state/market_adapter_centers.json` — run the bot first to populate state.
80
80
  > Prefer the `npm run analysis:*` shortcuts; they wrap the compiled runners with the same flags (see [npm Script Shortcuts](#npm-script-shortcuts) for the full mapping).
81
81
 
82
82
  ## Data Prerequisites
83
83
 
84
84
  Most runners expect candle data. Two paths to get it:
85
85
 
86
- **Market adapter source** (default for most runners) — reads from `market_adapter/state/market_adapter_centers.json`. No setup needed; just run the bot first to populate state.
86
+ **Market adapter source** (default for most runners) — resolves the bot's cached candle file first, then falls back to `market_adapter/state/market_adapter_centers.json`. No setup needed; just run the bot first to populate state.
87
87
 
88
88
  **LP candle files** — for deeper analysis with full OHLC data:
89
89
 
@@ -258,9 +258,11 @@ All amounts use the shared 4-significant-figure formatter (compact `K`/`M`, sign
258
258
 
259
259
  ### LAST-FILL-GUARD Check (`grid_correction_check.ts`)
260
260
 
261
- Validates LAST-FILL-GUARD discipline from the same Kibana fill pipeline as `trade_profitability.ts`. For a previous fill at price `x` and grid increment `i`, the next order must satisfy `BUY < x × (1 − i/2/100)` and `SELL > x × (1 + i/2/100)`, regardless of the previous fill's side. A violation is a buy or sell fill inside the prohibited half-increment band around its pivot.
261
+ Validates LAST-FILL-GUARD discipline from the same Kibana fill pipeline as `trade_profitability.ts`. The rule is **direction only** (v1.6.16+): with the previous fill at price `p`, the next order must satisfy `BUY < p` and `SELL > p` (equal price is blocked — a re-place at the just-filled level). There is no increment band: the older `pivot ± i/2` rule blocked a BUY below a SELL fill and a SELL one tick above our cost, i.e. it flagged the tightening placements the engine legitimately makes. A violation is a buy fill at/above its pivot or a sell fill at/below it.
262
262
 
263
- **Pipeline:** Kibana `fill_order` query (paginated `search_after`) → on-chain asset precision resolution → buy/sell classification → chronological sort → per-order/price-epoch aggregation (partial fills at one price collapsed to weighted-average; repriced order lifetimes kept separate) → consecutive pivot-band comparison → violation report with daily histogram.
263
+ **Offline limits:** the tool reconstructs pivots from consecutive fills, so it cannot see the runtime's edge-pinned-fill exclusion (no slot identity per fill) nor the spread-correction bypass — expect rare false positives on wick/insurance fills.
264
+
265
+ **Pipeline:** Kibana `fill_order` query (paginated `search_after`) → on-chain asset precision resolution → buy/sell classification → chronological sort → per-order/price-epoch aggregation (partial fills at one price collapsed to weighted-average; repriced order lifetimes kept separate) → consecutive direction comparison → violation report with daily histogram.
264
266
 
265
267
  ```bash
266
268
  # Per-order aggregated check (default), last 7 days
@@ -272,7 +274,7 @@ npm run analysis:grid-check -- --bot-key <bot-key> --hours 720 --json out.json -
272
274
  # Raw fill granularity instead of per-order aggregation
273
275
  npm run analysis:grid-check -- --bot-key <bot-key> --per-fill --hours 168
274
276
 
275
- # Override the bot's configured grid increment
277
+ # Override the bot's configured grid increment (informational: the guard has no band)
276
278
  npm run analysis:grid-check -- --bot-key <bot-key> --hours 168 --increment 0.5
277
279
  ```
278
280
 
@@ -287,10 +289,9 @@ Exit code `0` = pass, `2` = violations found, `1` = fatal error. Bot keys resolv
287
289
  | `--start <iso>` / `--end <iso>` | — | Absolute time window |
288
290
  | `--account <id>` | bot `preferredAccount` | Override account ID or name |
289
291
  | `--refresh-account` | off | Force re-resolution of `preferredAccount` and update the stored `accountId` when it changed |
290
- | `--increment <pct>` | bot config / `0.5` | Grid increment used to derive the half-increment guard band |
292
+ | `--increment <pct>` | bot config / `0.5` | Grid increment (informational only — the guard is direction-only and uses no band) |
291
293
  | `--per-fill` | off | Check at fill granularity instead of per-order aggregated |
292
294
  | `--include-cross-pair` | off | Also check consecutive fills across different pairs |
293
- | `--tolerance <pct>` | — | Deprecated compatibility alias for `--increment`; its value is doubled and a warning is emitted |
294
295
  | `--json <file>` / `--csv <file>` | — | Export violations |
295
296
  | `--verbose` | off | Print the fetched trade sequence before checking |
296
297
  | `--list-bots` | — | List available bot keys and exit |
@@ -10,7 +10,7 @@ parameters into `profiles/market_profiles.json` for the market adapter.
10
10
 
11
11
  ```
12
12
  1. fetch_lp_candles.ts → market_adapter/data/lp/<pairFolder>/lp_pool_<poolShort>_<interval>.json
13
- 2. optimizer_high_resolution.ts → optimization_results_*.json
13
+ 2. optimizer_high_resolution.ts → analysis/results/optimization_results_*.json
14
14
  → profiles/market_profiles.json (only with --write-profiles)
15
15
  3. scripts/generate_lp_chart.ts → market chart + comparison chart (visual review)
16
16
  - LP chart: `npm run lp:chart -- --data <lp-export.json>`
@@ -156,7 +156,7 @@ Source: pool 133 `IOB.XRP/BTS`, 1h candles, 2023-04-12 00:00 UTC through
156
156
  2026-04-11 23:00 UTC (the working-tree dataset `analysis/ama_fitting/data/lp_pool_133_iob.xrp_bts_1h.json`, regenerated by a local `fetch_lp_candles.ts` run).
157
157
 
158
158
  **Outputs:**
159
- - `analysis/ama_fitting/optimization_results_<datafile>_w<λ1>_<λ2>_<λ3>_<λ4>.json` — full results (e.g. `_w0_0031_0_0025_0_00185_0_0013`)
159
+ - `analysis/results/optimization_results_<datafile>_w<λ1>_<λ2>_<λ3>_<λ4>.json` — full results (e.g. `_w0_0031_0_0025_0_00185_0_0013`)
160
160
  - `analysis/charts/optimization_chart_<datafile>_w<λ1>_<λ2>_<λ3>_<λ4>.html` — interactive AMA overlay chart (auto-generated)
161
161
  - `profiles/market_profiles.json` — updated with new AMA parameters per pair only when `--write-profiles` is used
162
162
 
@@ -1,6 +1,6 @@
1
1
  ## Bot Fitting Backtest
2
2
 
3
- This folder contains parameter sweep backtests that simulate grid fills for the four AMA winners from `analysis/ama_fitting`.
3
+ This folder contains parameter sweep backtests that simulate grid fills for the four AMA winners produced by the optimizer in `analysis/ama_fitting/` (results land in `analysis/results/`).
4
4
 
5
5
  ### What it optimizes
6
6
 
@@ -74,7 +74,7 @@ microstructure, and no consolidation/dust-cancel/COW/collision mechanics.
74
74
  Both scripts require:
75
75
 
76
76
  - **LP candles JSON** (recommended 1h), from `market_adapter/data/lp/` — pass via `--data`
77
- - **AMA optimization winners JSON**, from `analysis/ama_fitting/` — for `backtest_ama_sweep.ts`, pass via `--results`
77
+ - **AMA optimization winners JSON**, from `analysis/results/` — for `backtest_ama_sweep.ts`, pass via `--results`
78
78
 
79
79
  ### Run
80
80
 
@@ -99,7 +99,7 @@ node dist/analysis/bot_fitting/backtest_lookback_drawdown.js \
99
99
  > builds on it and reports the paired per-lookback deltas.
100
100
 
101
101
  > `backtest_bot_fitting.ts` auto-derives `--results` from the `--data` filename
102
- > (`analysis/ama_fitting/optimization_results_<base>_w<λ1>_<λ2>_<λ3>_<λ4>.json`,
102
+ > (`analysis/results/optimization_results_<base>_w<λ1>_<λ2>_<λ3>_<λ4>.json`,
103
103
  > newest `_w*` file matching the base name; falls back to the legacy
104
104
  > `optimization_results_<base>.json`) when omitted.
105
105
  > `backtest_ama_sweep.ts` requires `--results` explicitly.
@@ -111,7 +111,7 @@ node dist/analysis/tradingview/analyze_tradingview.js \
111
111
  1. Reads `profiles/bots.json` to find the bot's `assetA`, `assetB`, and `ama` settings.
112
112
  2. Resolves the candle file at `market_adapter/data/market_adapter_<bot-key>_1h.json`.
113
113
  3. Looks up the matching market profile in `profiles/market_profiles.json` for AMA defaults.
114
- 4. AMA settings priority: bot-specific `ama` object > market profile > constants (AMA3, slowPeriod 83.6).
114
+ 4. AMA settings priority: bot-specific `ama` object > market profile > constants (AMA3, slowPeriod 83.5).
115
115
 
116
116
  > The candle file must exist — run the market adapter LP exporter first if needed (see [Getting Blockchain Data](#getting-blockchain-data)).
117
117
 
@@ -189,7 +189,7 @@ Indicator on/off state is not a generation-time flag: `SMA`, `VWMA`, `AMA`, `Ran
189
189
  | `--sma-period <n>` | SMA period | `500` |
190
190
  | `--ama-er-period <n>` | AMA ER period | `781` |
191
191
  | `--ama-fast-period <n>` | AMA fast period | `5.2` |
192
- | `--ama-slow-period <n>` | AMA slow period | `83.6` |
192
+ | `--ama-slow-period <n>` | AMA slow period | `83.5` |
193
193
  | `--vwap-bars <n>` | Rolling VWMA window | `500` |
194
194
  | `--no-sma` | Disable SMA | — |
195
195
  | `--no-vwap` | Disable VWMA | — |
@@ -166,7 +166,7 @@ All panels share aligned vertical time grid lines, and the bottom output panel s
166
166
  |------|-------|---------|---------|
167
167
  | **nz%** | 0–1 | 0.00 | Neutral zone: dead-band below which offset is forced to 0 |
168
168
  | **lb** | 4–32 | 16 | Logarithmic. Lookback bars for AMA slope calculation |
169
- | **amaS%** | 0.06–0.12 | 0.09 | Logarithmic. Gear ratio for per-bar AMA slope saturation |
169
+ | **amaS%** | 0.06–0.12 | 0.1 | Logarithmic. Gear ratio for per-bar AMA slope saturation |
170
170
  | **kalS%** | 0.75–1.5 | 1.2 | Logarithmic. Gear ratio for Kalman composite saturation |
171
171
  | **clip%** | 0–20 | 10 | Percentile clip: filters extreme inputs (0 = off) |
172
172
 
package/claw/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "dexbot2-claw",
3
- "version": "1.6.16",
3
+ "version": "1.6.18",
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.16",
5
+ "version": "1.6.18",
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.16",
4
+ "version": "1.6.18",
5
5
  "type": "module",
6
6
  "main": "index.js"
7
7
  }
@@ -177,11 +177,13 @@ function generateChartHtml(results, metricCache, fixEr, fixFast, dataLabel) {
177
177
  const move = results.map((r) => r.movement);
178
178
  const cacheSlow = metricCache.map((m) => m.slow);
179
179
  const cacheMove = metricCache.map((m) => m.movement);
180
+ // Current built-in presets: AMA1 is the λ=0.0031 fit, AMA2–AMA4 follow the
181
+ // exact −9%/step effective-smoothing ladder (see MARKET_ADAPTER.AMAS).
180
182
  const amaAnnotations = [
181
183
  { label: 'AMA1', lambda: 0.0031, slow: 62.1, color: '#ef5350' },
182
- { label: 'AMA2', lambda: 0.0025, slow: 72.0, color: '#fb8c00' },
183
- { label: 'AMA3', lambda: 0.00185, slow: 83.6, color: '#5c9ee6' },
184
- { label: 'AMA4', lambda: 0.0013, slow: 96.9, color: '#26a69a' },
184
+ { label: 'AMA2', lambda: 0.0025, slow: 71.5, color: '#fb8c00' },
185
+ { label: 'AMA3', lambda: 0.00185, slow: 83.5, color: '#5c9ee6' },
186
+ { label: 'AMA4', lambda: 0.0013, slow: 99.3, color: '#26a69a' },
185
187
  ].filter(a => a.lambda >= xs[0] && a.lambda <= xs[xs.length - 1]);
186
188
  return `<!DOCTYPE html>
187
189
  <html lang="en">
@@ -8,7 +8,7 @@
8
8
  */
9
9
  import type { SourceConfig } from './resolve_source.js';
10
10
  /** Fields every analysis CLI config shares. */
11
- export interface AnalysisBaseConfig {
11
+ interface AnalysisBaseConfig {
12
12
  source: {
13
13
  type: string;
14
14
  config: SourceConfig;
@@ -40,4 +40,5 @@ export declare function printHelpHeader(title: string, usagePath: string): void;
40
40
  * `width` is per-tool so adopting this helper keeps the original column.
41
41
  */
42
42
  export declare function helpRow(flag: string, description: string, width: number): string;
43
+ export {};
43
44
  //# sourceMappingURL=analyze_args.d.ts.map
@@ -17,13 +17,6 @@ interface FillRecord {
17
17
  }
18
18
  declare function assetSymbol(id: string): string;
19
19
  declare function assetPrec(id: string): number | undefined;
20
- declare function toReal(amount: number, assetId: string): number;
21
- /**
22
- * A fill needs strictly positive, finite amounts on both legs. A zero base
23
- * amount would produce an infinite price (quoteAmount / 0) that poisons
24
- * downstream inventory lots and PnL aggregates.
25
- */
26
- declare function isValidFillAmounts(baseAmount: number, quoteAmount: number): boolean;
27
20
  /** Match a user-supplied pair leg against a chain asset id or its symbol. */
28
21
  declare function matchesAssetRef(ref: string, assetId: string): boolean;
29
22
  interface ClassifiedFill {
@@ -55,5 +48,5 @@ declare function classifyFill(f: FillRecord): ClassifiedFill | null;
55
48
  declare function resolveAssetPrecisions(fills: FillRecord[]): Promise<void>;
56
49
  /** Fetch every fill_order for an account in [gte, lte], paginated via search_after. */
57
50
  declare function fetchAllFills(config: Record<string, unknown>, accountId: string, gte: string, lte: string): Promise<FillRecord[]>;
58
- export { BTS_ID, assetSymbol, assetPrec, toReal, isValidFillAmounts, matchesAssetRef, classifyFill, resolveAssetPrecisions, fetchAllFills, FillRecord, ClassifiedFill, };
51
+ export { BTS_ID, assetSymbol, assetPrec, matchesAssetRef, classifyFill, resolveAssetPrecisions, fetchAllFills, FillRecord, };
59
52
  //# sourceMappingURL=fills_source.d.ts.map
@@ -255,5 +255,5 @@ async function fetchAllFills(config, accountId, gte, lte) {
255
255
  }
256
256
  return fills;
257
257
  }
258
- export { BTS_ID, assetSymbol, assetPrec, toReal, isValidFillAmounts, matchesAssetRef, classifyFill, resolveAssetPrecisions, fetchAllFills, };
258
+ export { BTS_ID, assetSymbol, assetPrec, matchesAssetRef, classifyFill, resolveAssetPrecisions, fetchAllFills, };
259
259
  //# sourceMappingURL=fills_source.js.map
@@ -22,22 +22,25 @@ interface Violation {
22
22
  priceDelta: number;
23
23
  priceDeltaPct: number;
24
24
  pivot: number;
25
+ /** Direction-only rule has no band; kept at 0 so the JSON/CSV shape is stable. */
25
26
  halfInc: number;
27
+ /** The pivot itself (BUY must be below / SELL above it). */
26
28
  threshold: number;
27
29
  }
28
30
  /**
29
- * LAST-FILL-GUARD helper — pivot ± halfIncrement (replaces price-tolerance).
30
- * last fill @x with increment i: BUY < x*(1 - i/2/100), SELL > x*(1 + i/2/100)
31
- * e.g. x=1000, i=0.5% => BUY < 997.5, SELL > 1002.5
32
- * Cold (pivot null or lastType null) => disabled.
31
+ * LAST-FILL-GUARD helper — DIRECTION ONLY relative to the last fill price.
32
+ * BUY blocked if price >= pivot
33
+ * SELL blocked if price <= pivot
34
+ * e.g. pivot 1000 => BUY must be < 1000, SELL must be > 1000
35
+ * Cold (pivot null or lastType null) => disabled. Equal price stays blocked
36
+ * (a re-place at the just-filled level).
33
37
  * @param {number} price - Target order price
34
38
  * @param {string} type - buy/sell
35
39
  * @param {number|null} lastPrice - Most recent fill price
36
40
  * @param {string|null} lastType - Most recent fill side (buy/sell)
37
- * @param {number|any} incrementPercent - Grid increment percent (e.g. 0.5). If not finite/<=0 falls back to DEFAULT_CONFIG.
38
41
  * @returns {{blocked: boolean, pivot: number|null, halfInc: number, threshold: number|null}}
39
42
  */
40
- declare function isLastFillGuardBlocked(price: unknown, type: unknown, lastPrice: unknown, lastType: unknown, incrementPercent: unknown): {
43
+ declare function isLastFillGuardBlocked(price: unknown, type: unknown, lastPrice: unknown, lastType: unknown): {
41
44
  blocked: boolean;
42
45
  pivot: number | null;
43
46
  halfInc?: number;