dexbot 1.6.8 → 1.6.10

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (70) hide show
  1. package/CHANGELOG.md +42 -0
  2. package/analysis/README.md +1 -1
  3. package/analysis/tradingview/README.md +14 -9
  4. package/claw/modules/chain_queries.ts +9 -4
  5. package/claw/modules/claw_bridge.ts +9 -9
  6. package/claw/package.json +1 -1
  7. package/claw/runtimes/openclaw-plugin/openclaw.plugin.json +1 -1
  8. package/claw/runtimes/openclaw-plugin/package.json +1 -1
  9. package/dist/analysis/ama_fitting/optimizer_high_resolution.js +2 -1
  10. package/dist/analysis/bot_fitting/backtest_ama_sweep.js +2 -2
  11. package/dist/analysis/bot_fitting/backtest_bot_fitting.js +4 -4
  12. package/dist/analysis/bot_key_utils.js +14 -4
  13. package/dist/analysis/tradingview/analyze_tradingview.d.ts +0 -3
  14. package/dist/analysis/tradingview/analyze_tradingview.js +3 -14
  15. package/dist/analysis/tradingview/grid_reset_sim.d.ts +11 -1
  16. package/dist/analysis/tradingview/grid_reset_sim.js +22 -9
  17. package/dist/analysis/tradingview/tradingview_uplot_chart_generator.js +178 -32
  18. package/dist/analysis/trend_detection/dynamic_weight_chart_generator.js +8 -3
  19. package/dist/dexbot.js +57 -29
  20. package/dist/market_adapter/core/market_adapter_service.d.ts +81 -1
  21. package/dist/market_adapter/core/market_adapter_service.js +225 -18
  22. package/dist/market_adapter/core/signals/hurst_analyzer.d.ts +10 -1
  23. package/dist/market_adapter/core/signals/hurst_analyzer.js +40 -18
  24. package/dist/market_adapter/core/signals/permutation_entropy_analyzer.d.ts +26 -2
  25. package/dist/market_adapter/core/signals/permutation_entropy_analyzer.js +132 -29
  26. package/dist/market_adapter/core/strategies/ama_slope_model.d.ts +2 -2
  27. package/dist/market_adapter/core/strategies/ama_slope_model.js +12 -10
  28. package/dist/market_adapter/core/strategies/dynamic_weight_series.d.ts +41 -14
  29. package/dist/market_adapter/core/strategies/dynamic_weight_series.js +138 -30
  30. package/dist/market_adapter/core/strategies/regime_gate.d.ts +61 -3
  31. package/dist/market_adapter/core/strategies/regime_gate.js +207 -7
  32. package/dist/market_adapter/interval_utils.d.ts +18 -1
  33. package/dist/market_adapter/interval_utils.js +31 -1
  34. package/dist/market_adapter/lp_chart_strategy_loader.js +2 -1
  35. package/dist/market_adapter/market_adapter.d.ts +151 -2
  36. package/dist/market_adapter/market_adapter.js +378 -62
  37. package/dist/market_adapter/test_helpers.d.ts +2 -2
  38. package/dist/market_adapter/test_helpers.js +2 -2
  39. package/dist/market_adapter/utils/chain.d.ts +1 -1
  40. package/dist/market_adapter/utils/chain.js +8 -6
  41. package/dist/market_adapter/utils/file_json_cache.d.ts +29 -0
  42. package/dist/market_adapter/utils/file_json_cache.js +106 -0
  43. package/dist/modules/account_bots.js +5 -4
  44. package/dist/modules/bitshares-native/resolvers.js +5 -0
  45. package/dist/modules/bot_settings.js +13 -1
  46. package/dist/modules/chain_orders.js +2 -1
  47. package/dist/modules/config.d.ts +6 -0
  48. package/dist/modules/config.js +1 -0
  49. package/dist/modules/constants.d.ts +11 -1
  50. package/dist/modules/constants.js +64 -15
  51. package/dist/modules/credential_policy.js +4 -1
  52. package/dist/modules/credit_runtime.js +5 -1
  53. package/dist/modules/order/grid.js +95 -25
  54. package/dist/modules/order/utils/system.js +11 -1
  55. package/dist/modules/utils/asset_symbols.d.ts +59 -0
  56. package/dist/modules/utils/asset_symbols.js +128 -0
  57. package/dist/modules/version_notice.d.ts +166 -20
  58. package/dist/modules/version_notice.js +401 -56
  59. package/dist/pm2.js +9 -2
  60. package/dist/scripts/analyze-credit.js +10 -7
  61. package/dist/scripts/chart_command.js +12 -4
  62. package/dist/scripts/verify-browser-bundle.js +8 -0
  63. package/dist/unlock.js +7 -7
  64. package/docs/DEXBOT_COMPARISON.md +3 -3
  65. package/docs/EVOLUTION.md +14 -12
  66. package/docs/FUND_MOVEMENT_AND_ACCOUNTING.md +1 -1
  67. package/docs/GRID_RECALCULATION.md +28 -5
  68. package/docs/README.md +2 -2
  69. package/market_adapter/README.md +30 -2
  70. package/package.json +1 -1
@@ -1,6 +1,19 @@
1
1
  declare const AMA_SLOPE_PERCENT_MODE_PER_BAR = "perBar";
2
2
  declare function normalizeAmaSlopePercentMode(value: any): "perBar" | "window" | null;
3
3
  declare function convertSlopePercentToPerBar(value: any, lookbackBars: any, mode: any): number | null;
