dexbot 1.6.14 → 1.6.15

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 +34 -4
  2. package/analysis/README.md +6 -6
  3. package/analysis/tradingview/README.md +2 -1
  4. package/claw/README.md +7 -7
  5. package/claw/package.json +1 -1
  6. package/claw/runtimes/openclaw-plugin/openclaw.plugin.json +1 -1
  7. package/claw/runtimes/openclaw-plugin/package.json +1 -1
  8. package/dist/analysis/tradingview/tradingview_uplot_chart_generator.js +80 -6
  9. package/dist/analysis/trend_detection/dynamic_weight_chart_generator.js +36 -2
  10. package/dist/dexbot.js +23 -3
  11. package/dist/market_adapter/core/strategies/dynamic_weight_series.js +26 -11
  12. package/dist/modules/account_bots.d.ts +3 -0
  13. package/dist/modules/account_bots.js +3 -0
  14. package/dist/modules/bitshares-native/subscriptions.js +1 -1
  15. package/dist/modules/bot_defaults.d.ts +13 -2
  16. package/dist/modules/bot_defaults.js +31 -2
  17. package/dist/modules/bot_settings.js +3 -0
  18. package/dist/modules/constants.d.ts +6 -0
  19. package/dist/modules/constants.js +24 -0
  20. package/dist/modules/credit_runtime.d.ts +35 -5
  21. package/dist/modules/credit_runtime.js +219 -38
  22. package/dist/modules/dexbot_class.d.ts +19 -1
  23. package/dist/modules/dexbot_class.js +58 -20
  24. package/dist/modules/dexbot_cow_runtime.js +19 -18
  25. package/dist/modules/dexbot_fill_runtime.d.ts +1 -1
  26. package/dist/modules/dexbot_fill_runtime.js +4 -7
  27. package/dist/modules/dexbot_maintenance_runtime.d.ts +7 -2
  28. package/dist/modules/dexbot_maintenance_runtime.js +52 -7
  29. package/dist/modules/dexbot_startup_runtime.js +3 -2
  30. package/dist/modules/dexbot_state_recovery.js +1 -1
  31. package/dist/modules/order/export.js +2 -2
  32. package/dist/modules/order/grid.d.ts +118 -1
  33. package/dist/modules/order/grid.js +292 -50
  34. package/dist/modules/order/grid_reconcile.js +4 -3
  35. package/dist/modules/order/grid_reconcile_internal.js +13 -18
  36. package/dist/modules/order/index.d.ts +3 -1
  37. package/dist/modules/order/manager.d.ts +1 -0
  38. package/dist/modules/order/manager.js +5 -14
  39. package/dist/modules/order/sync_engine.js +18 -9
  40. package/dist/modules/order/utils/math.d.ts +98 -26
  41. package/dist/modules/order/utils/math.js +177 -57
  42. package/dist/modules/order/utils/order.js +16 -4
  43. package/dist/modules/order/utils/system.js +2 -2
  44. package/dist/modules/order/utils/validate.d.ts +1 -1
  45. package/dist/modules/order/utils/validate.js +48 -58
  46. package/dist/modules/types.d.ts +7 -0
  47. package/dist/scripts/analyze-credit.js +44 -27
  48. package/dist/scripts/diagnose-pool-history.js +35 -30
  49. package/dist/scripts/pnl.js +1 -1
  50. package/dist/scripts/rich_list.d.ts +18 -0
  51. package/dist/scripts/rich_list.js +461 -0
  52. package/dist/scripts/run-tests.js +80 -4
  53. package/dist/unlock.d.ts +2 -1
  54. package/dist/unlock.js +4 -3
  55. package/docs/COW_INVARIANTS.md +6 -0
  56. package/docs/DEXBOT_COMPARISON.md +6 -6
  57. package/docs/EVOLUTION.md +10 -9
  58. package/docs/FUND_MOVEMENT_AND_ACCOUNTING.md +1 -1
  59. package/docs/LOGGING.md +16 -1
  60. package/docs/MPA_CREDIT_USAGE.md +10 -5
  61. package/docs/ORDER_ENGINE_POST_1.0_RETROSPECTIVE.md +159 -9
  62. package/docs/README.md +1 -1
  63. package/docs/WORKFLOW.md +1 -0
  64. package/docs/architecture.md +56 -2
  65. package/docs/developer_guide.md +5 -1
  66. package/market_adapter/README.md +4 -4
  67. package/modules/README.md +1 -1
  68. package/package.json +2 -1
  69. package/scripts/README.md +59 -32
  70. package/tests/README.md +11 -2
package/CHANGELOG.md CHANGED
@@ -2,6 +2,36 @@
2
2
 
3
3
  All notable changes to this project will be documented in this file.
4
4
 
