dexbot 1.6.8 → 1.6.9

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 (37) hide show
  1. package/CHANGELOG.md +24 -0
  2. package/claw/package.json +1 -1
  3. package/claw/runtimes/openclaw-plugin/openclaw.plugin.json +1 -1
  4. package/claw/runtimes/openclaw-plugin/package.json +1 -1
  5. package/dist/dexbot.js +44 -21
  6. package/dist/market_adapter/core/market_adapter_service.d.ts +81 -1
  7. package/dist/market_adapter/core/market_adapter_service.js +225 -18
  8. package/dist/market_adapter/core/signals/hurst_analyzer.d.ts +10 -1
  9. package/dist/market_adapter/core/signals/hurst_analyzer.js +40 -18
  10. package/dist/market_adapter/core/signals/permutation_entropy_analyzer.d.ts +26 -2
  11. package/dist/market_adapter/core/signals/permutation_entropy_analyzer.js +132 -29
  12. package/dist/market_adapter/core/strategies/regime_gate.d.ts +61 -3
  13. package/dist/market_adapter/core/strategies/regime_gate.js +207 -7
  14. package/dist/market_adapter/interval_utils.d.ts +18 -1
  15. package/dist/market_adapter/interval_utils.js +31 -1
  16. package/dist/market_adapter/market_adapter.d.ts +151 -2
  17. package/dist/market_adapter/market_adapter.js +378 -62
  18. package/dist/market_adapter/test_helpers.d.ts +2 -2
  19. package/dist/market_adapter/test_helpers.js +2 -2
  20. package/dist/market_adapter/utils/file_json_cache.d.ts +29 -0
  21. package/dist/market_adapter/utils/file_json_cache.js +106 -0
  22. package/dist/modules/config.d.ts +6 -0
  23. package/dist/modules/config.js +1 -0
  24. package/dist/modules/constants.d.ts +5 -1
  25. package/dist/modules/constants.js +41 -14
  26. package/dist/modules/order/grid.js +95 -25
  27. package/dist/modules/version_notice.d.ts +166 -20
  28. package/dist/modules/version_notice.js +401 -56
  29. package/dist/pm2.js +9 -2
  30. package/dist/unlock.js +7 -7
  31. package/docs/DEXBOT_COMPARISON.md +3 -3
  32. package/docs/EVOLUTION.md +13 -12
  33. package/docs/FUND_MOVEMENT_AND_ACCOUNTING.md +1 -1
  34. package/docs/GRID_RECALCULATION.md +6 -2
  35. package/docs/README.md +2 -2
  36. package/market_adapter/README.md +28 -0
  37. package/package.json +1 -1
@@ -6,6 +6,157 @@ import { roundTo } from '../../../modules/order/utils/math.js';
6
6
  import { bilinearInterpolate } from './regime_interp.js';
7
7
  const HURST_CONFIG = MARKET_ADAPTER.HURST_CONFIG;
8
8
  const PE_CONFIG = MARKET_ADAPTER.PE_CONFIG;