4
+ /**
5
+ * Standing repair verdict for a PERSISTED STATE entry — the summary the
6
+ * previous cycle wrote. Returns a reason string when repair is still owed,
7
+ * null when the cache is clean.
8
+ *
9
+ * State-side mirror of candleFileCoversClosedBucket: that gate judges the
10
+ * on-disk candle file, this one judges the state summary, and the two must
11
+ * describe the same standing conditions so the startup sleep and the in-cycle
12
+ * skip cannot silently disagree. When a new standing signal is added to one,
13
+ * add it to the other (source/newest-candle checks are file-only and cannot
14
+ * appear here; unresolvedGapCount and the warmup shortfall exist in both).
15
+ */
16
+ declare function evaluateStateRepairVeto(entry: any): "unresolved_gaps" | "cache_count_unknown" | "cache_below_warmup_target" | null;
4
17
  declare class MarketAdapterService {
5
18
  deps: any;
6
19
  constructor(deps?: any);
@@ -16,6 +29,73 @@ declare class MarketAdapterService {
16
29
  * deeper history than the analytical minimum.
17
30
  */
18
31
  bootstrapKibanaLookbackHours(cfg: any, keepCount: any): number;
32
+ /**
33
+ * Closed-bucket arithmetic shared by the off-hour skip logic.
34
+ *
35
+ * Thin instance wrapper around the shared bucket helper so the `getNowMs`
36
+ * injection used by tests and embedders keeps working. `intervalSeconds`
37
+ * is validated by the helper: a missing/invalid interval can never
38
+ * masquerade as "nothing new" — it returns null and the caller must fall
39
+ * through to the network path instead of skipping a cycle it cannot
40
+ * evaluate.
41
+ */
42
+ latestClosedBucketStartMs(intervalSeconds: any, nowMs?: any): number | null;
43
+ /**
44
+ * Off-hour skip check: is there any closed candle this bot has not
45
+ * consumed yet? Runs on persisted state + the wall clock only — no
46
+ * chain RPC, no candle parse. Returns null when the answer cannot be
47
+ * determined (invalid interval, unknown state shape, one-shot mode), in
48
+ * which case the caller must run the full cycle instead of skipping.
49
+ *
50
+ * `once` (the `--once` CLI and the embedded runOnceForAma) always runs the
51
+ * full cycle: those entry points exist to *produce* a result on demand —
52
+ * the signal runner prints the AMA, an operator asks for a fresh cycle —
53
+ * and returning a state-only "skipped" record with null prices would
54
+ * quietly degrade their output. Only the long-running daemon, which has a
55
+ * schedule of its own, may answer "nothing new, skipping".
56
+ *
57
+ * The verdict requires the consumed marker to equal the newest closed
58
+ * bucket exactly. A marker AHEAD of that bucket means the two clocks
59
+ * disagree (clock skew, a state file carried across hosts, a synthetic
60
+ * fixture); skipping there would discard a candle the adapter may not
61
+ * actually have processed, so the conservative answer is always "run".
62
+ *
63
+ * Skipped bots still refresh `lastCycleAt`/`lastCycleSource` in state so
64
+ * monitoring can tell "idle by design" apart from "dead process".
65
+ */
66
+ shouldSkipBotForClosedCandle(_bot: any, botState: any, intervalSeconds: any, nowMs?: any, cfg?: any): {
67
+ latestClosedBucketStartMs: number;
68
+ previousClosedCandleTs: number;
69
+ } | null;
70
+ /**
71
+ * Does the cached candle file belong to a different market source than the
72
+ * bot is configured for?
73
+ *
74
+ * Single source of truth for the reset rule: the off-hour gate
75
+ * (candleFileCoversClosedBucket) and the full path must agree, otherwise a
76
+ * source switch could be skipped off-hour and the cache would keep serving
77
+ * candles from the old source until the next close forced a full run.
78
+ * The pool/book cross-checks matter for legacy caches that predate
79
+ * `meta.marketSource`: a stored pool id alongside a book-configured bot (or
80
+ * a book cache under a pool bot) is just as much a mismatch.
81
+ */
82
+ isCandleSourceMismatch(meta: any, marketSource: any): boolean;
83
+ /**
84
+ * Does the local candle cache already hold the data for a closed bucket?
85
+ *
86
+ * Second half of the off-hour skip verdict (see
87
+ * shouldSkipBotForClosedCandle): the full cycle repairs history even
88
+ * without a new close (Kibana backfill, gap fill), so skipping is only
89
+ * safe when the cache is healthy for that bucket. False whenever
90
+ * anything needs repair: a source switch, unresolved gaps, an empty or
91
+ * short file (fewer candles than the AMA warmup target — the exact case
92
+ * the backfill path exists for), or a newest candle that predates the
93
+ * bucket.
94
+ *
95
+ * The state-side mirror of the standing conditions (unresolved gaps, warmup
96
+ * shortfall) is evaluateStateRepairVeto above; keep the two in step.
97
+ */
98
+ candleFileCoversClosedBucket(candles: any, meta: any, marketSource: any, closedBucketStartMs: any, requiredCount?: any): boolean;
19
99
  selectClosedCandles(candles: any, intervalSeconds: any, nowMs?: any): {
20
100
  closedCandles: any[];
21
101
  currentBucketStartMs: null;
@@ -231,5 +311,5 @@ declare class MarketAdapterService {
231
311
  };
232
312
  processBot(bot: any, state: any, cfg: any, contextCache: any, hooks?: any): Promise<any>;
233
313
  }
234
- export { MarketAdapterService, AMA_SLOPE_PERCENT_MODE_PER_BAR, normalizeAmaSlopePercentMode, convertSlopePercentToPerBar };
314
+ export { MarketAdapterService, AMA_SLOPE_PERCENT_MODE_PER_BAR, normalizeAmaSlopePercentMode, convertSlopePercentToPerBar, evaluateStateRepairVeto };
235
315
  //# sourceMappingURL=market_adapter_service.d.ts.map
@@ -2,6 +2,7 @@
2
2
  import { calculateATR } from './strategies/atr/calculator.js';
3
3
  import { normalizeMarketSource, hasNumericStartPrice, resolveMarketSourceForBot } from '../utils/chain.js';
4
4
  import { computeRegimeMultiplier } from './strategies/regime_gate.js';
5
+ import { noteJsonWritten, readCachedJson } from '../utils/file_json_cache.js';
5
6
  import { calculateAMA, getAmaWarmupBars } from './strategies/ama.js';
6
7
  import { computeDynamicWeightSeries } from './strategies/dynamic_weight_series.js';
7
8
  import { KalmanTrendAnalyzer } from './signals/kalman_trend_analyzer.js';
@@ -16,6 +17,7 @@ import { normalizeAtrPeriod, normalizeMaxVolatilityOffset, normalizeVolatilityTh
16
17
  import { buildKalmanVelocitySeries, computeAbsolutePercentileThreshold, } from './signals/kalman_velocity_smoothing.js';
17
18
  import { resolveMaxAsymmetryFactor, computeAsymmetricBoundsMetrics, } from './asymmetric_bounds.js';
18
19
  import { getErrorMessage } from '../../modules/utils/errors.js';
20
+ import { bucketStartMs, latestClosedBucketStartMs as latestClosedBucket } from '../interval_utils.js';
19
21
  const marketAdapterServiceLogger = new Logger('MarketAdapterService');
20
22
  const AMA_SLOPE_PERCENT_MODE_PER_BAR = 'perBar';
21
23
  const AMA_SLOPE_PERCENT_MODE_WINDOW = 'window';
@@ -94,6 +96,34 @@ function computeGridPriceOffsetPlan(bot, amaSlope) {
94
96
  gridPriceOffsetPct,
95
97
  };
96
98
  }
99
+ /**
100
+ * Standing repair verdict for a PERSISTED STATE entry — the summary the
101
+ * previous cycle wrote. Returns a reason string when repair is still owed,
102
+ * null when the cache is clean.
103
+ *
104
+ * State-side mirror of candleFileCoversClosedBucket: that gate judges the
105
+ * on-disk candle file, this one judges the state summary, and the two must
106
+ * describe the same standing conditions so the startup sleep and the in-cycle
107
+ * skip cannot silently disagree. When a new standing signal is added to one,
108
+ * add it to the other (source/newest-candle checks are file-only and cannot
109
+ * appear here; unresolvedGapCount and the warmup shortfall exist in both).
110
+ */
111
+ function evaluateStateRepairVeto(entry) {
112
+ if (Number(entry?.unresolvedGapCount) > 0)
113
+ return 'unresolved_gaps';
114
+ const keepTarget = Number(entry?.rawKeepCount);
115
+ if (!Number.isFinite(keepTarget) || keepTarget <= 0)
116
+ return null;
117
+ const candleCount = Number(entry?.candleCount);
118
+ // Target known but current count unknown is NOT "nothing owed": an
119
+ // older or half-written row would otherwise read as healthy. Veto, and
120
+ // let the next full cycle rewrite the row with both fields.
121
+ if (!Number.isFinite(candleCount))
122
+ return 'cache_count_unknown';
123
+ if (candleCount < keepTarget)
124
+ return 'cache_below_warmup_target';
125
+ return null;
126
+ }
97
127
  class MarketAdapterService {
98
128
  deps;
99
129
  constructor(deps = {}) {
@@ -130,18 +160,123 @@ class MarketAdapterService {
130
160
  : 1;
131
161
  return Math.max(Number(cfg?.bootstrapLookbackHours) || 0, Number(keepCount) * intervalHours);
132
162
  }
163
+ /**
164
+ * Closed-bucket arithmetic shared by the off-hour skip logic.
165
+ *
166
+ * Thin instance wrapper around the shared bucket helper so the `getNowMs`
167
+ * injection used by tests and embedders keeps working. `intervalSeconds`
168
+ * is validated by the helper: a missing/invalid interval can never
169
+ * masquerade as "nothing new" — it returns null and the caller must fall
170
+ * through to the network path instead of skipping a cycle it cannot
171
+ * evaluate.
172
+ */
173
+ latestClosedBucketStartMs(intervalSeconds, nowMs = this.getNowMs()) {
174
+ return latestClosedBucket(nowMs, intervalSeconds);
175
+ }
176
+ /**
177
+ * Off-hour skip check: is there any closed candle this bot has not
178
+ * consumed yet? Runs on persisted state + the wall clock only — no
179
+ * chain RPC, no candle parse. Returns null when the answer cannot be
180
+ * determined (invalid interval, unknown state shape, one-shot mode), in
181
+ * which case the caller must run the full cycle instead of skipping.
182
+ *
183
+ * `once` (the `--once` CLI and the embedded runOnceForAma) always runs the
184
+ * full cycle: those entry points exist to *produce* a result on demand —
185
+ * the signal runner prints the AMA, an operator asks for a fresh cycle —
186
+ * and returning a state-only "skipped" record with null prices would
187
+ * quietly degrade their output. Only the long-running daemon, which has a
188
+ * schedule of its own, may answer "nothing new, skipping".
189
+ *
190
+ * The verdict requires the consumed marker to equal the newest closed
191
+ * bucket exactly. A marker AHEAD of that bucket means the two clocks
192
+ * disagree (clock skew, a state file carried across hosts, a synthetic
193
+ * fixture); skipping there would discard a candle the adapter may not
194
+ * actually have processed, so the conservative answer is always "run".
195
+ *
196
+ * Skipped bots still refresh `lastCycleAt`/`lastCycleSource` in state so
197
+ * monitoring can tell "idle by design" apart from "dead process".
198
+ */
199
+ shouldSkipBotForClosedCandle(_bot, botState, intervalSeconds, nowMs = this.getNowMs(), cfg = null) {
200
+ if (cfg?.once)
201
+ return null;
202
+ if (!botState || typeof botState !== 'object' || Array.isArray(botState))
203
+ return null;
204
+ const latestClosed = this.latestClosedBucketStartMs(intervalSeconds, nowMs);
205
+ if (latestClosed === null)
206
+ return null;
207
+ const previousClosedCandleTs = Number(botState.lastClosedCandleTs || 0);
208
+ // No consumed marker yet (fresh state / cleared state): the full
209
+ // cycle must run — bootstrap and warmup checks live there.
210
+ if (!Number.isFinite(previousClosedCandleTs) || previousClosedCandleTs <= 0)
211
+ return null;
212
+ if (latestClosed === previousClosedCandleTs) {
213
+ return { latestClosedBucketStartMs: latestClosed, previousClosedCandleTs };
214
+ }
215
+ return null;
216
+ }
217
+ /**
218
+ * Does the cached candle file belong to a different market source than the
219
+ * bot is configured for?
220
+ *
221
+ * Single source of truth for the reset rule: the off-hour gate
222
+ * (candleFileCoversClosedBucket) and the full path must agree, otherwise a
223
+ * source switch could be skipped off-hour and the cache would keep serving
224
+ * candles from the old source until the next close forced a full run.
225
+ * The pool/book cross-checks matter for legacy caches that predate
226
+ * `meta.marketSource`: a stored pool id alongside a book-configured bot (or
227
+ * a book cache under a pool bot) is just as much a mismatch.
228
+ */
229
+ isCandleSourceMismatch(meta, marketSource) {
230
+ const storedSource = normalizeMarketSource(meta?.marketSource);
231
+ const hasStoredPoolContext = meta?.pool != null && String(meta.pool).trim() !== '';
232
+ return (!!storedSource && storedSource !== marketSource)
233
+ || (marketSource === 'book' && hasStoredPoolContext)
234
+ || (marketSource === 'pool' && storedSource === 'book');
235
+ }
236
+ /**
237
+ * Does the local candle cache already hold the data for a closed bucket?
238
+ *
239
+ * Second half of the off-hour skip verdict (see
240
+ * shouldSkipBotForClosedCandle): the full cycle repairs history even
241
+ * without a new close (Kibana backfill, gap fill), so skipping is only
242
+ * safe when the cache is healthy for that bucket. False whenever
243
+ * anything needs repair: a source switch, unresolved gaps, an empty or
244
+ * short file (fewer candles than the AMA warmup target — the exact case
245
+ * the backfill path exists for), or a newest candle that predates the
246
+ * bucket.
247
+ *
248
+ * The state-side mirror of the standing conditions (unresolved gaps, warmup
249
+ * shortfall) is evaluateStateRepairVeto above; keep the two in step.
250
+ */
251
+ candleFileCoversClosedBucket(candles, meta, marketSource, closedBucketStartMs, requiredCount = 0) {
252
+ if (!Number.isFinite(closedBucketStartMs) || closedBucketStartMs <= 0)
253
+ return false;
254
+ if (this.isCandleSourceMismatch(meta, marketSource))
255
+ return false;
256
+ if (Number(meta?.unresolvedGapCount) > 0)
257
+ return false;
258
+ if (!Array.isArray(candles) || candles.length === 0)
259
+ return false;
260
+ // Short history means the warmup/backfill path still has work to do.
261
+ const required = Number(requiredCount);
262
+ if (Number.isFinite(required) && required > 0 && candles.length < required)
263
+ return false;
264
+ const newestTs = Number(candles[candles.length - 1]?.[0]);
265
+ if (!Number.isFinite(newestTs))
266
+ return false;
267
+ return newestTs >= closedBucketStartMs;
268
+ }
133
269
  selectClosedCandles(candles, intervalSeconds, nowMs = this.getNowMs()) {
134
- const bucketMs = Number(intervalSeconds) * 1000;
135
- if (!Number.isFinite(bucketMs) || bucketMs <= 0) {
270
+ const currentBucketStart = bucketStartMs(nowMs, intervalSeconds);
271
+ if (currentBucketStart === null) {
136
272
  return {
137
273
  closedCandles: Array.isArray(candles) ? candles.slice() : [],
138
274
  currentBucketStartMs: null,
139
275
  };
140
276
  }
141
- const currentBucketStartMs = Math.floor(Number(nowMs) / bucketMs) * bucketMs;
142
277
  const closedCandles = (Array.isArray(candles) ? candles : [])
143
- .filter((c) => Array.isArray(c) && Number.isFinite(c[0]) && c[0] < currentBucketStartMs);
144
- return { closedCandles, currentBucketStartMs };
278
+ .filter((c) => Array.isArray(c) && Number.isFinite(c[0]) && c[0] < currentBucketStart);
279
+ return { closedCandles, currentBucketStartMs: currentBucketStart };
145
280
  }
146
281
  buildBotContextSignature(bot) {
147
282
  return [
@@ -627,6 +762,12 @@ class MarketAdapterService {
627
762
  regimeTable: cfg.regimeTable,
628
763
  hurstZoneBand: cfg.hurstZoneBand,
629
764
  peNodes: cfg.peNodes,
765
+ // Stable per-market key: lets the gate resume from the previous
766
+ // cycle's analyzer state instead of replaying the whole history.
767
+ // The gate still recomputes from scratch whenever the cached
768
+ // closes are not a prefix of the incoming window (gap repair,
769
+ // rewritten bar, shortened window) or a parameter changed.
770
+ cacheKey: `${bot?.botKey ?? 'bot'}:${cfg.intervalSeconds}`,
630
771
  });
631
772
  regimeMultiplier = regimeResult.isReady && Math.abs(regimeResult.multiplier - 1.0) >= absoluteThreshold
632
773
  ? regimeResult.multiplier
@@ -943,17 +1084,84 @@ class MarketAdapterService {
943
1084
  });
944
1085
  }
945
1086
  const botAma = deps.resolveAmaForBot(bot, ctx, cfg);
1087
+ // `botAma.enabled` is a derived invariant (always true): `gridPrice` is
1088
+ // the single switch that makes a bot AMA-driven, and
1089
+ // usesAmaGridPrice(bot) below is what actually gates AMA work for this
1090
+ // bot. This guard stays only so a future resolver that can fail to
1091
+ // resolve an AMA config cannot silently trade on a missing one.
946
1092
  if (!botAma.enabled) {
947
1093
  return { ok: false, reason: 'ama disabled' };
948
1094
  }
949
1095
  const lookbackBars = normalizeAmaSlopeLookbackBars(cfg.amaSlope?.lookbackBars);
950
1096
  const filePath = deps.candleFileForBot(bot.botKey, cfg.intervalSeconds);
951
- const existing = deps.loadJson(filePath, null);
1097
+ // mtime-validated read cache: the previous cycle serialized this very
1098
+ // file, so re-parsing ~250 KiB of JSON per bot per hour is pure waste.
1099
+ // The cache decides on the file's stat alone — an unstattable file (or a
1100
+ // storage adapter that reports no mtime) is never served from the cache
1101
+ // and always goes through the loader, so it can never serve stale data.
1102
+ // Injecting deps.loadJson does not change that decision; it only changes
1103
+ // what a cache miss parses.
1104
+ const existing = readCachedJson(filePath, () => deps.loadJson(filePath, null));
952
1105
  const existingMeta = existing?.meta && typeof existing.meta === 'object' ? existing.meta : {};
953
1106
  let existingCandles = Array.isArray(existing?.candles) ? existing.candles : [];
954
- const existingMarketSource = normalizeMarketSource(existingMeta.marketSource);
955
1107
  const marketSource = resolveMarketSourceForBot(bot) || 'pool';
956
1108
  const isBookSource = marketSource === 'book';
1109
+ // Retention targets, derived from the bot's own AMA parameters. Pure and
1110
+ // local, so they are computed before the off-hour gate below (which
1111
+ // needs the warmup target) and reused by the full path unchanged.
1112
+ const amaWarmupBars = getAmaWarmupBars(botAma.erPeriod, botAma.slowPeriod, lookbackBars, botAma.fastPeriod, botAma.erSmoothPeriod ?? 0);
1113
+ const analysisKeepCount = amaWarmupBars + 1;
1114
+ // Retain one extra raw candle so the closed-candle analysis window still keeps a
1115
+ // full warmup/history set when the newest bucket is the current in-progress bar.
1116
+ const rawKeepCount = analysisKeepCount + 1;
1117
+ // Off-hour skip: the newest closed 1h bucket is already consumed, so
1118
+ // this bot cannot produce a new AMA, trigger, or snapshot this cycle.
1119
+ // Skip BEFORE the stale-tail Kibana verification and the native
1120
+ // overlap fetch below — on a mid-hour restart those are pure waste
1121
+ // (a per-bot RPC fetch, a Kibana round trip, and a ~250 KiB candle
1122
+ // re-serialize) for zero new information. Every input is already
1123
+ // local: persisted state, the candle file we just read, and the wall
1124
+ // clock. Note the chain connection itself is NOT saved here — the
1125
+ // daemon already opened it before runOnce; that socket is closed right
1126
+ // after the cycle, and the startup sleep is what avoids opening one.
1127
+ //
1128
+ // The local candle file is part of the verdict on purpose. The full
1129
+ // cycle also repairs history (Kibana backfill, gap fill) even when no
1130
+ // new candle closed, so a bot whose cache does not yet COVER the
1131
+ // newest closed bucket — short history, unresolved gaps, a source
1132
+ // change — must still run. Only a bot that has demonstrably consumed
1133
+ // that bucket and holds the data for it is skipped.
1134
+ const persistedBotState = (state?.bots && typeof state.bots === 'object')
1135
+ ? state.bots[bot.botKey]
1136
+ : null;
1137
+ const offHourSkip = this.shouldSkipBotForClosedCandle(bot, persistedBotState, cfg.intervalSeconds, undefined, cfg);
1138
+ const offHourSkipCovered = !!offHourSkip && this.candleFileCoversClosedBucket(existingCandles, existingMeta, marketSource, offHourSkip.latestClosedBucketStartMs, rawKeepCount);
1139
+ if (offHourSkip && offHourSkipCovered) {
1140
+ const skipNowIso = new Date().toISOString();
1141
+ const skipThreshold = typeof deps.calculateBotThreshold === 'function'
1142
+ ? deps.calculateBotThreshold(cfg)
1143
+ : null;
1144
+ const skippedState = {
1145
+ ...(persistedBotState && typeof persistedBotState === 'object' ? persistedBotState : {}),
1146
+ botName: bot.name,
1147
+ botKey: bot.botKey,
1148
+ lastCycleSource: 'off-hour-skip',
1149
+ lastCycleAt: skipNowIso,
1150
+ pendingClosedCandle: true,
1151
+ lastTriggerSuppressedReason: 'waiting_for_new_closed_candle',
1152
+ };
1153
+ state.bots[bot.botKey] = skippedState;
1154
+ return this.buildDefaultResult(bot, {
1155
+ dryRunMessages,
1156
+ source: 'off-hour-skip',
1157
+ thresholdPercent: skipThreshold,
1158
+ triggerSuppressedReason: 'waiting_for_new_closed_candle',
1159
+ lastCandleTs: persistedBotState?.lastCandleTs ?? null,
1160
+ rawLastCandleTs: persistedBotState?.rawLastCandleTs ?? null,
1161
+ lastClosedCandleTs: offHourSkip.previousClosedCandleTs || null,
1162
+ pendingClosedCandle: true,
1163
+ });
1164
+ }
957
1165
  const kibanaRequestTimeoutMs = Number.isFinite(cfg.kibanaRequestTimeoutMs) && cfg.kibanaRequestTimeoutMs > 0
958
1166
  ? cfg.kibanaRequestTimeoutMs
959
1167
  : MARKET_ADAPTER.KIBANA_REQUEST_TIMEOUT_MS;
@@ -1055,10 +1263,7 @@ class MarketAdapterService {
1055
1263
  existingCandles = verified.candles;
1056
1264
  applyStaleTailVerificationMeta(verified);
1057
1265
  }
1058
- const hasStoredPoolContext = existingMeta.pool != null && String(existingMeta.pool).trim() !== '';
1059
- const sourceMismatch = (existingMarketSource && existingMarketSource !== marketSource)
1060
- || (marketSource === 'book' && hasStoredPoolContext)
1061
- || (marketSource === 'pool' && existingMarketSource === 'book');
1266
+ const sourceMismatch = this.isCandleSourceMismatch(existingMeta, marketSource);
1062
1267
  if (sourceMismatch) {
1063
1268
  existingCandles = [];
1064
1269
  existingMeta.nativeRecentTradeSequences = [];
@@ -1067,11 +1272,6 @@ class MarketAdapterService {
1067
1272
  existingMeta.staleTailVerifiedEndTs = null;
1068
1273
  }
1069
1274
  const needBootstrap = existingCandles.length === 0;
1070
- const amaWarmupBars = getAmaWarmupBars(botAma.erPeriod, botAma.slowPeriod, lookbackBars, botAma.fastPeriod, botAma.erSmoothPeriod ?? 0);
1071
- const analysisKeepCount = amaWarmupBars + 1;
1072
- // Retain one extra raw candle so the closed-candle analysis window still keeps a
1073
- // full warmup/history set when the newest bucket is the current in-progress bar.
1074
- const rawKeepCount = analysisKeepCount + 1;
1075
1275
  const nowIso = new Date().toISOString();
1076
1276
  const botThreshold = deps.calculateBotThreshold(cfg);
1077
1277
  if (!Number.isFinite(botThreshold) || botThreshold <= 0) {
@@ -1722,6 +1922,9 @@ class MarketAdapterService {
1722
1922
  candles: nextCandles,
1723
1923
  };
1724
1924
  deps.saveJson(filePath, candlePayload);
1925
+ // The object just serialized IS the file's content now, so the next
1926
+ // cycle's read can skip the parse.
1927
+ noteJsonWritten(filePath, candlePayload);
1725
1928
  if (!hasNewClosedCandle) {
1726
1929
  const { staleData, staleAgeHours } = deps.computeCandleStaleness(lastClosedCandleTs, cfg.maxStaleHours);
1727
1930
  const pendingClosedCandle = !staleData;
@@ -1868,7 +2071,11 @@ class MarketAdapterService {
1868
2071
  const amaSlopeThresholdPercent = amaSlopeResetDetails.thresholdPercent;
1869
2072
  // 4. Advisory collateral-ratio hint only; execution is owned by the debt runtime.
1870
2073
  const collateralRecommendation = canExposeDynamicWeights ? adjustCollateralRatio(slopeResult, 1.5, 2.0) : null;
1871
- const amaComparison = deps.calcAmaComparison(analysisCandles, bot, ctx);
2074
+ // Reports the single AMA this bot trades on (its own resolved
2075
+ // parameters, value already computed above as `amaPrice`). No extra
2076
+ // calculateAMA pass: the AMA1..AMA4 preset sweep this replaced fed
2077
+ // nothing but a log line.
2078
+ const amaComparison = deps.buildAmaRecord(botAma, amaPrice);
1872
2079
  const closedCandleTs = lastCandle[0] || null;
1873
2080
  const { staleData, staleAgeHours } = deps.computeCandleStaleness(closedCandleTs, cfg.maxStaleHours);
1874
2081
  const referencePrice = amaPrice;
@@ -2321,5 +2528,5 @@ class MarketAdapterService {
2321
2528
  };
2322
2529
  }
2323
2530
  }
2324
- export { MarketAdapterService, AMA_SLOPE_PERCENT_MODE_PER_BAR, normalizeAmaSlopePercentMode, convertSlopePercentToPerBar };
2531
+ export { MarketAdapterService, AMA_SLOPE_PERCENT_MODE_PER_BAR, normalizeAmaSlopePercentMode, convertSlopePercentToPerBar, evaluateStateRepairVeto };
2325
2532
  //# sourceMappingURL=market_adapter_service.js.map
@@ -1,3 +1,8 @@
1
+ /**
2
+ * Compute R/S (rescaled range) over `returns[from..to)` (to exclusive).
3
+ * Taking a range instead of a slice keeps the caller's buffer reusable.
4
+ */
5
+ declare function computeRS(returns: ArrayLike<number>, from: number, to: number): number;
1
6
  /**
2
7
  * Shared Hurst zone classification used by both HurstAnalyzer.getAnalysis()
3
8
  * and the regime gate, so the zone boundaries live in exactly one place.
@@ -10,8 +15,12 @@ declare function classifyHurst(h: number, band?: number): {
10
15
  declare class HurstAnalyzer {
11
16
  private _w;
12
17
  window: number;
18
+ /** Bars of history this analyzer's state depends on (see bufferBars use in the regime gate). */
19
+ bufferBars: number;
13
20
  scales: number[];
14
21
  private _prices;
22
+ private _returns;
23
+ private _priceCount;
15
24
  private _updateCount;
16
25
  hurst: number;
17
26
  isReady: boolean;
@@ -44,5 +53,5 @@ declare class HurstAnalyzer {
44
53
  updateCount: number;
45
54
  };
46
55
  }
47
- export { HurstAnalyzer, classifyHurst };
56
+ export { HurstAnalyzer, classifyHurst, computeRS };
48
57
  //# sourceMappingURL=hurst_analyzer.d.ts.map
@@ -17,6 +17,15 @@ import { roundTo } from '../../../modules/order/utils/math.js';
17
17
  * Algorithm: for each scale τ in config.scales, partition the log-return window into
18
18
  * non-overlapping chunks of length τ, compute average R/S per chunk, then OLS-fit
19
19
  * log(avgRS) vs log(τ) — the slope is the Hurst exponent.
20
+ *
21
+ * PERFORMANCE (2026-09): like the permutation-entropy analyzer, this one is
22
+ * re-created and re-fed the entire candle history for every bot on every hourly
23
+ * cycle. The previous implementation allocated `returns.slice(c*tau, ...)` for
24
+ * every R/S chunk (~30 arrays per bar, ~23k per bot per cycle) plus a fresh
25
+ * log-return array per bar. The buffers are now preallocated typed arrays and
26
+ * `computeRS` takes a [from, to) range instead of a slice, so `update()`
27
+ * allocates nothing. Measured on an 782-bar series: ~5 ms -> ~3 ms per bot per
28
+ * cycle with the same exponent (see tests/test_market_adapter_entropy_equivalence.ts).
20
29
  */
21
30
  /**
22
31
  * OLS slope of ys ~ slope * xs + intercept. Returns slope only.
@@ -34,18 +43,19 @@ function olsSlope(xs, ys) {
34
43
  return denom !== 0 ? (n * sumXY - sumX * sumY) / denom : 0.5;
35
44
  }
36
45
  /**
37
- * Compute R/S (rescaled range) for an array of log returns.
46
+ * Compute R/S (rescaled range) over `returns[from..to)` (to exclusive).
47
+ * Taking a range instead of a slice keeps the caller's buffer reusable.
38
48
  */
39
- function computeRS(returns) {
40
- const n = returns.length;
49
+ function computeRS(returns, from, to) {
50
+ const n = to - from;
41
51
  if (n < 2)
42
52
  return 0;
43
53
  let sum = 0;
44
- for (let i = 0; i < n; i++)
54
+ for (let i = from; i < to; i++)
45
55
  sum += returns[i];
46
56
  const mean = sum / n;
47
57
  let cumDev = 0, maxCum = -Infinity, minCum = Infinity, sumSq = 0;
48
- for (let i = 0; i < n; i++) {
58
+ for (let i = from; i < to; i++) {
49
59
  const d = returns[i] - mean;
50
60
  cumDev += d;
51
61
  if (cumDev > maxCum)
@@ -84,8 +94,12 @@ function classifyHurst(h, band = MARKET_ADAPTER.HURST_ZONE_BAND) {
84
94
  class HurstAnalyzer {
85
95
  _w;
86
96
  window;
97
+ /** Bars of history this analyzer's state depends on (see bufferBars use in the regime gate). */
98
+ bufferBars;
87
99
  scales;
88
100
  _prices;
101
+ _returns;
102
+ _priceCount;
89
103
  _updateCount;
90
104
  hurst;
91
105
  isReady;
@@ -97,8 +111,14 @@ class HurstAnalyzer {
97
111
  constructor(config = {}) {
98
112
  this._w = Math.ceil(config.window ?? 128);
99
113
  this.window = this._w;
114
+ this.bufferBars = this._w + 1;
100
115
  this.scales = config.scales ?? [8, 16, 32, 64];
101
- this._prices = [];
116
+ // Rolling price buffer holds window+1 prices so returns span [0..window]
117
+ // and always include the newest bar (a window+2 cap would permanently
118
+ // exclude it). Returns reuse one buffer across every update.
119
+ this._prices = new Float64Array(this._w + 1);
120
+ this._returns = new Float64Array(this._w);
121
+ this._priceCount = 0;
102
122
  this._updateCount = 0;
103
123
  this.hurst = 0.5;
104
124
  this.isReady = false;
@@ -112,32 +132,34 @@ class HurstAnalyzer {
112
132
  if (!Number.isFinite(price) || price <= 0) {
113
133
  throw new Error('price must be a positive finite number');
114
134
  }
115
- this._prices.push(price);
116
- // Keep exactly window+1 prices so returns span [0..window] and always
117
- // include the newest bar (a window+2 cap would permanently exclude it).
118
- if (this._prices.length > this.window + 1)
119
- this._prices.shift();
135
+ const capacity = this._w + 1;
136
+ if (this._priceCount === capacity) {
137
+ this._prices.copyWithin(0, 1);
138
+ this._priceCount--;
139
+ }
140
+ this._prices[this._priceCount++] = price;
120
141
  this._updateCount++;
121
- if (this._prices.length < this.window + 1) {
142
+ if (this._priceCount < capacity) {
122
143
  this.isReady = false;
123
144
  return this.getAnalysis();
124
145
  }
125
146
  // Log returns over the rolling window
126
- const returns = new Array(this.window);
127
- for (let i = 0; i < this.window; i++) {
147
+ const w = this._w;
148
+ const returns = this._returns;
149
+ for (let i = 0; i < w; i++) {
128
150
  returns[i] = Math.log(this._prices[i + 1] / this._prices[i]);
129
151
  }
130
152
  // R/S at each scale → OLS slope
131
153
  const logRS = [], logTau = [];
132
154
  for (const τ of this.scales) {
133
- if (τ >= returns.length)
155
+ if (τ >= w)
134
156
  continue;
135
- const nChunks = Math.floor(returns.length / τ);
157
+ const nChunks = Math.floor(w / τ);
136
158
  if (nChunks < 1)
137
159
  continue;
138
160
  let sumRS = 0, count = 0;
139
161
  for (let c = 0; c < nChunks; c++) {
140
- const rs = computeRS(returns.slice(c * τ, (c + 1) * τ));
162
+ const rs = computeRS(returns, c * τ, (c + 1) * τ);
141
163
  if (rs > 0) {
142
164
  sumRS += rs;
143
165
  count++;
@@ -166,5 +188,5 @@ class HurstAnalyzer {
166
188
  };
167
189
  }
168
190
  }
169
- export { HurstAnalyzer, classifyHurst };
191
+ export { HurstAnalyzer, classifyHurst, computeRS };
170
192
  //# sourceMappingURL=hurst_analyzer.js.map
@@ -1,3 +1,13 @@
1
+ /**
2
+ * Ordinal pattern key for the m values starting at `prices[start]`, stepping by
3
+ * `delay`. Returns the permutation of source indices (sorted by value, ties
4
+ * broken by source index) encoded as a factorial-number-system integer, so the
5
+ * key is a small int (m! - 1 <= 5039 for m = 7) instead of a string.
6
+ *
7
+ * Sorting uses a preallocated scratch pair and insertion sort (m <= 7), so the
8
+ * hot path allocates nothing.
9
+ */
10
+ declare function ordinalPatternKey(prices: Float64Array, start: number, m: number, delay: number): number;
1
11
  interface PermutationEntropyAnalysis {
2
12
  isReady: boolean;
3
13
  entropy: number;
@@ -11,8 +21,11 @@ declare class PermutationEntropyAnalyzer {
11
21
  delay: number;
12
22
  window: number;
13
23
  _bufSize: number;
24
+ bufferBars: number;
14
25
  _maxEntropy: number;
15
- _prices: number[];
26
+ _prices: Float64Array;
27
+ _priceCount: number;
28
+ _counts: Map<number, number>;
16
29
  _updateCount: number;
17
30
  entropy: number;
18
31
  normalizedEntropy: number;
@@ -24,6 +37,17 @@ declare class PermutationEntropyAnalyzer {
24
37
  * @param {number} config.window - Rolling window of ordinal patterns (default 100)
25
38
  */
26
39
  constructor(config?: Record<string, number>);
40
+ /** Number of ordinal patterns currently inside a full buffer. */
41
+ private get _numPatterns();
42
+ private _addPattern;
43
+ private _removePattern;
44
+ /**
45
+ * Shannon entropy: H = -Σ p_k * log(p_k) over the live pattern counts.
46
+ * Iterating the (small, <= min(window, m!)) count map is cheaper than
47
+ * maintaining a running sum and keeps the arithmetic identical to counting
48
+ * the window from scratch.
49
+ */
50
+ private _entropyFromCounts;
27
51
  /**
28
52
  * Feed a new price and return analysis.
29
53
  * @param {number} price
@@ -32,5 +56,5 @@ declare class PermutationEntropyAnalyzer {
32
56
  update(price: number): PermutationEntropyAnalysis;
33
57
  getAnalysis(): PermutationEntropyAnalysis;
34
58
  }
35
- export { PermutationEntropyAnalyzer };
59
+ export { PermutationEntropyAnalyzer, ordinalPatternKey };
36
60
  //# sourceMappingURL=permutation_entropy_analyzer.d.ts.map