5
+ ## [1.6.15] - 2026-10-16 - Spread-Correction Resilience, Credit Renewal Free-Collateral Top-Up, Price-vs-Amount Level Identity, TradingView Chart Fixes & Data-Age Badge, `dexbot rich`, Parallel Test Runner
6
+
7
+ ### 2026-10-16
8
+
9
+ - **Fix(order)**: keep grid level identity price-based, not amount-based — a bot on a low-precision quote asset (precision 4) placed only one of 20 sells and collapsed its outside→center pairing, because `priceSlotEqual(price, price, assetPrecision)` rounded a PRICE through an asset AMOUNT precision: 0.000318 and 0.000343 both round to 3, so every adjacent level looked like the same level and every CREATE after the first was rejected as a collision. The overloaded helper is replaced by three explicit identities: `pricesOnSameLevel` (chain-representable tolerance, min across both types, now clamped to half a grid step so a dust-inflated tolerance cannot merge adjacent levels) for any chain-derived price, exact `sameGridPrice` for grid-vs-grid, and genesis-aware `sameGridLevel` (falls back to `sameGridPrice` out of rail). Every production call site is repointed, `isChainPriceOutOfGrid` excuses only genuine float dust at the rail edge (capped chain tolerance) instead of a whole below-rail dip-protection band, and the test-only `findPriceCollision` is deleted. Covered by `tests/test_price_collision_guard.ts`, `tests/test_sync_out_of_grid_defer.ts` and `tests/test_validate_create_target_slots.ts`.
10
+
11
+ - **Fix(order)**: harden spread correction against concurrent plan invalidation — a plan invalidated between planning and commit (a concurrent fill rebalance advanced the master version or took the destination slot) was refused fail-closed, and an out-of-spread grid cannot self-heal because it produces no fill to re-plan, so the bot stayed stale. `checkSpreadCondition` now holds the refcounted broadcast region across the whole plan/broadcast/retry loop (released in `finally`); `getOccupiedCorrectionSlots`/`resolveOccupiedCorrection` re-derive or withhold a plan whose CREATE destination was taken; a transient refusal triggers a bounded `replanSpreadCorrectionFromFreshMaster` (`TIMING.SPREAD_CORRECTION_MAX_ATTEMPTS`, default 2); `trackOutOfSpreadStaleness` tolerates transient refusals up to `TIMING.SPREAD_STALE_TRANSIENT_GRACE` before escalating to a re-center; and opt-in backlog coalescing (`fillProcessing.COALESCE_BACKLOG_REPLAY`, default off) is added. New P0 counters (`spreadCorrectionRefusedCount`, per-cause `spreadCorrectionRefusalCauses`, `spreadCorrectionRetryCount`) surface via `getMetrics()`, and the uncertain-broadcast adopt-or-defer invariant is recorded (INV-COW-010). Covered by `tests/test_spread_correction_resilience.ts` plus a settings-merge override contract.
12
+
13
+ - **Feat(credit)**: top up renewals from free collateral — a renewal previously capped the reborrow at the collateral released by the repay, so it scaled the principal down when the offer's collateral price moved even while idle collateral of the same asset was held. `useFreeCollateral` (default true, per lending item) adds the borrower's free balance of the collateral asset to the renewal budget, bounded by the position's `assignedCollateralBudget`; the accept builder treats an explicit collateral amount as a floor and tops it up to what the borrow requires while the borrow stays clamped to the budget. Deferred reborrows re-read the live free balance and position budget per retry, and the free-balance read is skipped when the released collateral already backs the reborrow. `useFreeCollateral: false` opts back into the released-only ceiling. Behavioral caveat: a renewal can now lock idle collateral, including an asset also used by the grid. Covered by new credit-runtime stages for top-up, opt-out, budget cap, switch-flow and replay refresh.
14
+
15
+ - **Feat(credit)**: report Avar. CR per borrowed credit — the single Avar. CR line value-weighted every priced deal together, so unrelated debt assets (e.g. a BTS borrow and an MPA borrow) were blended into one figure that matched neither obligation. Priced support rows are now grouped by debt asset with one value-weighted average per group, ordered by borrowed amount (largest exposure first); collateral legs within a borrowed credit still join on one line. The unused global `avgCr` is dropped (the blank-line guard simplifies to `supportedRows.length > 0`). Display-only change to `scripts/analyze-credit.ts`.
16
+
17
+ - **Fix(config)**: exclude legacy order-key aliases from the draft seed — pre-rename `activeOrders`/`reserveOrders` keys survive in `DEFAULT_CONFIG` of settings files written before the `coreOrders`/`edgeOrders` rename, and `mergeSettings` propagates them into the loaded defaults, failing the parity guard on an unclassified key. Both aliases are added to `DRAFT_EXCLUDED_KEYS` while `migrateLegacyOrderKeys` still migrates them away, so older files pass without hiding genuinely new keys.
18
+
19
+ - **Feat(cli)**: add a per-asset rich list (`dexbot rich`) — a read-only utility printing top holders of one or more assets via the chain `asset_api` (`get_asset_holders`), exposed as `dexbot rich <asset...> [--top N] [--json|--csv]` with a `richlist` npm script. It connects only to nodes that expose `asset_api` to anonymous logins, clamps `--top` to the node's advertised `api_limit_get_asset_holders`, and retries unresolved legacy `bit*` MPA names with the prefix stripped. Source-checkout-only and intentionally not advertised in the root README.
20
+
21
+ - **Fix(scripts)**: make the pool-history diagnostic fail fast and exit cleanly — `--pool` is validated against the `1.19.N` object-ID shape up front (clear message, exit 1) instead of issuing doomed RPCs that surfaced an opaque remote `uint64_t` parse error; the two invalid account-history tests are replaced by a real `get_liquidity_pool_history_by_sequence` pagination test; and `process.exit(0)` after disconnect stops the native transport's reconnect timers from hanging the script.
22
+
23
+ - **Feat(ui)**: TradingView exporter fixes and a live data-age badge — restore the accidentally dropped `1h` timeframe (aggregation stays keyed by seconds, so the `seconds >= baseIntervalSeconds` guard disables it on coarser bases); resolve the default timeframe from `payload.defaultTimeframe` in the page script (the generation-time identifier threw `ReferenceError` and drew nothing); sort candles by bucket time once at the entry point (three consumers assume ascending order) with a warn on an actual reorder; drop the noisy `· volume · uPlot` subtitle tail; and embed the newest-candle freshness anchor plus `intervalSeconds` so a readout beside the title recomputes the age every minute, fully offline (green under 24h, amber 1-7 days, red over a week). Also brighten the dynamic-weight research-panel labels and add a 16-knob factory reset button that reuses `applyParams()`.
24
+
25
+ - **Fix(bot)**: return to the Actions menu after saving a new bot — the New bot flow looped back into `promptBotData` after a successful save, immediately opening another blank Bot Editor that read as a duplicate window and hid the fact the previous bot was saved. Only the success path changes; Cancel/Esc and invalid-input paths already exited the loop.
26
+
27
+ - **Fix(order)**: treat empty-string boundary/gap as unknown geometry in the last `''`-blind guards — the earlier null/`''` hardening missed three sibling guards, so a `''` boundary could pass as finite boundary 0. `sync_engine.ts` orphan adoption now defers with `boundary-unknown-deferred`, `order.ts consumePendingFillCrawls` drops owed crawls with `null-boundary`, `validate.ts optimizeRebalanceActions` yields NaN instead of stamping a bogus boundary-0 gap-evacuation bypass, and `math.ts getSellStartIdx`/`resolveGapSlots` move the absent-aware contract into the shared helper (a genuine boundary 0 is preserved). Defense-in-depth on currently unreachable paths; covered by EVAC-021/023 and PEND-007b.
28
+
29
+ - **Perf(tests)**: cut suite wall time ~4x with a parallel runner and deterministic waits — `run-tests.ts` defaults to `min(cores, 4)` parallel files (`DEXBOT_TEST_CONCURRENCY=1` restores sequential) and preloads the ESM loader hooks for `esmMockEntry`-only and single-stage files so they no longer re-exec a second node process; fixed sleeps/busy-loops become condition-driven waits across the COW, native-subscription, fill-lifecycle, account-totals, bot-supervisor and position-manager suites; and two test-only seams default to the existing production values. A follow-up consolidates shared-mock stages into grouped units and trims the heaviest deterministic sweeps (Huber scratch-array reuse verified bit-identical, coarser entropy stride, shorter tracker prefix-parity series). Production numeric output is unchanged: 313 passed / 0 failed / 14 skipped live in ~11.4s (from ~45s sequential).
30
+
31
+ - **Chore**: replace live bot/account identifiers with placeholders in source comments, test fixtures and CHANGELOG entries (`<bot>`, `<account-name>`, synthetic `1.2.12345`, `BITSHARES_TEST_ACCOUNT*` env overrides) so no live identifier ships. Comment/string-only.
32
+
33
+ - **Docs**: highlight collapsible `<details>` summaries with `<mark>` across the sub-READMEs; add the §9 order-engine retrospective addendum for the v1.6.4→v1.6.14 arc (uncertain-broadcast and suspended-persistence deferral, fail-closed unknown geometry, pre-broadcast UPDATE-target guard) with the commit ledger and four new invariants; and record the spread-correction resilience contract across `architecture.md`, `LOGGING.md`, `COW_INVARIANTS.md` (INV-COW-010), the developer guide, `modules/README.md` and `tests/README.md`.
34
+
5
35
  ## [1.6.14] - 2026-10-12 - Spread-Correction Last-Fill Guard & Live Market Floor, Committed-Size Drift Resize, COW Pre-Broadcast Guards & P2 Counters, Fail-Closed Unknown Geometry, Order-Key Rename
6
36
 
7
37
  ### 2026-10-12