9
+ /**
10
+ * Cross-cycle memoization for the regime gate.
11
+ *
12
+ * The adapter runs one cycle per hour per bot, but only ONE new candle closes in
13
+ * that window, and the Hurst/PE state at bar i depends solely on the previous
14
+ * `window` prices. Re-creating both analyzers and re-feeding all ~780 closes
15
+ * every hour therefore recomputed ~99.8% of the same numbers — the single
16
+ * largest CPU item in a cycle.
17
+ *
18
+ * When the caller supplies a stable `cacheKey` (the adapter passes
19
+ * `<botKey>:<intervalSeconds>`), the analyzers and the already-computed
20
+ * per-bar series are kept per key. The next cycle resumes the memoized state
21
+ * when the regime parameters are unchanged and the incoming window is the
22
+ * cached one advanced: same bars, with k leading bars dropped and m new bars
23
+ * appended. A gap repair, a corrected bar, a rewritten value, a different
24
+ * market or a config change all fail that check and fall back to a full
25
+ * recomputation. The resumed result is bit-identical to a from-scratch run in
26
+ * the headline multiplier and in every bar from that run's first ready bar
27
+ * onwards; the pre-warmup prefix can differ by the one-bar readiness offset
28
+ * described below. See tests/test_market_adapter_entropy_equivalence.ts.
29
+ *
30
+ * The leading-drop tolerance is what makes this worthwhile in production: the
31
+ * adapter caps the analysis window (rawKeepCount + analysisKeepCount), so once
32
+ * history saturates every hourly cycle SLIDES the window by one bar. A
33
+ * strict "cached is a prefix of incoming" test misses every one of those
34
+ * cycles. It is safe because both analyzers are rolling: their state depends
35
+ * only on the last `bufferSize` bars, so as long as the shared region still
36
+ * covers that much history, feeding only the new bars lands on exactly the
37
+ * state a cold replay of the whole window would produce.
38
+ *
39
+ * What a resume does NOT reproduce: the warmup boundary in the historical
40
+ * prefix. A warm analyzer pair has been fed one more bar in total than a freshly
41
+ * created one, so it reports its first value one bar earlier. Only the prefix
42
+ * is affected — the headline multiplier and every bar from the cold run's first
43
+ * ready index onwards are identical, which is every bar the service can act on
44
+ * (regimeMultipliers scales a per-bar offset that is itself zero before the
45
+ * AMA/Kalman channels are ready). See
46
+ * tests/test_market_adapter_entropy_equivalence.ts.
47
+ *
48
+ * Without a `cacheKey` the function is stateless, exactly as before.
49
+ */
50
+ const REGIME_CACHE_LIMIT = 32;
51
+ const _regimeCache = new Map();
52
+ /**
53
+ * How many bars of history the analyzers' rolling state can depend on.
54
+ *
55
+ * Taken from the analyzer INSTANCES (each exposes `bufferBars`), never from a
56
+ * second copy of their constructor defaults: a mirrored formula silently
57
+ * under-estimates whenever a default or a buffer formula changes. Being too
58
+ * large only costs a missed resume; being too small would let the resume carry
59
+ * `cached.series` entries that were computed from bars the incoming window no
60
+ * longer contains (the analyzers' final state is unaffected either way — see
61
+ * _locateResume). An analyzer that does not report a usable size fails closed
62
+ * (MAX_SAFE_INTEGER), which disables resuming for that cache entry.
63
+ */
64
+ function _analyzerBufferSize(hurst, pe) {
65
+ const sizes = [Number(hurst?.bufferBars), Number(pe?.bufferBars)]
66
+ .filter((value) => Number.isFinite(value) && value > 0);
67
+ if (sizes.length !== 2)
68
+ return Number.MAX_SAFE_INTEGER;
69
+ return Math.max(sizes[0], sizes[1]);
70
+ }
71
+ /**
72
+ * Locate how `closes` advances the cached window, or null when they are not
73
+ * related that way.
74
+ *
75
+ * Returns `{ k, shared }` where `closes[0..shared)` is exactly
76
+ * `cached[k..cached.length)` — i.e. the incoming window dropped k leading bars
77
+ * and appended `closes.length - shared` new ones. `k = 0, shared =
78
+ * cached.length` is the plain "one or more bars were added" case.
79
+ *
80
+ * The shift is pinned by matching the cached window's newest bar inside the
81
+ * incoming window, then the ENTIRE shared region is verified, so a coincidental
82
+ * price match cannot pass. NaN-aware, like the pre-cache implementation.
83
+ *
84
+ * When the cached newest bar occurs at more than one position and more than one
85
+ * candidate alignment verifies, the window is ambiguous and the function
86
+ * declines to resume. This is hygiene, not a safety requirement: any verified
87
+ * alignment with `shared >= minShared` is exact by construction, because that
88
+ * requirement guarantees the resumed stream's last `bufferBars` values are the
89
+ * same values the incoming stream ends with — the analyzers are rolling, so
90
+ * their final state (and every series entry from that point on) is identical
91
+ * whichever alignment is chosen. Declining only avoids anchoring the
92
+ * `cached.series` carry-over — whose early entries rest on bars the window may
93
+ * no longer contain — to a pattern match we did not intend. It can only arise
94
+ * on degenerate periodic windows, and a cold recompute there is cheap and
95
+ * honest.
96
+ */
97
+ function _locateResume(cached, closes, minShared) {
98
+ if (cached.length === 0 || closes.length === 0)
99
+ return null;
100
+ if (cached.length > closes.length)
101
+ return null;
102
+ // Unchanged window: no scan needed, and no ambiguity to resolve.
103
+ if (cached.length === closes.length) {
104
+ let identical = true;
105
+ for (let i = 0; i < cached.length; i++) {
106
+ if (cached[i] === closes[i] || (Number.isNaN(cached[i]) && Number.isNaN(closes[i])))
107
+ continue;
108
+ identical = false;
109
+ break;
110
+ }
111
+ if (identical)
112
+ return minShared <= cached.length ? { k: 0, shared: cached.length } : null;
113
+ }
114
+ const newest = cached[cached.length - 1];
115
+ let found = null;
116
+ // Newest match first, so the alignment that drops the fewest bars wins.
117
+ for (let p = closes.length - 1; p >= 0; p--) {
118
+ if (!(closes[p] === newest || (Number.isNaN(closes[p]) && Number.isNaN(newest))))
119
+ continue;
120
+ const k = cached.length - 1 - p;
121
+ // k < 0 means the match sits beyond the cached window: not this
122
+ // alignment, but a smaller p may still hold the right one.
123
+ if (k < 0)
124
+ continue;
125
+ const shared = cached.length - k;
126
+ if (shared < minShared)
127
+ return null; // too little history survives the slide
128
+ let ok = true;
129
+ for (let j = k; j < cached.length; j++) {
130
+ const a = cached[j];
131
+ const b = closes[j - k];
132
+ if (a === b || (Number.isNaN(a) && Number.isNaN(b)))
133
+ continue;
134
+ ok = false;
135
+ break;
136
+ }
137
+ if (!ok)
138
+ continue;
139
+ if (found)
140
+ return null; // ambiguous: repeated closes
141
+ found = { k, shared };
142
+ }
143
+ return found;
144
+ }
145
+ function regimeParamsKey(sensitivity, regimeTable, hurstZoneBand, peNodes, hurstCfg, peCfg) {
146
+ return JSON.stringify([sensitivity, regimeTable, hurstZoneBand, peNodes, hurstCfg, peCfg]);
147
+ }
148
+ /**
149
+ * Drop all memoized analyzer state.
150
+ *
151
+ * A test seam today, not a runtime path: the cycle resolves its parameters once
152
+ * per run, so there is no in-process config reload to invalidate state for, and
153
+ * a parameter change is already detected by `regimeParamsKey` (it forces a full
154
+ * recompute). Production never calls this — it exists so a test can assert a
155
+ * cold run against a warm cache without leaking entries between cases.
156
+ */
157
+ function _resetRegimeCache() {
158
+ _regimeCache.clear();
159
+ }
9
160
  function resolvePeNodes(peNodes = null) {
10
161
  if (Array.isArray(peNodes) && peNodes.length === 3 && peNodes.every(Number.isFinite)) {
11
162
  return peNodes;
@@ -39,9 +190,13 @@ function classifyPeRegime(pe, peNodes = null) {
39
190
  * canonical pure implementation in strategies/regime_interp.ts (shared with the
40
191
  * browser-embedded chart scripts).
41
192
  *
42
- * Feeds all prices through HurstAnalyzer and PermutationEntropyAnalyzer,
193
+ * Feeds prices through HurstAnalyzer and PermutationEntropyAnalyzer,
43
194
  * then bilinear-interpolates the regime table to produce a multiplier that
44
- * gates the AMA slope offset in production weight computation.
195
+ * gates the AMA slope offset in production weight computation. When
196
+ * `opts.cacheKey` is set, a window that ADVANCES the memoized one (k leading
197
+ * bars dropped, m appended) resumes from the cached analyzer state and feeds
198
+ * only the appended bars; anything else recomputes from scratch. See the cache
199
+ * notes above.
45
200
  *
46
201
  * @param {number[]} closes - Full close price series (same array used for AMA)
47
202
  * @param {Object} [opts]
@@ -49,6 +204,7 @@ function classifyPeRegime(pe, peNodes = null) {
49
204
  * @param {Array} [opts.regimeTable] - Custom 3x3 regime multiplier table
50
205
  * @param {number} [opts.hurstZoneBand] - Override Hurst neutral-zone width
51
206
  * @param {Array} [opts.peNodes] - Override entropy thresholds
207
+ * @param {string} [opts.cacheKey] - Stable per-market key enabling cross-cycle reuse
52
208
  * @param {Object} [opts.hurstConfig] - Override for HurstAnalyzer config
53
209
  * @param {Object} [opts.peConfig] - Override for PermutationEntropyAnalyzer config
54
210
  * @returns {{ multiplier: number, hurst: number|null, pe: number|null,
@@ -67,6 +223,7 @@ function computeRegimeMultiplier(closes, opts = {}) {
67
223
  const peNodes = Array.isArray(opts.peNodes) ? opts.peNodes : MARKET_ADAPTER.PE_NODES;
68
224
  const hurstCfg = opts.hurstConfig ?? HURST_CONFIG;
69
225
  const peCfg = opts.peConfig ?? PE_CONFIG;
226
+ const cacheKey = typeof opts.cacheKey === 'string' && opts.cacheKey !== '' ? opts.cacheKey : null;
70
227
  // Clamp to 1.0 max: regime only dampens, never amplifies. The
71
228
  // sensitivity exponent is applied in one place for both the per-bar
72
229
  // series and the final value.
@@ -82,12 +239,31 @@ function computeRegimeMultiplier(closes, opts = {}) {
82
239
  };
83
240
  if (!Array.isArray(closes) || closes.length === 0)
84
241
  return notReady;
85
- const hurst = new HurstAnalyzer(hurstCfg);
86
- const pe = new PermutationEntropyAnalyzer(peCfg);
242
+ const paramsKey = regimeParamsKey(sensitivity, regimeTable, hurstZoneBand, peNodes, hurstCfg, peCfg);
243
+ const cached = cacheKey ? _regimeCache.get(cacheKey) : null;
244
+ const resume = (cached && cached.paramsKey === paramsKey)
245
+ ? _locateResume(cached.closes, closes, _analyzerBufferSize(cached.hurst, cached.pe))
246
+ : null;
247
+ const resumable = !!resume;
248
+ const hurst = resumable ? cached.hurst : new HurstAnalyzer(hurstCfg);
249
+ const pe = resumable ? cached.pe : new PermutationEntropyAnalyzer(peCfg);
250
+ // Index-aligned with `closes`, exactly like the pre-cache implementation.
251
+ // The neutral 1.0 fill also covers bars the loop below does not produce a
252
+ // value for (warmup, or a non-finite price it skips): a resumed run must
253
+ // never come back with a hole the cold path would have filled.
254
+ const series = new Array(closes.length).fill(1.0);
255
+ // cached.series[i] was computed for cached.closes[i] === closes[i - k].
256
+ const startIndex = resumable ? resume.shared : 0;
257
+ if (resumable) {
258
+ for (let i = 0; i < startIndex; i++) {
259
+ const carried = cached.series[i + resume.k];
260
+ if (carried !== undefined)
261
+ series[i] = carried;
262
+ }
263
+ }
87
264
  let hurstResult = null;
88
265
  let peResult = null;
89
- const series = new Array(closes.length).fill(1.0);
90
- for (let i = 0; i < closes.length; i++) {
266
+ for (let i = startIndex; i < closes.length; i++) {
91
267
  const price = closes[i];
92
268
  if (!Number.isFinite(price) || price <= 0)
93
269
  continue;
@@ -105,6 +281,30 @@ function computeRegimeMultiplier(closes, opts = {}) {
105
281
  // skip invalid prices (analyzers throw only on non-positive prices)
106
282
  }
107
283
  }
284
+ if (cacheKey) {
285
+ const entry = {
286
+ paramsKey,
287
+ closes: closes.slice(),
288
+ series: series.slice(),
289
+ hurst,
290
+ pe,
291
+ };
292
+ // Re-insert so the Map's insertion order stays a usable LRU order.
293
+ _regimeCache.delete(cacheKey);
294
+ _regimeCache.set(cacheKey, entry);
295
+ while (_regimeCache.size > REGIME_CACHE_LIMIT) {
296
+ const oldest = _regimeCache.keys().next();
297
+ if (oldest.done)
298
+ break;
299
+ _regimeCache.delete(oldest.value);
300
+ }
301
+ }
302
+ // A resumed cycle can legitimately have no new bar to feed (the window is
303
+ // unchanged since the last call); the analyzers already hold that state.
304
+ if (!hurstResult)
305
+ hurstResult = hurst.getAnalysis();
306
+ if (!peResult)
307
+ peResult = pe.getAnalysis();
108
308
  if (!hurstResult?.isReady || !peResult?.isReady)
109
309
  return notReady;
110
310
  const h = hurstResult.hurst;
@@ -121,5 +321,5 @@ function computeRegimeMultiplier(closes, opts = {}) {
121
321
  series: series.map((value) => roundTo(value, 1000)),
122
322
  };
123
323
  }
124
- export { computeRegimeMultiplier };
324
+ export { computeRegimeMultiplier, _resetRegimeCache, _locateResume, _analyzerBufferSize };
125
325
  //# sourceMappingURL=regime_gate.js.map
@@ -6,5 +6,22 @@ declare function toIntervalLabel(intervalSeconds: any): string;
6
6
  * fetch_book_data.ts and scripts/chart_command.ts.
7
7
  */
8
8
  declare function slugPart(value: any): string;
9
- export { toIntervalLabel, slugPart };
9
+ /**
10
+ * Start of the interval bucket that contains `nowMs` (floor on the bucket
11
+ * grid), or null when the interval or clock is unusable.
12
+ *
13
+ * Single home for the candle-grid arithmetic shared by the closed-candle
14
+ * gate, the startup-sleep verdict, the aligned-boundary sleep and candle
15
+ * selection. Keeping one implementation matters because the closed-bucket
16
+ * gate and the startup sleep must agree on "the newest closed bucket" by
17
+ * construction, not by two copies happening to match.
18
+ */
19
+ declare function bucketStartMs(nowMs: any, intervalSeconds: any): number | null;
20
+ /**
21
+ * Start of the newest FULLY CLOSED bucket as of `nowMs` — the bucket just
22
+ * before the one that contains `nowMs`. Null when `bucketStartMs` cannot
23
+ * evaluate the interval/clock.
24
+ */
25
+ declare function latestClosedBucketStartMs(nowMs: any, intervalSeconds: any): number | null;
26
+ export { toIntervalLabel, slugPart, bucketStartMs, latestClosedBucketStartMs };
10
27
  //# sourceMappingURL=interval_utils.d.ts.map
@@ -21,5 +21,35 @@ function slugPart(value) {
21
21
  .replace(/[^a-z0-9]+/g, '_')
22
22
  .replace(/^_+|_+$/g, '') || 'unknown';
23
23
  }
24
- export { toIntervalLabel, slugPart };
24
+ /**
25
+ * Start of the interval bucket that contains `nowMs` (floor on the bucket
26
+ * grid), or null when the interval or clock is unusable.
27
+ *
28
+ * Single home for the candle-grid arithmetic shared by the closed-candle
29
+ * gate, the startup-sleep verdict, the aligned-boundary sleep and candle
30
+ * selection. Keeping one implementation matters because the closed-bucket
31
+ * gate and the startup sleep must agree on "the newest closed bucket" by
32
+ * construction, not by two copies happening to match.
33
+ */
34
+ function bucketStartMs(nowMs, intervalSeconds) {
35
+ const bucketMs = Number(intervalSeconds) * 1000;
36
+ if (!Number.isFinite(bucketMs) || bucketMs <= 0)
37
+ return null;
38
+ const now = Number(nowMs);
39
+ if (!Number.isFinite(now) || now <= 0)
40
+ return null;
41
+ return Math.floor(now / bucketMs) * bucketMs;
42
+ }
43
+ /**
44
+ * Start of the newest FULLY CLOSED bucket as of `nowMs` — the bucket just
45
+ * before the one that contains `nowMs`. Null when `bucketStartMs` cannot
46
+ * evaluate the interval/clock.
47
+ */
48
+ function latestClosedBucketStartMs(nowMs, intervalSeconds) {
49
+ const currentBucketStart = bucketStartMs(nowMs, intervalSeconds);
50
+ if (currentBucketStart === null)
51
+ return null;
52
+ return currentBucketStart - Number(intervalSeconds) * 1000;
53
+ }
54
+ export { toIntervalLabel, slugPart, bucketStartMs, latestClosedBucketStartMs };
25
55
  //# sourceMappingURL=interval_utils.js.map
@@ -46,6 +46,109 @@ declare const DEFAULT_AMA: {
46
46
  slowPeriod: number;
47
47
  };
48
48
  declare function sleepUntilAlignedBoundary(pollSeconds: number, referenceNowMs?: any, nowMs?: any): number;
49
+ /**
50
+ * Sleep-first startup decision for the daemon.
51
+ *
52
+ * Returns `{ delayMs, veto }`: `delayMs` is how long to wait before the first
53
+ * cycle (0 = run a catch-up cycle now); `veto` is null when the adapter may
54
+ * sleep, otherwise `{ reason, botKeys }` saying why not. The wait uses the
55
+ * SAME poll boundary the loop aligns to (sleepUntilAlignedBoundary with
56
+ * cfg.pollSeconds, default 3600s), so the timing setting is honoured, not
57
+ * hardcoded.
58
+ *
59
+ * `veto` is non-null — and `delayMs` 0 — when:
60
+ * - state is fresh/empty (first run, cleared state — bootstrap lives in the
61
+ * cycle),
62
+ * - no in-scope bot has a consumed closed-candle marker yet,
63
+ * - ANY in-scope bot's consumed marker is not exactly the newest closed bucket
64
+ * (older = that bot still owes a cycle; newer = the clocks disagree, so do
65
+ * not trust the marker). Evaluated per bot, never aggregated: one lagging
66
+ * bot is invisible behind a max() over the others, and that bot is exactly
67
+ * what a catch-up cycle is for.
68
+ * - the candle interval is not the poll cadence, or the clock cannot be
69
+ * evaluated,
70
+ * - an active bot's last cycle left repair work still outstanding
71
+ * (unresolved gaps, or a cache shorter than its own warmup target),
72
+ * - an active bot has never been processed (no state row, or no consumed
73
+ * marker) — its bootstrap is still owed,
74
+ * - the active bot list cannot be read (then every state entry counts).
75
+ *
76
+ * The interval guard matters: the newest closed bucket is computed on the
77
+ * poll grid, while the markers in state are candle-bucket starts. With a
78
+ * mismatch (e.g. 2h candles polled hourly) the two grids only coincide by
79
+ * accident, and "coincide" here would delay a real cycle by up to one poll
80
+ * period. Refuse to sleep unless the grids are identical, i.e. unless one
81
+ * cycle per poll actually is one cycle per candle.
82
+ *
83
+ * One grid for every bot is correct because `intervalSeconds` is not in the
84
+ * per-pair/per-bot override whitelist, so all bots in a cycle share a bucket
85
+ * size. If that ever changes, the comparison has to become per bot.
86
+ *
87
+ * Otherwise it returns the wait until the next poll boundary. Mid-hour
88
+ * respawns (the common case: wrapper restart, crash recovery) therefore sleep
89
+ * instead of running a full cycle that the closed-candle gate would discard
90
+ * anyway. That wait is always shorter than one poll period, so at most one
91
+ * boundary is ever passed over: a candle that closes during the sleep is
92
+ * picked up by the very next cycle, never skipped.
93
+ *
94
+ * Only entries for bots the adapter would actually process are considered
95
+ * (activeBotKeys). A removed bot's leftover row, or a fixed-price bot, must
96
+ * not be able to defeat the sleep for everyone else — such an entry either
97
+ * has no marker at all or a marker that is months old. An active bot with NO
98
+ * row is treated exactly like an active bot with a row but no marker: both owe
99
+ * a bootstrap, so both veto the sleep and that bot goes live on the next cycle
100
+ * rather than up to a poll period later.
101
+ *
102
+ * Repair work is judged from the state entry, which records how the previous
103
+ * cycle ended. Two of its fields are deliberately distinguished:
104
+ *
105
+ * - `unresolvedGapCount` is a STANDING condition — it is measured on the final
106
+ * candle set, so a non-zero value means gaps are still missing right now.
107
+ * - `candleCount < rawKeepCount` is standing too: the cache has not reached
108
+ * the bot's own warmup target.
109
+ *
110
+ * `kibanaBackfillCount` is deliberately NOT consulted. It is an action count —
111
+ * how many candles the last completed cycle happened to fetch — and that cycle
112
+ * already applied them. A non-zero value means "repair was needed and was
113
+ * done", not "repair is owed". Because a skip carries the persisted entry
114
+ * forward, treating it as outstanding would keep vetoing the sleep after every
115
+ * backfill until some full cycle happened to rewrite the field with a zero.
116
+ * Cache shortness is the real signal, and it is checked directly above. The
117
+ * standing verdict is computed by evaluateStateRepairVeto in
118
+ * market_adapter_service.ts, immediately before the candle-file mirror
119
+ * (candleFileCoversClosedBucket), so a new standing signal is added once.
120
+ *
121
+ * None of this can see a config change made after that cycle (a grown AMA
122
+ * window, for instance): the backfill for that is then deferred to the next
123
+ * boundary, bounded by one poll period. Reading the state entry costs no extra
124
+ * I/O — no candle file is re-read and no connection is opened (the startup
125
+ * decision reads bots.json to build the active list, and each cycle reads it
126
+ * again).
127
+ *
128
+ * Known consequence of the "active bot with no row vetoes" rule: an active bot
129
+ * that can never reach a state write (unresolvable market, persistent
130
+ * pre-persist failure) keeps the sleep disabled for the whole daemon. That is
131
+ * intentional and fail-safe — healthy bots still take the in-cycle off-hour
132
+ * skip, so only the startup sleep is lost — and the veto is reported with its
133
+ * reason and bot keys so the situation is visible instead of silent.
134
+ */
135
+ declare function evaluateStartupSleep(cfg: any, state: any, nowMs?: any, activeBotKeys?: any): {
136
+ delayMs: number;
137
+ veto: {
138
+ reason: string;
139
+ botKeys: string[];
140
+ };
141
+ } | {
142
+ delayMs: number;
143
+ veto: null;
144
+ };
145
+ /**
146
+ * Numeric form of evaluateStartupSleep: the wait before the daemon's first
147
+ * cycle, or 0 to run a catch-up cycle now. The decision rules — and the reasons
148
+ * it can refuse — are documented there; this wrapper exists so callers that
149
+ * only need the wait do not have to unpack a verdict object.
150
+ */
151
+ declare function computeStartupDelayMs(cfg: any, state: any, nowMs?: any, activeBotKeys?: any): number;
49
152
  declare function resolveDeltaThresholdPercentFromGeneralSettings(settings: any): number | null;
50
153
  /**
51
154
  * Slope-trigger factor from general settings (`(value/100) × maxSlopePct`).
@@ -62,8 +165,54 @@ declare function computeCandleStaleness(lastCandleTs: any, maxStaleHours: any):
62
165
  staleData: boolean;
63
166
  staleAgeHours: number | null;
64
167
  };
168
+ /**
169
+ * Resolve the AMA configuration a bot trades on.
170
+ *
171
+ * Precedence, as implemented: when a market profile applies for the pair, the
172
+ * preset is chosen from the profile by the bot's `gridPrice` keyword, else the
173
+ * profile/`AMA3` default (a profile entry always wins over the bot's numeric
174
+ * `ama` block). Without a profile, the bot's own `ama` numbers are used, with
175
+ * the `gridPrice` keyword preset filling any missing period and AMA3 as the last
176
+ * resort.
177
+ *
178
+ * The winning preset key — or 'custom' when the numbers came from the bot's own
179
+ * `ama` block — rides along as `name`, so the cycle log and the state snapshot
180
+ * can state which AMA this bot runs without re-deriving it.
181
+ *
182
+ * `enabled` is a derived invariant, always true here. `gridPrice` is the single
183
+ * switch that decides whether a bot is AMA-driven — `usesAmaGridPrice()` reads
184
+ * it in the bot runtime, the maintenance runtime and the launcher — so an
185
+ * `ama.enabled` flag could only ever disagree with them. It used to: this
186
+ * function honoured it on the profile-less path and hardcoded `true` on the
187
+ * profile path, and because the bot side ignores the flag, honouring it froze
188
+ * the published center while the bot kept trading on it. Callers must gate AMA
189
+ * work on `usesAmaGridPrice(bot)`.
190
+ */
65
191
  declare function resolveAmaForBot(bot: any, ctx?: any, cfg?: any): any;
66
- declare function calcAmaComparison(candles: any, bot?: any, ctx?: any): any[];
192
+ /**
193
+ * Build the per-bot AMA record that is logged and persisted in the state file.
194
+ *
195
+ * It reports the ONE AMA the bot actually trades on — the value the cycle has
196
+ * already computed as `amaValues` — instead of re-running `calculateAMA` for the
197
+ * AMA1..AMA4 preset sweep. Those four extra passes cost ~0.3 ms each per bot per
198
+ * hour and fed nothing but the old "AMA compare:" log line: the presets are
199
+ * research knobs, not a signal, and the bot's price always came from its own
200
+ * configured parameters. So the comparison was 4 duplications of work whose
201
+ * result no decision, log consumer or dashboard ever read.
202
+ *
203
+ * The array shape (one entry, same fields) is kept so the state schema and the
204
+ * cycle log stay stable; the field is still called `amaComparison` in the
205
+ * persisted state for backwards compatibility with existing snapshots.
206
+ */
207
+ declare function buildAmaRecord(botAma: any, amaPrice: any): {
208
+ name: string;
209
+ erPeriod: number;
210
+ fastPeriod: number;
211
+ slowPeriod: number;
212
+ erSmoothPeriod: number;
213
+ value: number | null;
214
+ ok: boolean;
215
+ }[];
67
216
  declare function fetchNativeMarketHistorySince(assetA: any, assetB: any, sinceMs: any, untilMs: any, intervalSeconds: any, options?: {
68
217
  fillCandleGaps?: Function;
69
218
  }): Promise<any[]>;
@@ -114,5 +263,5 @@ declare function runOnceForAma(overrides?: any): Promise<{
114
263
  updatedAt: any;
115
264
  }>;
116
265
  declare function main(): Promise<0 | 1>;
117
- export { main, runOnceForAma, DEFAULT_AMA, DEFAULTS, calculateBotThreshold, calcAmaComparison, computeCandleStaleness, normalizeMarketSource, sleepUntilAlignedBoundary, resolveAmaForBot, resolveDeltaThresholdPercentFromGeneralSettings, resolveAmaSlopeDeltaThresholdPercentFromGeneralSettings, applyRuntimeDefaultsFromGeneralSettings, resolveBotCfg, usesAmaGridPrice, isBotWhitelisted, isBotDynamicWeightWhitelisted, isBotAsymmetricBoundsWhitelisted, _resetCycleCache, writeCenterSnapshot, writeBotDynamicGrid, writeGridResetTrigger, mergeGridResetMetadataFromDynamicGrid, normalizeNativeMarketHistoryCandles, fetchNativeMarketHistorySince, setBitsharesClientForTests as _setBitsharesClientForTests, loadMarketAdapterSettings, findPairForBot };
266
+ export { main, runOnceForAma, DEFAULT_AMA, DEFAULTS, calculateBotThreshold, buildAmaRecord, computeCandleStaleness, normalizeMarketSource, sleepUntilAlignedBoundary, computeStartupDelayMs, evaluateStartupSleep, resolveAmaForBot, resolveDeltaThresholdPercentFromGeneralSettings, resolveAmaSlopeDeltaThresholdPercentFromGeneralSettings, applyRuntimeDefaultsFromGeneralSettings, resolveBotCfg, usesAmaGridPrice, isBotWhitelisted, isBotDynamicWeightWhitelisted, isBotAsymmetricBoundsWhitelisted, _resetCycleCache, writeCenterSnapshot, writeBotDynamicGrid, writeGridResetTrigger, mergeGridResetMetadataFromDynamicGrid, normalizeNativeMarketHistoryCandles, fetchNativeMarketHistorySince, setBitsharesClientForTests as _setBitsharesClientForTests, loadMarketAdapterSettings, findPairForBot };
118
267
  //# sourceMappingURL=market_adapter.d.ts.map