@@ -635,7 +665,7 @@ The `fix(version-notice)` work committed after the 1.6.8 tag (real verdict from
635
665
  - **Chore(browser-boundary)**: align the browser-safe surface with reality — `package.json` browser-map exclusions added for `modules/runtime_settings.js`, all five Node-bound `bitshares-native` entry files (`transport`, `signing_client`, `subscriptions`, `tx/builder`, `tx/tx_cache`) and `market_adapter/utils/chain.js` (top-level `createRequire(import.meta.url)`); AGENTS.md Node-only list extended with the same files so convention docs match the bundler config (`package.json`, `AGENTS.md`).
636
666
  - **Refactor(dead-code)**: remove unreferenced symbols surfaced by the audit — `constants.ts` prunes the ECC mirror block, unused timing/network constants (`SUBSCRIPTION_SILENT_THRESHOLD_MS`, `STARTUP_CONNECT_TIMEOUT_MS`, `MAX_TRANSACTION_SIZE`, `MAX_TIME_UNTIL_EXPIRATION`, `PERCENT_1`) and the supervisor `MAX_MEMORY_MB` fallback, and aligns OBJECT_TYPES with the BitShares enum (`CUSTOM_AUTHORITY` 17 … `CREDIT_DEAL` 22) adding the credit-offer/deal object types used by credit flows; `cr_planner.ts` drops the legacy CR-formula exports (`planCrAdjustment`, collateral/debt target helpers) while keeping `calculateCollateralRatio` internal; `credit_runtime.ts` removes the test-only `openCreditPosition`/`getCollateralOffsets` wrappers (renewOnly coverage retargeted to `buildCreditOfferAcceptOperation`); `key_store.ts` removes the unused `DirectKeyStore`; `crypto/index.ts` drops dead pure-primitive re-exports; `dexbot_fill_runtime.ts` collapses tautological FILL_PROCESSING.MODE comparisons (history processing unconditional, open-orders fallback gated solely on `requiresOpenOrdersSync`); `bots_file_lock.ts` fixes the writeJsonFileAtomic doc drift (`modules/constants.ts`, `modules/cr_planner.ts`, `modules/credit_runtime.ts`, `modules/key_store.ts`, `modules/crypto/index.ts`, `modules/dexbot_fill_runtime.ts`, `modules/bots_file_lock.ts`).
637
667
  - **Test**: add regression coverage for the trickier audit fixes — `test_to_finite_number_null.ts` locks the nullable-read semantics, `test_credential_policy_layer_merge.ts` covers per-op allowedOps merging plus `__proto__` rejection, settings-merge tests cover EXPERT GRID_COMPARISON preservation and scalar-override immunity plus deep-merge `__proto__` pollution rejection at nested levels, and the fill-batch suite asserts a deferred fill restores the exact pre-call `_fillBatchInFlight` count so concurrent batches cannot zero each other's guard; fixtures updated for the removed `getSizingContext` wrapper and the signal-based abort path (`tests/test_to_finite_number_null.ts`, `tests/test_credential_policy_layer_merge.ts`, `tests/test_settings_merge.ts`, `tests/test_sync_fill_history_batch.ts`, `tests/*`).
638
- - **Tune**: raise the AMA slope ceiling default 0.085 → 0.09 and narrow the research slider floor 0.04 → 0.06 — de-sensitizes the AMA trend channel by ~5.6% (factor 0.85/0.9) so grid range-scaling asymmetry, grid price offset, and buy/sell weight tilt react proportionally weaker to the same slope magnitude; applied asymmetry at the current XRP-BTS slope drops ~21.25% → ~20.1% and the AMA-slope grid-reset trigger threshold rises 0.0068 → 0.0072 %/bar; behavior unchanged at |slopePct| ≥ 0.09 (identical saturation cap), research chart paste payloads with amaS% in [0.04, 0.06) clamp up to 0.06 (`modules/constants.ts`, `analysis/trend_detection/dynamic_weight_chart_generator.ts`, `analysis/trend_detection/DYNAMIC_WEIGHT_RESEARCH.md`).
668
+ - **Tune**: raise the AMA slope ceiling default 0.085 → 0.09 and narrow the research slider floor 0.04 → 0.06 — de-sensitizes the AMA trend channel by ~5.6% (factor 0.85/0.9) so grid range-scaling asymmetry, grid price offset, and buy/sell weight tilt react proportionally weaker to the same slope magnitude; applied asymmetry at the current <market-pair> slope drops ~21.25% → ~20.1% and the AMA-slope grid-reset trigger threshold rises 0.0068 → 0.0072 %/bar; behavior unchanged at |slopePct| ≥ 0.09 (identical saturation cap), research chart paste payloads with amaS% in [0.04, 0.06) clamp up to 0.06 (`modules/constants.ts`, `analysis/trend_detection/dynamic_weight_chart_generator.ts`, `analysis/trend_detection/DYNAMIC_WEIGHT_RESEARCH.md`).
639
669
  - **Fix(market-adapter)**: harden locking, signal math, and input tools from a full module review — Hurst buffer cap window+2 → window+1 so the newest candle is always included with shared `classifyHurst()` and a `HURST_STRENGTH_NORMALIZER` strength scale; ATR re-warms per chain segment so a bad candle no longer leaks pre-break values across the gap; dynamic-weight/slope dead-band boundaries inclusive on both sides with exact-zero slopes staying NEUTRAL at the default `neutralZonePct` of 0; permutation entropy validates m/delay/window against `PE_ANALYZER_LIMITS` at construction instead of running degenerate configs silently; Kalman filter defaults unified through a single `_initState()` with beams returned as a copy and null-safe displacement; a malformed custom regimeTable throws at construction instead of producing silent NaN multipliers. File locks gain an ownership token (fresh UUID per holder written into every payload; release only unlinks when the token still matches) so a stolen lock can no longer be deleted by its previous holder, including pid collisions across containers sharing a mounted volume — legacy token-less payloads stay releasable; partial acquisitions clean up their orphaned lock file instead of locking out later contenders, heartbeat derives as clamp(staleMs/2, 1s..30s) so it always fires inside the staleness window, and the holder heuristic recognizes dexbot-embedded adapters while anchoring entrypoint names to argv/path boundaries so unrelated scripts such as robot.js no longer match. Service wiring clamps clipPercentile to (0,100] at the read point, normalizes volatility exponent/scaleX to their effective ranges at the single configured point, derives amaSlopeGated/amaChannelContribution diagnostics from the canonical Kalman-disabled weight series so diagnostics agree with finalOffset whenever gating is active, records `triggerSuppressedReason=stale_candle_data` for stale-but-new cycles, and config normalizers treat null/empty as unset before `Number()` coercion so explicit JSON null no longer means "disabled". Input tools: fetch_lp_data completes the interval map (30m..7d) with loud validation instead of parsing "30m" as 30 seconds, adds linear retry backoff and honest range labels in --start/--end mode; fetch_cex_synthetic_data fixes the dead HTX endpoint (/market/history/kline), honors exchange page caps via `CEX_PAGE_LIMIT_CAPS`, corrects MEXC intervals (6h/12h/1W), rejects zero-price leg candles, and handles --help before bot resolution. Constants: new keys centralized (`FILE_LOCK_HEARTBEAT_MIN/MAX_MS`, `LP_FETCH_RETRY_BACKOFF_BASE_MS`, `CEX_PAGE_LIMIT_CAPS`, `PE_ANALYZER_LIMITS`, `HURST_STRENGTH_NORMALIZER`, `DYNAMIC_WEIGHT_KALMAN_WARMUP_BARS_DEFAULT`, `DYNAMIC_WEIGHT_KALMAN_BEAM_COUNT_DEFAULT`, `DYNAMIC_WEIGHT_VOLATILITY_EXPONENT/SCALE_X_MIN/MAX`), sourceRetries default 3 → 4; misc: kibana_client releases redirect bodies, data_discovery skips unreadable entries and dangling symlinks, asymmetric_bounds/collateral_manager share previously duplicated math, analysis/bot_key_utils delegates to the production createBotKey so unnamed bots resolve identical keys, vestigial exports removed, and 'use strict' hoisted above imports across ~90 files where it sat as a no-op (`market_adapter/**`, `modules/constants.ts`, `analysis/bot_key_utils.ts`).
640
670
 
641
671
  ### 2026-08-25
@@ -691,7 +721,7 @@ The `fix(version-notice)` work committed after the 1.6.8 tag (real verdict from
691
721
 
692
722
  - **Feat(cow)**: enforce a per-broadcast operation cap — a single COW rebalance can expand one fill batch into many more order operations (4 fills → 12 creates + 4 updates = 16 ops), so `FILL_PROCESSING.MAX_FILL_BATCH_SIZE` is a weak proxy for on-chain transaction size. `COW_PERFORMANCE.MAX_OPS_PER_BROADCAST` (default 4) now caps operations per broadcast; oversized batches are split into sequential transactions via `executeChunkedWithRetryOnUncertain`, restoring the original "N fills per broadcast" intent at the op level. An uncertain chunk failure continues broadcasting the remaining chunks (no order dropped); a definitively rejected chunk aborts the rest; the first failure is rethrown enriched with `partialOnChainState`, `chunksTotal`/`chunksFailed`/`chunksAborted`, and `broadcastedOperationCount`. Configurable via the runtime settings override chain (`runtimeCowPerformance`/`marketCowPerformance`/`botCowPerformance`). Covered by the new 463-line `test_cow_ops_per_broadcast.ts` (`modules/dexbot_cow_runtime.ts`, `modules/constants.ts`, `modules/dexbot_class.ts`, `modules/runtime_settings.ts`).
693
723
  - **Fix(grid)**: exclude gap-band strays from divergence desired-window selection — a fund-driven boundary shift during `applyGridDivergenceCorrections` re-types the working grid, but the SPREAD GUARD keeps live on-chain orders inside the new spread band typed BUY/SELL, so the Phase-2 window selected "closest to market" slots purely by stored type+price and a stray SELL inside the new gap looked like the bottom of the sell rail and was never relocated, collapsing the real spread (boundary 107→110 left sells at 111–113 inside the new gap, real spread 0.5% vs the 2.0% target). New shared `MathUtils.isSlotInRail` (pure geometric rail-membership test) now filters desired-window candidates using the working boundary; the strategy window and virtual-slot selection delegate to the same helper, and gap-band strays become surplus → cancelled and relocated back onto the rail (`modules/order/utils/math.ts`, `modules/order/utils/system.ts`, `modules/order/strategy.ts`, `modules/order/grid_reconcile_internal.ts`, `tests/test_is_slot_in_rail.ts`, `tests/test_cow_divergence_correction.ts`, `tests/test_lp_chart.ts`).
694
- - **Tune**: lower the AMA slope grid-reset threshold from 10 to 8 — the AMA slope delta trigger resets the grid when the slope swing exceeds (`AMA_SLOPE_DELTA_THRESHOLD_PERCENT`/100) × maxSlopePct. At 10 the XRP-BTS trend reversal (DOWN baseline → UP current, delta 0.0074%/bar) stayed below the 0.0085 threshold, leaving the grid scaled for the wrong direction. Lowering to 8 (threshold 0.0068%/bar) reacts to the reversal while still ignoring small slope noise (`modules/constants.ts`).
724
+ - **Tune**: lower the AMA slope grid-reset threshold from 10 to 8 — the AMA slope delta trigger resets the grid when the slope swing exceeds (`AMA_SLOPE_DELTA_THRESHOLD_PERCENT`/100) × maxSlopePct. At 10 the <market-pair> trend reversal (DOWN baseline → UP current, delta 0.0074%/bar) stayed below the 0.0085 threshold, leaving the grid scaled for the wrong direction. Lowering to 8 (threshold 0.0068%/bar) reacts to the reversal while still ignoring small slope noise (`modules/constants.ts`).
695
725
  - **Feat(ui)**: green/red relative-scaling feedback for price inputs — the bot editor's Price Range displayed min/max as plain white, hiding whether relative scaling (x multipliers) is active. Range values now render green for "1.55x" multipliers and red for fixed prices, and `readInput` gains a colorize option so the typed input switches red → green live the moment the "x" is entered (`modules/account_bots.ts`, `modules/order/utils/system.ts`).
696
726
  - **Fix(ui)**: clarify the GridPrice label in the bot editor — the Price section displayed the gridPrice reference as bare "Grid:", which was ambiguous next to "Start:"/"Pool:" and collided with the section "4) Grid". Renamed to "GridPrice:" (one word, matching the `gridPrice` config field name) to reflect the values it accepts (pool/book/ama/number/none) (`modules/account_bots.ts`).
697
727
  - **Docs**: add an end-to-end lifecycle walkthrough — new `docs/LIFECYCLE.md` consolidates the startup, fill-driven (reactive), and maintenance/AMA-driven (periodic) flows into one newcomer-facing map with mermaid system-context and sequence diagrams (fill → `_incomingFillQueue` → `processFilledOrders` → Accounting SSOT → WorkingGrid COW → single atomic broadcast → persist; `_performPeriodicGridChecks` → `performPeriodicGridChecks` → `runGridMaintenance` → `executeMaintenanceLogic`), plus a cross-cutting invariants table and file map. Surfaced as the first read from README and the docs index, and added to the npm `files` array (`docs/LIFECYCLE.md`, `docs/developer_guide.md`, `docs/README.md`, `README.md`, `package.json`).
@@ -785,7 +815,7 @@ The `fix(version-notice)` work committed after the 1.6.8 tag (real verdict from
785
815
 
786
816
  ### 2026-08-14
787
817
 
788
- - **Feat**: add an optional bot filter to `dexbot order` — pass a bot key as a positional argument (e.g. `dexbot order xrp-bts`) to render only that bot's persisted grid, optionally combined with `--export` for a single-bot HTML report; matching accepts the raw key, its sanitized form, or the configured name; a missing key lists available bots and suppresses skipped-candidate noise (`scripts/analyze-orders.ts`, `dexbot.ts`, `README.md`, `docs/WORKFLOW.md`).
818
+ - **Feat**: add an optional bot filter to `dexbot order` — pass a bot key as a positional argument (e.g. `dexbot order <botKey>`) to render only that bot's persisted grid, optionally combined with `--export` for a single-bot HTML report; matching accepts the raw key, its sanitized form, or the configured name; a missing key lists available bots and suppresses skipped-candidate noise (`scripts/analyze-orders.ts`, `dexbot.ts`, `README.md`, `docs/WORKFLOW.md`).
789
819
 
790
820
  ### 2026-08-13
791
821
 
@@ -1341,7 +1371,7 @@ The `fix(version-notice)` work committed after the 1.6.8 tag (real verdict from
1341
1371
  - **Fix**: process queued price corrections on startup and in maintenance loop — corrections queued by syncFromOpenOrders (via ordersNeedingPriceCorrection) were only processed inside _consumeFillQueue, which only runs when new fills arrive. For an idle market where sync detects a price mismatch during startup, the correction sat in the queue indefinitely, stalling the pipeline. Now processed immediately after startup sync and at the start of every maintenance cycle (`modules/dexbot_class.ts:1339`, `modules/dexbot_maintenance_runtime.ts:1399`).
1342
1372
  - **Fix**: protect committed orders from recovery sync virtualization — during UNCERTAIN broadcast and fund-invariant recovery, the full two-pass syncFromOpenOrders could virtualize orders that were correctly placed by prior successful COW commits when the chain snapshot lags behind confirmed transactions. New `_committedOrderIds` set tracked across COW commit boundaries; PASS 1 virtualization guard skips any orderId in the set (`modules/order/manager.ts`, `modules/order/sync_engine.ts`, `modules/dexbot_class.ts`, `modules/order/accounting.ts`).
1343
1373
  - **Fix**: cancel residual ghost orders left on chain by other-side rounding — when a fill leaves a tiny residual where opposite-asset value rounds to 0 at blockchain precision, the grid slot was virtualized but the chain order was never cancelled. New `ghostOrderId` return field drains orphan cancellations via a per-session guarded set to avoid repeat attempts (`modules/dexbot_class.ts`, `modules/order/sync_engine.ts`, `tests/test_ghost_order_fix.ts`).
1344
- - **Fix**: remove hardcoded XRP-BTS defaults from analysis scripts and docs — all 6 analysis scripts now require `--bot-key` explicitly at runtime; documentation uses `EXAMPLE-BOT` placeholders instead of `XRP-BTS` (`analysis/analyze_dynamic_weight.ts`, `analysis/analyze_volatility.ts`, `analysis/analyze_kalman.ts`, `analysis/analyze_regime.ts`, `analysis/analyze_regime_windows.ts`, `analysis/analyze_derivatives.ts`, `docs/*.md`, `market_adapter/README.md`).
1374
+ - **Fix**: remove hardcoded <market-pair> defaults from analysis scripts and docs — all 6 analysis scripts now require `--bot-key` explicitly at runtime; documentation uses `EXAMPLE-BOT` placeholders instead of `<market-pair>` (`analysis/analyze_dynamic_weight.ts`, `analysis/analyze_volatility.ts`, `analysis/analyze_kalman.ts`, `analysis/analyze_regime.ts`, `analysis/analyze_regime_windows.ts`, `analysis/analyze_derivatives.ts`, `docs/*.md`, `market_adapter/README.md`).
1345
1375
  - **Feat**: centralize AMA config resolution in bot_key_utils for analysis tools — shared `loadBotMeta`, `resolveAmaConfig` (inline > profile > built-in with preset merge, erSmoothPeriod on all paths, fast/slow swap guard), and `resolveAmaKey` extracted from individual scripts. Dynamic chart legend now shows the resolved AMA label (AMA1/AMA2/AMA3/AMA4) instead of hardcoded AMA3 (`analysis/bot_key_utils.ts`, `analysis/analyze_dynamic_weight.ts`, `analysis/analyze_tradingview.ts`, `analysis/trend_detection/dynamic_weight_chart_generator.ts`).
1346
1376
 
1347
1377
  ## [1.1.11] - 2026-07-18 - npm publish, README install options, CLI dist resolution, .npmrc ignore
@@ -39,7 +39,7 @@ Tools that inspect DEXBot trading behavior and the market data it operates on. O
39
39
 
40
40
  Common abbreviations used throughout: OHLC, AMA, ER, ATR, Kalman, Hurst, PE, R, LIFO, FIFO, PnL, SMA, VWMA. Full definitions below.
41
41
 
42
- <details><summary>Abbreviation glossary (click to expand)</summary>
42
+ <details><summary><mark>Abbreviation glossary (click to expand)</mark></summary>
43
43
 
44
44
  | Term | Full name | Plain English |
45
45
  |------|-----------|---------------|
@@ -163,7 +163,7 @@ node dist/analysis/trade_profitability.js 1.2.123456 \
163
163
  --hours 168 --match-mode fifo
164
164
  ```
165
165
 
166
- <details><summary>Options (click to expand)</summary>
166
+ <details><summary><mark>Options (click to expand)</mark></summary>
167
167
 
168
168
  | Flag | Default | Description |
169
169
  |------|---------|-------------|
@@ -208,7 +208,7 @@ node dist/analysis/trade_profitability.js 1.2.123456 \
208
208
 
209
209
  **Metrics glossary** — `R` = the size of the average losing trade. A +3R trade earned 3× what a typical loser costs you.
210
210
 
211
- <details><summary>Per-metric definitions (click to expand)</summary>
211
+ <details><summary><mark>Per-metric definitions (click to expand)</mark></summary>
212
212
 
213
213
  | Output line | Meaning |
214
214
  |-------------|---------|
@@ -278,7 +278,7 @@ npm run analysis:grid-check -- --bot-key <bot-key> --hours 168 --increment 0.5
278
278
 
279
279
  Exit code `0` = pass, `2` = violations found, `1` = fatal error. Bot keys resolve via `profiles/bots.json` (`--list-bots` to enumerate); the account defaults to the bot's stored `accountId` when present (no chain lookup — the ID is auto-saved next to `preferredAccount` after the first successful name resolution, re-verified with `--refresh-account`), otherwise `preferredAccount` is resolved on-chain, and can be overridden with `--account <1.2.x|name>`.
280
280
 
281
- <details><summary>Options (click to expand)</summary>
281
+ <details><summary><mark>Options (click to expand)</mark></summary>
282
282
 
283
283
  | Flag | Default | Description |
284
284
  |------|---------|-------------|
@@ -319,7 +319,7 @@ node dist/analysis/analyze_trade_heatmap.js \
319
319
  --slice-months 6
320
320
  ```
321
321
 
322
- <details><summary>Options (click to expand)</summary>
322
+ <details><summary><mark>Options (click to expand)</mark></summary>
323
323
 
324
324
  | Flag | Default | Description |
325
325
  |------|---------|-------------|
@@ -429,7 +429,7 @@ Shared analyzers and chart renderers for the dynamic-weight signal path. Core en
429
429
  - [README.md](trend_detection/README.md) — directory overview and module index
430
430
  - [DYNAMIC_WEIGHT_RESEARCH.md](trend_detection/DYNAMIC_WEIGHT_RESEARCH.md) — AMA+Kalman blend with Hurst/PE regime gating, formula reference, knob guide
431
431
 
432
- <details><summary>Modules (click to expand)</summary>
432
+ <details><summary><mark>Modules (click to expand)</mark></summary>
433
433
 
434
434
  | Module | Purpose |
435
435
  |--------|---------|
@@ -34,7 +34,7 @@ The sections below cover manual usage (explicit candle files, direct runner flag
34
34
  ## What It Produces
35
35
 
36
36
  - Log-scale price chart
37
- - Candle timeframe buttons: `1h`, `4h`, `1d`, `1w`
37
+ - Candle timeframe buttons: `1h`, `4h`, `1d`, `1w`, `1M`
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
@@ -48,6 +48,7 @@ The sections below cover manual usage (explicit candle files, direct runner flag
48
48
  - Volume badge (bottom-right of the volume chart, same small type): visible-window max volume, always with the currency suffix (`1.2M BTS`); click the badge, the legend `Vol` value, or the toolbar unit button to switch base/quote units (quote ≈ base × close, persisted per chart like the AMA settings; feed charts show publish counts and disable the switch)
49
49
  - Bottom volume panel with `Volume` toggle and per-bar hover tooltip
50
50
  - Crosshair legend with current candle values
51
+ - Live data-age badge next to the title: the age of the newest candle is recomputed every minute in the browser (minutes under an hour, hours and minutes under a day, days and hours beyond), so a chart saved or opened later shows its own staleness — green under 24h, amber 1–7 days, red over a week (unknown when the source carries no candle time or `meta.updatedAt`)
51
52
 
52
53
  ## Quick Start
53
54
 
package/claw/README.md CHANGED
@@ -43,7 +43,7 @@ npm install
43
43
 
44
44
  ## Files
45
45
 
46
- <details><summary>Module and file map (click to expand)</summary>
46
+ <details><summary><mark>Module and file map (click to expand)</mark></summary>
47
47
 
48
48
  - Core BitShares runtime: `modules/bitshares_client.ts`, `modules/chain_queries.ts`, `modules/chain_broadcast.ts`, `modules/chain_actions.ts`
49
49
  - Strategy and state helpers: `modules/short_mpa_strategy.ts`, `modules/position_manager.ts`, `modules/position_manager_watch.ts`
@@ -188,7 +188,7 @@ Shared boundary notes live in `skills/shared/references/skill-boundaries.md`.
188
188
  | NullClaw | `SKILL.toml` skill manifest plus MCP server config | Zig-native workspace assistant with manifest loading | Strong fit for local workspace loading, but more dependent on NullClaw-specific config conventions |
189
189
  | memU | Subprocess bridge plus MCP server | Proactive memory and intent capture for AI agents | Python-based memory framework with LLM-powered extraction and vector search |
190
190
 
191
- <details><summary>Quick selection rule of thumb (click to expand)</summary>
191
+ <details><summary><mark>Quick selection rule of thumb (click to expand)</mark></summary>
192
192
 
193
193
  - Choose **OpenClaw** for the broadest assistant platform.
194
194
  - Choose **Hermes** if you want a general-purpose assistant with memory, messaging, cron, and browser tooling that can also trade through Claw.
@@ -271,7 +271,7 @@ npm run openfang:skill -- --repo-root "$CLAW_ROOT" --profile-root "$DEXBOT_ROOT"
271
271
 
272
272
  OpenFang uses the same shared bridge surface through a local CLI wrapper.
273
273
 
274
- <details><summary>Compatibility command surface (click to expand)</summary>
274
+ <details><summary><mark>Compatibility command surface (click to expand)</mark></summary>
275
275
 
276
276
  ```bash
277
277
  npm run openfang:bridge -- manifest
@@ -338,7 +338,7 @@ npm run nanoclaw:skill -- --repo-root "$CLAW_ROOT" --profile-root "$DEXBOT_ROOT"
338
338
 
339
339
  NanoClaw already ships its own `claw` skill, so keep this bridge skill named `bitshares-claw`.
340
340
 
341
- <details><summary>Compatibility command surface (click to expand)</summary>
341
+ <details><summary><mark>Compatibility command surface (click to expand)</mark></summary>
342
342
 
343
343
  ```bash
344
344
  npm run nanoclaw:bridge -- manifest
@@ -359,7 +359,7 @@ DEXBOT_ROOT="$(cd .. && pwd)"
359
359
  npm run zeroclaw:skill -- --repo-root "$CLAW_ROOT" --profile-root "$DEXBOT_ROOT" --output ~/.zeroclaw/workspace/skills/ai-bots/SKILL.toml
360
360
  ```
361
361
 
362
- <details><summary>Compatibility command surface (click to expand)</summary>
362
+ <details><summary><mark>Compatibility command surface (click to expand)</mark></summary>
363
363
 
364
364
  ```bash
365
365
  npm run zeroclaw:bridge -- manifest
@@ -383,7 +383,7 @@ DEXBOT_ROOT="$(cd .. && pwd)"
383
383
  npm run nullclaw:skill -- --repo-root "$CLAW_ROOT" --profile-root "$DEXBOT_ROOT" --output ~/.nullclaw/workspace/skills/bitshares-claw/SKILL.toml
384
384
  ```
385
385
 
386
- <details><summary>Compatibility command surface (click to expand)</summary>
386
+ <details><summary><mark>Compatibility command surface (click to expand)</mark></summary>
387
387
 
388
388
  ```bash
389
389
  npm run nullclaw:bridge -- manifest
@@ -435,7 +435,7 @@ mcp_servers:
435
435
  args: ["/absolute/path/to/DEXBot2/dist/claw/scripts/memu_mcp_server.js", "--memu-dir", "/absolute/path/to/claw/data/memu"]
436
436
  ```
437
437
 
438
- <details><summary>Compatibility command surface (click to expand)</summary>
438
+ <details><summary><mark>Compatibility command surface (click to expand)</mark></summary>
439
439
 
440
440
  ```bash
441
441
  # Via claw bridge
package/claw/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "dexbot2-claw",
3
- "version": "1.6.14",
3
+ "version": "1.6.15",
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.14",
5
+ "version": "1.6.15",
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.14",
4
+ "version": "1.6.15",
5
5
  "type": "module",
6
6
  "main": "index.js"
7
7
  }
@@ -118,7 +118,27 @@ function resolveChartStorageKey(meta = {}, baseIntervalSeconds = 0) {
118
118
  }
119
119
  function generateHTML(data, title = 'TradingView Style Research') {
120
120
  const rawCandles = Array.isArray(data.candles) ? data.candles : [];
121
- const candles = rawCandles.map(normalizeCandle).filter(Boolean);
121
+ const normalizedCandles = rawCandles
122
+ .map(normalizeCandle)
123
+ .filter((c) => c != null);
124
+ // Data-quality guard: uPlot, inferBaseIntervalSeconds and aggregateCandles all
125
+ // assume ascending bucket time, and an out-of-order series silently corrupts
126
+ // the chart (zig-zag lines, wrong base interval, buckets split during
127
+ // aggregation). Normalize order at the single entry point so every source is
128
+ // safe. A stable sort is a no-op for already-ascending input, so valid charts
129
+ // render unchanged; only bad input is reordered (and reported).
130
+ let outOfOrder = false;
131
+ for (let i = 1; i < normalizedCandles.length; i++) {
132
+ if (normalizedCandles[i].time < normalizedCandles[i - 1].time) {
133
+ outOfOrder = true;
134
+ break;
135
+ }
136
+ }
137
+ const candles = outOfOrder
138
+ ? normalizedCandles.slice().sort((a, b) => a.time - b.time)
139
+ : normalizedCandles;
140
+ if (outOfOrder)
141
+ console.warn('[TradingView] candle input was out of order; sorted ascending before rendering');
122
142
  if (candles.length === 0)
123
143
  throw new Error('No candle data in input');
124
144
  const meta = data.meta || {};
@@ -126,6 +146,7 @@ function generateHTML(data, title = 'TradingView Style Research') {
126
146
  ? Number(meta.intervalSeconds)
127
147
  : inferBaseIntervalSeconds(candles, 3600);
128
148
  const timeframes = [
149
+ { label: '1h', seconds: 3600 },
129
150
  { label: '4h', seconds: 14400 },
130
151
  { label: '1d', seconds: 86400 },
131
152
  { label: '1w', seconds: 604800 },
@@ -211,6 +232,15 @@ function generateHTML(data, title = 'TradingView Style Research') {
211
232
  const storageKey = typeof data.storageKey === 'string' && data.storageKey.length > 0
212
233
  ? data.storageKey
213
234
  : resolveChartStorageKey(meta, baseIntervalSeconds);
235
+ // Data-freshness anchor for the in-page live age badge: the newest candle's
236
+ // bucket time (epoch seconds), falling back to the source file's
237
+ // `meta.updatedAt`. Null hides the age (non-JSON sources may carry neither).
238
+ const lastCandleEntry = candles.length ? candles[candles.length - 1] : null;
239
+ const lastCandleSec = Number(lastCandleEntry?.time);
240
+ const metaUpdatedMs = Date.parse(String(meta.updatedAt ?? ''));
241
+ const dataUpdatedAtSec = Number.isFinite(lastCandleSec) && lastCandleSec > 0
242
+ ? Math.floor(lastCandleSec)
243
+ : (Number.isFinite(metaUpdatedMs) ? Math.floor(metaUpdatedMs / 1000) : null);
214
244
  const payload = {
215
245
  storageKey,
216
246
  syncKey: TRADINGVIEW_SYNC_KEY,
@@ -247,6 +277,8 @@ function generateHTML(data, title = 'TradingView Style Research') {
247
277
  pairLabelInverse,
248
278
  poolLabel,
249
279
  intervalLabel,
280
+ intervalSeconds: baseIntervalSeconds,
281
+ dataUpdatedAtSec,
250
282
  amaDefaultsSource: marketProfiles ? 'market_profiles' : 'constants',
251
283
  volumeIsCount: !!meta?.feed,
252
284
  };
@@ -280,8 +312,16 @@ function generateHTML(data, title = 'TradingView Style Research') {
280
312
  backdrop-filter: blur(10px);
281
313
  }
282
314
  #brand { display: flex; flex-direction: column; gap: 4px; min-width: 240px; }
315
+ #title-row { display: flex; align-items: baseline; gap: 10px; }
283
316
  #title { font-size: 15px; font-weight: 700; color: #f5f8fb; }
284
- #subtitle { font-size: 11px; color: #b9c6d4; text-transform: uppercase; letter-spacing: 0.6px; }
317
+ #subtitle { font-size: 12px; color: #b9c6d4; text-transform: uppercase; letter-spacing: 0.6px; }
318
+ #data-age { display: inline-flex; align-items: center; gap: 6px; font-size: 14px; font-weight: 600; color: #8290a2; letter-spacing: 0.2px; }
319
+ #data-age::before { content: ""; width: 8px; height: 8px; border-radius: 50%; background: #22c55e; box-shadow: 0 0 0 2px rgba(34,197,94,0.18); }
320
+ #data-age.is-stale { color: #d8b36a; }
321
+ #data-age.is-stale::before { background: #f59e0b; box-shadow: 0 0 0 2px rgba(245,158,11,0.18); }
322
+ #data-age.is-outdated { color: #e08585; }
323
+ #data-age.is-outdated::before { background: #ef5350; box-shadow: 0 0 0 2px rgba(239,83,80,0.18); }
324
+ #data-age.is-unknown::before { background: #475569; box-shadow: none; }
285
325
  #toolbar { display: flex; flex-direction: column; align-items: flex-end; gap: 6px; }
286
326
  .toolbar-row { display: flex; flex-wrap: wrap; justify-content: flex-end; gap: 8px 12px; align-items: center; }
287
327
  .group { display: inline-flex; align-items: center; gap: 8px; padding-left: 12px; border-left: 1px solid #263241; }
@@ -522,8 +562,11 @@ function generateHTML(data, title = 'TradingView Style Research') {
522
562
  <div id="app">
523
563
  <div id="topbar">
524
564
  <div id="brand">
525
- <div id="title">${escapeHtml(title)}</div>
526
- <div id="subtitle">${escapeHtml(poolLabel)} · ${escapeHtml(pairLabelNormal)} · ${escapeHtml(intervalLabel)} base · indicators from 1h · volume · uPlot</div>
565
+ <div id="title-row">
566
+ <div id="title">${escapeHtml(title)}</div>
567
+ <span id="data-age" title="Age of the newest candle, recomputed live in the browser. Fresh: under 24h, stale: 1–7 days, out of date: over a week.">—</span>
568
+ </div>
569
+ <div id="subtitle">${escapeHtml(poolLabel)} · ${escapeHtml(pairLabelNormal)} · ${escapeHtml(intervalLabel)} base · indicators from 1h</div>
527
570
  </div>
528
571
  <div id="toolbar">
529
572
  <div class="toolbar-row primary-toolbar-row">
@@ -641,6 +684,37 @@ function generateHTML(data, title = 'TradingView Style Research') {
641
684
  const volumeEl = document.getElementById('volume-chart');
642
685
  const baseCandles = Array.isArray(payload.candles) ? payload.candles.slice() : [];
643
686
  const baseCloseValues = baseCandles.map((c) => c.close);
687
+ // Live data-age badge: recomputed from the clock every minute, so a chart
688
+ // saved or opened later shows how stale its newest candle is. The
689
+ // freshness anchor is the newest candle's bucket time, embedded at
690
+ // generation time; the interval sets the color thresholds.
691
+ const dataAgeEl = document.getElementById('data-age');
692
+ const dataUpdatedAtSec = Number(payload.dataUpdatedAtSec) > 0 ? Number(payload.dataUpdatedAtSec) : NaN;
693
+ function formatDataAge(sec) {
694
+ const totalMin = Math.floor(sec / 60);
695
+ if (totalMin < 60) return totalMin + 'm';
696
+ const totalHours = Math.floor(totalMin / 60);
697
+ if (totalHours < 24) return totalHours + 'h ' + String(totalMin % 60).padStart(2, '0') + 'm';
698
+ return Math.floor(totalHours / 24) + 'd ' + (totalHours % 24) + 'h';
699
+ }
700
+ function refreshDataAge() {
701
+ if (!dataAgeEl) return;
702
+ if (!Number.isFinite(dataUpdatedAtSec)) {
703
+ dataAgeEl.className = 'is-unknown';
704
+ dataAgeEl.textContent = '—';
705
+ return;
706
+ }
707
+ const ageSec = Math.max(0, Date.now() / 1000 - dataUpdatedAtSec);
708
+ // Fresh: under 24h. Stale: 1d–7d. Out of date: over a week.
709
+ const DAY = 86400;
710
+ const level = ageSec < DAY ? 'fresh'
711
+ : ageSec < DAY * 7 ? 'stale' : 'outdated';
712
+ dataAgeEl.className = level === 'fresh' ? '' : 'is-' + level;
713
+ dataAgeEl.textContent = formatDataAge(ageSec);
714
+ dataAgeEl.title = 'Newest candle in this chart is ' + Math.round(ageSec / 60) + ' minute(s) old (computed live in the browser).';
715
+ }
716
+ refreshDataAge();
717
+ setInterval(refreshDataAge, 60000);
644
718
  const timeframes = Array.isArray(payload.timeframes) ? payload.timeframes.slice() : [];
645
719
  const timeframeMap = new Map(timeframes.map((item) => [item.label, item]));
646
720
  const STORAGE_KEY = typeof payload.storageKey === 'string' && payload.storageKey.length > 0
@@ -1134,7 +1208,7 @@ function generateHTML(data, title = 'TradingView Style Research') {
1134
1208
  function refreshSubtitle() {
1135
1209
  const subtitleEl = document.getElementById('subtitle');
1136
1210
  if (!subtitleEl) return;
1137
- subtitleEl.textContent = payload.poolLabel + ' · ' + getPairLabel() + ' · ' + payload.intervalLabel + ' base · indicators from 1h · volume · uPlot';
1211
+ subtitleEl.textContent = payload.poolLabel + ' · ' + getPairLabel() + ' · ' + payload.intervalLabel + ' base · indicators from 1h';
1138
1212
  }
1139
1213
  function snapInitOffset(value) {
1140
1214
  const next = Math.round(Number(value) || 0);
@@ -2314,7 +2388,7 @@ function generateHTML(data, title = 'TradingView Style Research') {
2314
2388
  return { hooks: { draw: [drawSimBand, drawSimResets] } };
2315
2389
  }
2316
2390
  function buildData() {
2317
- const tf = timeframeMap.get(currentTimeframe) || timeframeMap.get(defaultTimeframe.label) || timeframes[0];
2391
+ const tf = timeframeMap.get(currentTimeframe) || timeframeMap.get(payload.defaultTimeframe) || timeframes[0];
2318
2392
  currentSeriesState = getSeriesState(currentPairMode);
2319
2393
  currentSeriesCandles = currentSeriesState.candles;
2320
2394
  currentSeriesCloseValues = currentSeriesState.closeValues;
@@ -199,6 +199,9 @@ function generateHTML(data, title = 'Dynamic Weight Research') {
199
199
  ${uplotInlineTags()}
200
200
  <style>
201
201
  ${sharedChartCSS()}
202
+ /* Panel titles sit at the top-right; make them clearly readable
203
+ (shared CSS uses a very dark #30363d that vanishes on the dark bg). */
204
+ .section-label { color: #c9d1d9; font-size: 10px; }
202
205
  #price-panel { flex: 0 0 34%; min-height: 0; position: relative; border-bottom: 1px solid #30363d; }
203
206
  #ama-panel { flex: 0 0 14%; min-height: 0; position: relative; border-bottom: 1px solid #30363d; }
204
207
  #kalman-panel { flex: 0 0 21%; min-height: 0; position: relative; border-bottom: 1px solid #30363d; }
@@ -256,11 +259,12 @@ function generateHTML(data, title = 'Dynamic Weight Research') {
256
259
  .ctrl.off .val { color: #3fb950; }
257
260
  .ctrl.nz input[type="range"] { accent-color: #8b949e; }
258
261
  .ctrl.nz .val { color: #8b949e; }
259
- .copy-btn, .paste-btn { pointer-events: auto; margin-left: 6px; padding: 2px 10px; font-size: 10px; background: #21262d; color: #8b949e; border: 1px solid #30363d; border-radius: 4px; cursor: pointer; }
260
- .copy-btn:hover, .paste-btn:hover { background: #30363d; color: #e6edf3; }
262
+ .copy-btn, .paste-btn, .reset-btn { pointer-events: auto; margin-left: 6px; padding: 2px 10px; font-size: 10px; background: #21262d; color: #8b949e; border: 1px solid #30363d; border-radius: 4px; cursor: pointer; }
263
+ .copy-btn:hover, .paste-btn:hover, .reset-btn:hover { background: #30363d; color: #e6edf3; }
261
264
  .copy-btn.copied { color: #3fb950; border-color: #3fb950; }
262
265
  .paste-btn.pasted { color: #58a6ff; border-color: #58a6ff; }
263
266
  .paste-btn.error { color: #f85149; border-color: #f85149; }
267
+ .reset-btn.reset { color: #d29922; border-color: #d29922; }
264
268
  #paste-confirm { display: none; position: fixed; background: #161b22; border: 1px solid #30363d; border-radius: 6px; padding: 14px 16px; z-index: 1000; box-shadow: 0 4px 24px rgba(0,0,0,0.7); min-width: 200px; }
265
269
  #paste-confirm-title { font-size: 10px; color: #8b949e; margin-bottom: 8px; text-transform: uppercase; letter-spacing: 0.5px; }
266
270
  #paste-confirm-vals { font-size: 11px; font-family: monospace; color: #e6edf3; line-height: 1.7; margin-bottom: 12px; }
@@ -346,6 +350,7 @@ function generateHTML(data, title = 'Dynamic Weight Research') {
346
350
  <div class="ctrl regime"><label for="regime-slider">regi</label><input type="range" id="regime-slider" min="0" max="${REGI_MAX * 100}" value="${regimeInitSlider}" title="Regime Sensitivity"><span class="val" id="regime-value">${defaultRegimeSensitivity.toFixed(2)}</span></div>
347
351
  <button class="copy-btn" id="copy-params-btn">copy</button>
348
352
  <button class="paste-btn" id="paste-params-btn">paste</button>
353
+ <button class="reset-btn" id="reset-params-btn">reset</button>
349
354
  </div>
350
355
  <div id="output-chart"></div>
351
356
  </div>
@@ -1285,6 +1290,27 @@ function applyParams(p, btn) {
1285
1290
 
1286
1291
  const LS_KEY = 'dw_research_params';
1287
1292
 
1293
+ // Factory defaults captured server-side; the reset button restores
1294
+ // every knob to these values.
1295
+ const RESET_PARAMS = ${JSON.stringify({
1296
+ alpha: defaultAlpha,
1297
+ amaMaxSlopePct: defaultAmaMaxSlopePct,
1298
+ kalmanMaxSlopePct: defaultKalmanMaxSlopePct,
1299
+ minOutputThreshold: defaultMinOutputThreshold,
1300
+ gain: defaultGain,
1301
+ kalmanSmoothPct: defaultKalmanSmoothPct,
1302
+ kalmanDispScaleMult: defaultKalmanDispScaleMult,
1303
+ dispScaleMinPct: defaultDispScaleMinPct,
1304
+ kalmanDispThresholdMult: defaultKalmanDispThresholdMult,
1305
+ kalmanSmoothSpanPct: defaultKalmanSmoothSpanPct,
1306
+ signalConfirmBars: defaultSignalConfirmBars,
1307
+ clipPct: defaultClipPct,
1308
+ neutralZonePct: defaultNeutralZone,
1309
+ regimeSensitivity: defaultRegimeSensitivity,
1310
+ dispWeight: defaultDispWeight,
1311
+ lookbackBars,
1312
+ })};
1313
+
1288
1314
  document.getElementById('copy-params-btn').addEventListener('click', () => {
1289
1315
  const btn = document.getElementById('copy-params-btn');
1290
1316
  const params = {
@@ -1340,6 +1366,14 @@ function applyParams(p, btn) {
1340
1366
  ta.addEventListener('keydown', (e) => { if (e.key === 'Escape') cleanup(); });
1341
1367
  setTimeout(cleanup, 10000);
1342
1368
  });
1369
+
1370
+ document.getElementById('reset-params-btn').addEventListener('click', () => {
1371
+ const btn = document.getElementById('reset-params-btn');
1372
+ applyParams(RESET_PARAMS);
1373
+ btn.textContent = 'reset!';
1374
+ btn.classList.add('reset');
1375
+ setTimeout(() => { btn.textContent = 'reset'; btn.classList.remove('reset'); }, 1500);
1376
+ });
1343
1377
  }
1344
1378
 
1345
1379
  ${sizeChartsFn([['priceChart', 'price-panel'], ['amaChart', 'ama-panel'], ['kalmanChart', 'kalman-panel'], ['outputChart', 'output-panel']])}
package/dist/dexbot.js CHANGED
@@ -47,7 +47,7 @@ const __dirname = _esmDirname(__filename);
47
47
  * Runtime: dexbot start [bot] | stop | reload | restart | delete | status | pm2
48
48
  * Trading: dexbot test <bot> | drystart <bot> | reset {all|<bot>}
49
49
  * Config: dexbot bot | key | enable {all|<bot>} | disable {all|<bot>} | default | update
50
- * Analysis: dexbot order [<bot>] | export <bot> | credit [<bot>]
50
+ * Analysis: dexbot order [<bot>] | export <bot> | credit [<bot>] | rich <asset...>
51
51
  * dexbot tv <target> | dw <target> | pnl <account>
52
52
  * Files: dexbot clear | clear-orders | clear-market-adapter | clear-all
53
53
  *
@@ -142,7 +142,7 @@ if (typeof credentialPolicy.checkPolicyFileSecurity === 'function')
142
142
  // Primary CLI driver that manages tracked bots and helper utilities such as key/bot editors.
143
143
  const PROFILES_BOTS_FILE = PATHS.PROFILES.BOTS_JSON;
144
144
  const PROFILES_DIR = PATHS.PROFILES_DIR;
145
- const CLI_COMMANDS = ['start', 'test', 'reset', 'default', 'disable', 'enable', 'drystart', 'key', 'bot', 'pm2', 'update', 'export', 'order', 'credit', 'tv', 'dw', 'pnl', 'git', 'clear', 'clear-orders', 'clear-market-adapter', 'clear-all', 'status', 'unlock', 'delete', 'stop', 'restart', 'reload', 'help'];
145
+ const CLI_COMMANDS = ['start', 'test', 'reset', 'default', 'disable', 'enable', 'drystart', 'key', 'bot', 'pm2', 'update', 'export', 'order', 'credit', 'rich', 'tv', 'dw', 'pnl', 'git', 'clear', 'clear-orders', 'clear-market-adapter', 'clear-all', 'status', 'unlock', 'delete', 'stop', 'restart', 'reload', 'help'];
146
146
  const COMMAND_ALIASES = { orders: 'order', keys: 'key', bots: 'bot', stat: 'status', stats: 'status', start: 'unlock', defaults: 'default', stp: 'stop', stopall: 'stop', restartall: 'restart', reloadall: 'reload' };
147
147
  const CLI_HELP_FLAGS = ['-h', '--help'];
148
148
  const CLI_EXAMPLES_FLAG = '--cli-examples';
@@ -157,6 +157,7 @@ const CLI_EXAMPLES = [
157
157
  { title: 'Export bot trades', command: 'dexbot export <bot>', notes: 'Write trades and settings to CSV/JSON.' },
158
158
  { title: 'Analyze order grids', command: 'dexbot order', notes: 'Spread, increment, and funds; --export for HTML.' },
159
159
  { title: 'Show live credit positions', command: 'dexbot credit', notes: 'Summed MPA + borrowed-credit positions per bot.' },
160
+ { title: 'Asset rich list', command: 'dexbot rich <asset> [<asset...>]', notes: 'Top holder(s) per asset from the chain asset holders API.' },
160
161
  { title: 'Chart a bot, pool, or pair', command: 'dexbot tv <bot|pool-id|AssetA/AssetB> --month 3', notes: 'OHLC chart; --feed charts MPA price-feed history.' },
161
162
  { title: 'PnL report', command: 'dexbot pnl <bot|account> --month 3 [--pair BASE/QUOTE]', notes: 'Self-contained HTML PnL report for the resolved bot or chain account.' }
162
163
  ];
@@ -213,6 +214,7 @@ function printCLIUsage() {
213
214
  ['order [<bot>]', 'Analyze persisted order grids; --export for HTML.'],
214
215
  ['export <bot>', 'Export bot trades/settings to CSV/JSON.'],
215
216
  ['credit [<bot>]', 'Show live MPA and borrowed-credit positions.'],
217
+ ['rich <asset...>', 'Per-asset rich list / top holder; --top N, --json.'],
216
218
  ['tv <target>', 'OHLC chart for <bot|pool-id|AssetA/AssetB>; --month N (default 3), --feed for MPA price-feed history.'],
217
219
  ['dw <target>', 'Dynamic-weight research chart; same targets and flags as tv.'],
218
220
  ['pnl <account>', 'HTML PnL report for a bot or account; --month N, optional --pair BASE/QUOTE filter.'],
@@ -260,7 +262,7 @@ if (cliArgs.some(arg => CLI_HELP_FLAGS.includes(arg))) {
260
262
  // so the script prints its usage. Only scripts with offline help handling
261
263
  // belong here — forwarding to a script without it could misinterpret the
262
264
  // flag as input (e.g. a bot-name filter triggering live work).
263
- const HELP_OWNING_COMMANDS = new Set(['credit', 'tv', 'dw', 'pnl']);
265
+ const HELP_OWNING_COMMANDS = new Set(['credit', 'rich', 'tv', 'dw', 'pnl']);
264
266
  const requestedCommand = COMMAND_ALIASES[cliArgs[0]] ?? cliArgs[0];
265
267
  if (!HELP_OWNING_COMMANDS.has(requestedCommand)) {
266
268
  printCLIUsage();
@@ -1008,6 +1010,24 @@ async function handleCLICommands() {
1008
1010
  process.exit(result.status ?? 0);
1009
1011
  return true;
1010
1012
  }
1013
+ case 'rich': {
1014
+ const { spawnSync } = require('child_process');
1015
+ const scriptArgs = buildRuntimeScriptArgs({
1016
+ codeRoot: __dirname,
1017
+ scriptSegments: ['scripts', 'rich_list'],
1018
+ scriptArgs: cliArgs.slice(1),
1019
+ });
1020
+ const result = spawnSync(Config.EXEC_PATH, scriptArgs, {
1021
+ cwd: PATHS.PROJECT_ROOT,
1022
+ stdio: 'inherit',
1023
+ });
1024
+ if (result.error) {
1025
+ console.error(`rich: ${result.error.message}`);
1026
+ process.exit(1);
1027
+ }
1028
+ process.exit(result.status ?? 0);
1029
+ return true;
1030
+ }
1011
1031
  case 'git': {
1012
1032
  // Repository statistics analyzer (scripts/analyze-git.ts): parses
1013
1033
  // git history and writes analysis/charts/repo-stats.html. Git-only;