dexbot 1.6.17 → 1.6.18

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (101) hide show
  1. package/CHANGELOG.md +32 -0
  2. package/analysis/README.md +10 -9
  3. package/analysis/ama_fitting/README.md +2 -2
  4. package/analysis/bot_fitting/README.md +3 -3
  5. package/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/analyze_args.d.ts +2 -1
  9. package/dist/analysis/fills_source.d.ts +1 -8
  10. package/dist/analysis/fills_source.js +1 -1
  11. package/dist/analysis/grid_correction_check.d.ts +9 -6
  12. package/dist/analysis/grid_correction_check.js +56 -64
  13. package/dist/analysis/math_utils.d.ts +1 -1
  14. package/dist/analysis/trade_profitability.d.ts +1 -1
  15. package/dist/analysis/tradingview/tradingview_uplot_chart_generator.js +3 -3
  16. package/dist/analysis/trend_detection/huber_scale_variants.d.ts +4 -3
  17. package/dist/market_adapter/cli_args.d.ts +6 -1
  18. package/dist/market_adapter/cli_args.js +16 -2
  19. package/dist/market_adapter/core/kibana_candles.d.ts +5 -1
  20. package/dist/market_adapter/core/kibana_candles.js +3 -1
  21. package/dist/market_adapter/core/strategies/regime_gate.d.ts +7 -1
  22. package/dist/market_adapter/core/strategies/regime_gate.js +3 -1
  23. package/dist/market_adapter/inputs/cex_candle_parsing.d.ts +7 -2
  24. package/dist/market_adapter/inputs/cex_candle_parsing.js +3 -1
  25. package/dist/market_adapter/inputs/fetch_book_data.d.ts +7 -1
  26. package/dist/market_adapter/inputs/fetch_book_data.js +3 -1
  27. package/dist/market_adapter/inputs/fetch_cex_synthetic_data.js +2 -11
  28. package/dist/market_adapter/inputs/fetch_lp_data.d.ts +26 -1
  29. package/dist/market_adapter/inputs/fetch_lp_data.js +62 -52
  30. package/dist/market_adapter/inputs/kibana_feed_source.d.ts +14 -2
  31. package/dist/market_adapter/inputs/kibana_feed_source.js +14 -1
  32. package/dist/market_adapter/inputs/window_cache.d.ts +14 -3
  33. package/dist/market_adapter/inputs/window_cache.js +14 -1
  34. package/dist/market_adapter/lp_chart_runner.d.ts +12 -9
  35. package/dist/market_adapter/lp_chart_runner.js +3 -1
  36. package/dist/market_adapter/lp_chart_strategy_loader.d.ts +5 -1
  37. package/dist/market_adapter/lp_chart_strategy_loader.js +3 -1
  38. package/dist/market_adapter/market_adapter.d.ts +10 -2
  39. package/dist/market_adapter/market_adapter.js +10 -11
  40. package/dist/market_adapter/utils/chain.d.ts +2 -3
  41. package/dist/market_adapter/utils/file_json_cache.d.ts +5 -1
  42. package/dist/market_adapter/utils/file_json_cache.js +3 -1
  43. package/dist/market_adapter/utils/file_lock.js +1 -1
  44. package/dist/market_adapter/utils/native_history.d.ts +7 -3
  45. package/dist/market_adapter/utils/native_history.js +3 -1
  46. package/dist/market_adapter/utils/pair_orientation.d.ts +2 -2
  47. package/dist/modules/bots_file_lock.d.ts +2 -2
  48. package/dist/modules/bots_file_lock.js +2 -2
  49. package/dist/modules/constants.js +6 -3
  50. package/dist/modules/dexbot_class.d.ts +8 -0
  51. package/dist/modules/dexbot_class.js +10 -0
  52. package/dist/modules/dexbot_cow_runtime.d.ts +62 -1
  53. package/dist/modules/dexbot_cow_runtime.js +461 -43
  54. package/dist/modules/dexbot_credential_client.d.ts +5 -0
  55. package/dist/modules/dexbot_maintenance_runtime.js +56 -9
  56. package/dist/modules/dexbot_startup_runtime.js +7 -1
  57. package/dist/modules/graceful_shutdown.d.ts +2 -2
  58. package/dist/modules/graceful_shutdown.js +2 -2
  59. package/dist/modules/launcher/runtime_mode.d.ts +4 -3
  60. package/dist/modules/node_manager.d.ts +1 -1
  61. package/dist/modules/node_manager.js +1 -1
  62. package/dist/modules/order/accounting.js +2 -1
  63. package/dist/modules/order/export.d.ts +2 -2
  64. package/dist/modules/order/export.js +2 -2
  65. package/dist/modules/order/grid.d.ts +19 -14
  66. package/dist/modules/order/grid.js +262 -61
  67. package/dist/modules/order/grid_reconcile.js +5 -1
  68. package/dist/modules/order/grid_reconcile_internal.js +2 -1
  69. package/dist/modules/order/index.d.ts +9 -3
  70. package/dist/modules/order/manager.d.ts +10 -0
  71. package/dist/modules/order/manager.js +41 -11
  72. package/dist/modules/order/strategy.js +22 -2
  73. package/dist/modules/order/sync_engine.d.ts +12 -1
  74. package/dist/modules/order/sync_engine.js +135 -20
  75. package/dist/modules/order/utils/math.d.ts +8 -9
  76. package/dist/modules/order/utils/math.js +24 -13
  77. package/dist/modules/order/utils/order.d.ts +52 -11
  78. package/dist/modules/order/utils/order.js +137 -21
  79. package/dist/modules/order/utils/system.d.ts +73 -29
  80. package/dist/modules/order/utils/system.js +239 -48
  81. package/dist/modules/order/utils/validate.d.ts +1 -0
  82. package/dist/modules/order/utils/validate.js +4 -1
  83. package/dist/modules/storage/index.d.ts +3 -2
  84. package/dist/modules/storage/index.js +3 -2
  85. package/dist/modules/types.d.ts +9 -0
  86. package/docs/COPY_ON_WRITE_MASTER_PLAN.md +1 -1
  87. package/docs/COW_INVARIANTS.md +20 -10
  88. package/docs/DEXBOT_COMPARISON.md +5 -5
  89. package/docs/EVOLUTION.md +9 -8
  90. package/docs/FUND_MOVEMENT_AND_ACCOUNTING.md +11 -11
  91. package/docs/GRID_PRICE_INVARIANT.md +24 -4
  92. package/docs/GRID_RECONCILE.md +5 -5
  93. package/docs/LIFECYCLE.md +11 -11
  94. package/docs/LOGGING.md +15 -2
  95. package/docs/ORDER_ENGINE_POST_1.0_RETROSPECTIVE.md +123 -36
  96. package/docs/README.md +1 -1
  97. package/docs/architecture.md +115 -13
  98. package/docs/developer_guide.md +12 -0
  99. package/market_adapter/README.md +9 -4
  100. package/modules/README.md +18 -14
  101. package/package.json +4 -3
@@ -3480,7 +3480,7 @@ function generateHTML(data, title = 'TradingView Style Research') {
3480
3480
  document.getElementById('ama-init-offset').disabled = !currentAmaInitOffsetEnabled;
3481
3481
  document.getElementById('ama-init-offset-val').textContent = currentAmaInitOffset + '%';
3482
3482
  currentVwapEnabled = document.getElementById('vwap-toggle').checked;
3483
- currentVwapBars = clamp(Math.round(Number(document.getElementById('vwap-bars').value) || 500), 24, 2000);
3483
+ currentVwapBars = clamp(Math.round(Number(document.getElementById('vwap-bars').value) || 500), 10, 2000);
3484
3484
  currentRangeEnabled = document.getElementById('range-toggle').checked;
3485
3485
  currentRangeScaleEnabled = document.getElementById('range-scale-toggle').checked;
3486
3486
  currentRangeSpan = Math.min(${RANGE_SPAN_MAX}, Math.max(${RANGE_SPAN_MIN}, Math.round((Number(document.getElementById('range-span').value) || ${RANGE_SPAN_DEFAULT}) * 20) / 20));
@@ -3609,8 +3609,8 @@ function generateHTML(data, title = 'TradingView Style Research') {
3609
3609
  addHold(dec, -1);
3610
3610
  addHold(inc, 1);
3611
3611
  }
3612
- makeStepper('sma-period', 1, 1, 0);
3613
- makeStepper('vwap-bars', 1, 24, 0);
3612
+ makeStepper('sma-period', 10, 10, 0);
3613
+ makeStepper('vwap-bars', 10, 10, 0);
3614
3614
  makeStepper('ama-er', 10, 1, 0);
3615
3615
  makeStepper('ama-fast', 0.1, 0.1, 1);
3616
3616
  makeStepper('ama-slow', 1, 0.1, 1);
@@ -1,18 +1,18 @@
1
1
  export type HuberScaleMode = 'none' | 'df' | 'mscale';
2
2
  /** One-bar diagnostic snapshot returned alongside the slope. */
3
- export interface HuberDiagnostics {
3
+ interface HuberDiagnostics {
4
4
  slopePct: number;
5
5
  scale: number;
6
6
  outlierFraction: number;
7
7
  }
8
8
  /** Accumulated stats attached to an estimator built by {@link createHuberEstimator}. */
9
- export interface HuberEstimatorStats {
9
+ interface HuberEstimatorStats {
10
10
  calls: number;
11
11
  outlierFractionSum: number;
12
12
  scaleSum: number;
13
13
  }
14
14
  /** Estimator function shape accepted by simulateGridResetSeries (cfg.slopeEstimator). */
15
- export interface HuberConsts {
15
+ interface HuberConsts {
16
16
  C?: number;
17
17
  ITERATIONS?: number;
18
18
  SCALE_FLOOR?: number;
@@ -37,4 +37,5 @@ export declare function huberSlopeCore(amaValues: unknown, index: number, lookba
37
37
  * accumulating the mean outlier fraction and scale across calls in `.stats`.
38
38
  */
39
39
  export declare function createHuberEstimator(mode?: HuberScaleMode, hub?: HuberConsts): HuberEstimator;
40
+ export {};
40
41
  //# sourceMappingURL=huber_scale_variants.d.ts.map
@@ -7,10 +7,14 @@
7
7
  * register handlers instead of re-listing the same switch cases; the walker
8
8
  * owns value consumption, `--help`/`-h`, and the unknown-flag error.
9
9
  *
10
+ * Values are the next argv token, or the text after `=` in a `--flag=value`
11
+ * token. The `=` form exists because a bare value that itself starts with `--`
12
+ * is rejected as a missing value (`--out --weird` fails, `--out=--weird` works).
13
+ *
10
14
  * Deliberately free of Node globals: callers pass in their own argv and own
11
15
  * the `process.exit` policy via `onHelp`, so this module stays browser-safe.
12
16
  */
13
- export interface CliArgHandlers {
17
+ interface CliArgHandlers {
14
18
  /** Flags that take a value; receives the raw next argv token (never missing or flag-shaped). */
15
19
  value?: Record<string, (raw: string) => void>;
16
20
  /** Flags that take no value. */
@@ -19,4 +23,5 @@ export interface CliArgHandlers {
19
23
  onHelp: () => void;
20
24
  }
21
25
  export declare function walkCliArgs(args: readonly string[], handlers: CliArgHandlers): void;
26
+ export {};
22
27
  //# sourceMappingURL=cli_args.d.ts.map
@@ -1,16 +1,27 @@
1
1
  'use strict';
2
2
  export function walkCliArgs(args, handlers) {
3
3
  for (let i = 0; i < args.length; i++) {
4
- const a = args[i];
4
+ const rawArg = args[i];
5
+ // `--flag=value` keeps a value that itself starts with `--` addressable.
6
+ const eq = rawArg.startsWith('--') ? rawArg.indexOf('=') : -1;
7
+ const inlineValue = eq > 2 ? rawArg.slice(eq + 1) : undefined;
8
+ const a = eq > 2 ? rawArg.slice(0, eq) : rawArg;
5
9
  if (a === '--gridResetFactor') {
6
10
  throw new Error('--gridResetFactor is no longer supported; use --deltaPercent <percent>');
7
11
  }
8
12
  if (a === '--help' || a === '-h') {
13
+ if (inlineValue !== undefined) {
14
+ throw new Error(`Flag ${a} does not take a value`);
15
+ }
9
16
  handlers.onHelp();
10
17
  continue;
11
18
  }
12
19
  const valueHandler = handlers.value?.[a];
13
20
  if (valueHandler) {
21
+ if (inlineValue !== undefined) {
22
+ valueHandler(inlineValue);
23
+ continue;
24
+ }
14
25
  const raw = args[i + 1];
15
26
  if (raw === undefined || raw.startsWith('--')) {
16
27
  throw new Error(`Flag ${a} expects a value; got ${raw === undefined ? 'nothing' : raw}`);
@@ -21,10 +32,13 @@ export function walkCliArgs(args, handlers) {
21
32
  }
22
33
  const flagHandler = handlers.flag?.[a];
23
34
  if (flagHandler) {
35
+ if (inlineValue !== undefined) {
36
+ throw new Error(`Flag ${a} does not take a value`);
37
+ }
24
38
  flagHandler();
25
39
  continue;
26
40
  }
27
- throw new Error(`Unknown argument: ${a}`);
41
+ throw new Error(`Unknown argument: ${rawArg}`);
28
42
  }
29
43
  }
30
44
  //# sourceMappingURL=cli_args.js.map
@@ -81,5 +81,9 @@ declare function resolveRequestedFillRange(cfg: KibanaCandleConfig, nowMs?: numb
81
81
  */
82
82
  declare function fetchKibanaCandles({ opType, fieldMap, assetA, assetB, config, poolId }: KibanaCandlesParams): Promise<number[][]>;
83
83
  declare function fetchKibanaClosePrices(params: KibanaCandlesParams): Promise<number[]>;
84
- export { buildDirectionalDocumentQuery, resolveRequestedFillRange, fetchKibanaCandles, fetchKibanaClosePrices, sourceFieldsForFieldMap, hitSortKey, hitSequence };
84
+ export { buildDirectionalDocumentQuery, resolveRequestedFillRange, fetchKibanaCandles, fetchKibanaClosePrices, hitSortKey, hitSequence };
85
+ /** Internal seams exercised directly by tests. */
86
+ export declare const __test: {
87
+ sourceFieldsForFieldMap: typeof sourceFieldsForFieldMap;
88
+ };
85
89
  //# sourceMappingURL=kibana_candles.d.ts.map
@@ -418,5 +418,7 @@ async function fetchKibanaClosePrices(params) {
418
418
  const candles = await fetchKibanaCandles(params);
419
419
  return candles.map((candle) => candle[4]);
420
420
  }
421
- export { buildDirectionalDocumentQuery, resolveRequestedFillRange, fetchKibanaCandles, fetchKibanaClosePrices, sourceFieldsForFieldMap, hitSortKey, hitSequence };
421
+ export { buildDirectionalDocumentQuery, resolveRequestedFillRange, fetchKibanaCandles, fetchKibanaClosePrices, hitSortKey, hitSequence };
422
+ /** Internal seams exercised directly by tests. */
423
+ export const __test = { sourceFieldsForFieldMap };
422
424
  //# sourceMappingURL=kibana_candles.js.map
@@ -105,5 +105,11 @@ export interface RegimeMultiplierResult {
105
105
  series: number[];
106
106
  }
107
107
  declare function computeRegimeMultiplier(closes: unknown, opts?: RegimeOpts): RegimeMultiplierResult;
108
- export { computeRegimeMultiplier, _resetRegimeCache, _locateResume, _analyzerBufferSize };
108
+ export { computeRegimeMultiplier };
109
+ /** Internal seams exercised directly by tests. */
110
+ export declare const __test: {
111
+ _resetRegimeCache: typeof _resetRegimeCache;
112
+ _locateResume: typeof _locateResume;
113
+ _analyzerBufferSize: typeof _analyzerBufferSize;
114
+ };
109
115
  //# sourceMappingURL=regime_gate.d.ts.map
@@ -294,5 +294,7 @@ function computeRegimeMultiplier(closes, opts = {}) {
294
294
  series: series.map((value) => roundTo(value, 1000)),
295
295
  };
296
296
  }
297
- export { computeRegimeMultiplier, _resetRegimeCache, _locateResume, _analyzerBufferSize };
297
+ export { computeRegimeMultiplier };
298
+ /** Internal seams exercised directly by tests. */
299
+ export const __test = { _resetRegimeCache, _locateResume, _analyzerBufferSize };
298
300
  //# sourceMappingURL=regime_gate.js.map
@@ -7,7 +7,7 @@
7
7
  * a one-liner and guarantees identical handling across exchanges.
8
8
  */
9
9
  export type CandleRow = [number, number, number, number, number, number];
10
- export interface OhlcIndexes {
10
+ interface OhlcIndexes {
11
11
  minLength: number;
12
12
  ts: number;
13
13
  open: number;
@@ -21,9 +21,14 @@ export declare const OHLC_CLOSE_HIGH_LOW: OhlcIndexes;
21
21
  export declare const OHLC_GATE: OhlcIndexes;
22
22
  export declare const OHLC_KRAKEN: OhlcIndexes;
23
23
  /** Normalize a seconds- or milliseconds-epoch timestamp to milliseconds. */
24
- export declare function normalizeTimestamp(raw: unknown): number;
24
+ declare function normalizeTimestamp(raw: unknown): number;
25
25
  export declare function parseCandleRow(row: unknown, idx: OhlcIndexes): CandleRow | null;
26
26
  export declare function parseCandleRows(rows: unknown[], idx: OhlcIndexes): CandleRow[];
27
27
  /** HTX can return objects instead of arrays; map those to the shared shape. */
28
28
  export declare function parseHtxObjectRow(row: unknown): CandleRow | null;
29
+ /** Internal seams exercised directly by tests. */
30
+ export declare const __test: {
31
+ normalizeTimestamp: typeof normalizeTimestamp;
32
+ };
33
+ export {};
29
34
  //# sourceMappingURL=cex_candle_parsing.d.ts.map
@@ -9,7 +9,7 @@ export const OHLC_GATE = { minLength: 7, ts: 0, open: 5, high: 3, low: 4, close:
9
9
  // Kraken OHLC: [tsSeconds, open, high, low, close, vwap, volume, count].
10
10
  export const OHLC_KRAKEN = { minLength: 7, ts: 0, open: 1, high: 2, low: 3, close: 4, volume: 6 };
11
11
  /** Normalize a seconds- or milliseconds-epoch timestamp to milliseconds. */
12
- export function normalizeTimestamp(raw) {
12
+ function normalizeTimestamp(raw) {
13
13
  const ts = Number(raw);
14
14
  if (!Number.isFinite(ts))
15
15
  return Number.NaN;
@@ -49,4 +49,6 @@ export function parseHtxObjectRow(row) {
49
49
  return null;
50
50
  return [ts, open, high, low, close, Number.isFinite(volume) ? volume : 0];
51
51
  }
52
+ /** Internal seams exercised directly by tests. */
53
+ export const __test = { normalizeTimestamp };
52
54
  //# sourceMappingURL=cex_candle_parsing.js.map
@@ -26,5 +26,11 @@ declare function isBookChunkMatch(metaInput: unknown, requestKeyInput: unknown):
26
26
  * @returns {Promise<Array>} [[timestamp_ms, open, high, low, close, volume_A], ...]
27
27
  */
28
28
  declare function fetchMarketCandlesSequentially(assetA: AssetRef, assetB: AssetRef, opts?: BookFetchOpts): Promise<number[][]>;
29
- export { bookCacheKey, bookOutputPath, isBookChunkMatch, fetchMarketCandlesSequentially, };
29
+ export { fetchMarketCandlesSequentially };
30
+ /** Internal seams exercised directly by tests. */
31
+ export declare const __test: {
32
+ bookCacheKey: typeof bookCacheKey;
33
+ bookOutputPath: typeof bookOutputPath;
34
+ isBookChunkMatch: typeof isBookChunkMatch;
35
+ };
30
36
  //# sourceMappingURL=fetch_book_data.d.ts.map
@@ -159,5 +159,7 @@ async function fetchMarketCandlesSequentially(assetA, assetB, opts = {}) {
159
159
  });
160
160
  return flipped ? invertCandleSeries(merged, { volume: 'scale' }) : merged;
161
161
  }
162
- export { bookCacheKey, bookOutputPath, isBookChunkMatch, fetchMarketCandlesSequentially, };
162
+ export { fetchMarketCandlesSequentially };
163
+ /** Internal seams exercised directly by tests. */
164
+ export const __test = { bookCacheKey, bookOutputPath, isBookChunkMatch };
163
165
  //# sourceMappingURL=fetch_book_data.js.map
@@ -613,17 +613,8 @@ function applyBotDerivedConfig(config) {
613
613
  if (!next.quoteProvided && botContext.bot.assetB) {
614
614
  next.quote = normalizeCexAssetSymbol(botContext.bot.assetB);
615
615
  }
616
- const baseCfg = MARKET_ADAPTER_DEFAULTS || {
617
- amaSlope: {
618
- lookbackBars: MARKET_ADAPTER.DYNAMIC_WEIGHT_AMA_LOOKBACK_BARS,
619
- },
620
- };
621
- const botCfg = typeof resolveBotCfg === 'function'
622
- ? resolveBotCfg(botContext.bot, baseCfg)
623
- : baseCfg;
624
- const botAma = typeof resolveAmaForBot === 'function'
625
- ? resolveAmaForBot(botContext.bot, null, botCfg)
626
- : null;
616
+ const botCfg = resolveBotCfg(botContext.bot, MARKET_ADAPTER_DEFAULTS);
617
+ const botAma = resolveAmaForBot(botContext.bot, null, botCfg);
627
618
  return { config: next, botContext, botCfg, botAma };
628
619
  }
629
620
  function printHelp() {
@@ -33,6 +33,23 @@ interface BotConfig {
33
33
  assetB?: string;
34
34
  [key: string]: unknown;
35
35
  }
36
+ declare function parseArgs(): {
37
+ poolId: null;
38
+ botName: null;
39
+ precA: null;
40
+ precB: null;
41
+ config: {
42
+ intervalSeconds: number;
43
+ lookbackHours: number;
44
+ apiKey: string | null;
45
+ chunkMonths: number;
46
+ timeRange?: {
47
+ gte?: string;
48
+ lte?: string;
49
+ };
50
+ outPath?: string;
51
+ };
52
+ };
36
53
  declare function outputPath(poolId: unknown, intervalSeconds: number, assetA: AssetRef, assetB: AssetRef): string;
37
54
  declare function applyPrecisionOverrides(assetA: AssetRef, assetB: AssetRef, precA: number | null, precB: number | null): {
38
55
  assetA: AssetRef;
@@ -57,5 +74,13 @@ declare function parseBotsConfig(raw: string, sourceLabel?: string): BotConfig[]
57
74
  * Pick a bot: by name if given, otherwise first active bot with startPrice: "pool".
58
75
  */
59
76
  declare function selectBot(bots: BotConfig[], botName: string | null | undefined): BotConfig;
60
- export { applyPrecisionOverrides, parseBotsConfig, selectBot, fetchCandlesSequentially, outputPath, loadCachedFetchContext };
77
+ export { fetchCandlesSequentially, outputPath };
78
+ /** Internal seams exercised directly by tests. */
79
+ export declare const __test: {
80
+ applyPrecisionOverrides: typeof applyPrecisionOverrides;
81
+ parseBotsConfig: typeof parseBotsConfig;
82
+ selectBot: typeof selectBot;
83
+ loadCachedFetchContext: typeof loadCachedFetchContext;
84
+ parseArgs: typeof parseArgs;
85
+ };
61
86
  //# sourceMappingURL=fetch_lp_data.d.ts.map
@@ -41,6 +41,7 @@ import { shardStemFromName } from '../utils/month_shards.js';
41
41
  import * as bitsharesClient from '../../modules/bitshares_client.js';
42
42
  import { getErrorMessage, resolveSeamMs } from '../../modules/utils/errors.js';
43
43
  import { isSameBotName } from '../../modules/utils/sanitize_key.js';
44
+ import { walkCliArgs } from '../cli_args.js';
44
45
  import { pathToFileURL } from 'node:url';
45
46
  const storage = getStorage();
46
47
  const { readJSON } = storage;
@@ -56,8 +57,44 @@ const FETCH_MAX_ATTEMPTS = MARKET_ADAPTER.RUNTIME_DEFAULTS.sourceRetries;
56
57
  const FETCH_RETRY_BACKOFF_BASE_MS = MARKET_ADAPTER.LP_FETCH_RETRY_BACKOFF_BASE_MS;
57
58
  const BOTS_JSON = PATHS.PROFILES.BOTS_JSON;
58
59
  // ─── CLI ──────────────────────────────────────────────────────────────────────
60
+ function printHelp() {
61
+ console.log(`Usage:
62
+ node dist/market_adapter/inputs/fetch_lp_data.js [options]
63
+
64
+ Options:
65
+ --bot <name> Read pool/assets/interval from profiles/bots.json
66
+ --pool <id> Liquidity pool id (1.19.N or N)
67
+ --interval <label> Candle interval (1m|5m|15m|30m|1h|2h|4h|6h|12h|1d|1w or seconds)
68
+ --lookback <hours> Trailing window in hours (accepts a trailing \`h\`)
69
+ --start <date> Absolute ISO start time (pairs with --end)
70
+ --end <date> Absolute ISO end time (pairs with --start)
71
+ --chunkMonths <n> Fetch window size in months (default ${DEFAULT_CONFIG.chunkMonths})
72
+ --precA <n> Override asset A precision
73
+ --precB <n> Override asset B precision
74
+ --apiKey <key> Kibana API key, when the endpoint requires auth
75
+ --out <file> Explicit output path
76
+ --help, -h Show this help
77
+
78
+ Flags accept \`--flag value\` or \`--flag=value\`; use the second form when the
79
+ value itself starts with \`--\`.
80
+ `);
81
+ }
82
+ /** Parse an integer option, rejecting non-numeric or out-of-range input. */
83
+ function parseIntOption(flag, raw, min) {
84
+ const value = raw.trim() === '' ? Number.NaN : Number(raw);
85
+ if (!Number.isInteger(value) || value < min) {
86
+ throw new Error(`${flag}: invalid value "${raw}" (expected an integer >= ${min})`);
87
+ }
88
+ return value;
89
+ }
90
+ /** Reject an empty string option (a blank path or API key is never intended). */
91
+ function requireNonEmpty(flag, raw) {
92
+ if (raw.trim() === '') {
93
+ throw new Error(`${flag}: expected a non-empty value`);
94
+ }
95
+ return raw;
96
+ }
59
97
  function parseArgs() {
60
- const args = process.argv.slice(2);
61
98
  const config = { ...DEFAULT_CONFIG };
62
99
  let poolId = null; // null = auto-discover from bots.json
63
100
  let botName = null;
@@ -71,19 +108,15 @@ function parseArgs() {
71
108
  '1h': 3600, '2h': 7200, '4h': 14400, '6h': 21600, '12h': 43200,
72
109
  '1d': 86400, '1w': 604800, '7d': 604800,
73
110
  };
74
- for (let i = 0; i < args.length; i++) {
75
- const arg = args[i];
76
- const val = args[i + 1];
77
- switch (arg) {
78
- case '--bot':
79
- botName = val;
80
- i++;
81
- break;
82
- case '--pool':
83
- poolId = val;
84
- i++;
85
- break;
86
- case '--interval': {
111
+ walkCliArgs(process.argv.slice(2), {
112
+ onHelp: () => {
113
+ printHelp();
114
+ process.exit(0);
115
+ },
116
+ value: {
117
+ '--bot': (val) => { botName = val; },
118
+ '--pool': (val) => { poolId = val; },
119
+ '--interval': (val) => {
87
120
  let seconds = intervalMap[val];
88
121
  if (seconds == null)
89
122
  seconds = parseInt(val, 10);
@@ -91,48 +124,23 @@ function parseArgs() {
91
124
  throw new Error(`--interval: unsupported value "${val}" (use ${Object.keys(intervalMap).join(', ')} or seconds)`);
92
125
  }
93
126
  config.intervalSeconds = seconds;
94
- i++;
95
- break;
96
- }
97
- case '--lookback': {
127
+ },
128
+ '--lookback': (val) => {
98
129
  const hours = parseInt(String(val).replace('h', ''), 10);
99
130
  if (!Number.isFinite(hours) || hours <= 0) {
100
131
  throw new Error(`--lookback: invalid value "${val}" (expected hours, e.g. 48 or 48h)`);
101
132
  }
102
133
  config.lookbackHours = hours;
103
- i++;
104
- break;
105
- }
106
- case '--chunkMonths':
107
- config.chunkMonths = parseInt(val, 10);
108
- i++;
109
- break;
110
- case '--precA':
111
- precA = parseInt(val, 10);
112
- i++;
113
- break;
114
- case '--precB':
115
- precB = parseInt(val, 10);
116
- i++;
117
- break;
118
- case '--apiKey':
119
- config.apiKey = val;
120
- i++;
121
- break;
122
- case '--start':
123
- config.timeRange = { ...(config.timeRange || {}), gte: val };
124
- i++;
125
- break;
126
- case '--end':
127
- config.timeRange = { ...(config.timeRange || {}), lte: val };
128
- i++;
129
- break;
130
- case '--out':
131
- config.outPath = val;
132
- i++;
133
- break;
134
- }
135
- }
134
+ },
135
+ '--chunkMonths': (val) => { config.chunkMonths = parseIntOption('--chunkMonths', val, 1); },
136
+ '--precA': (val) => { precA = parseIntOption('--precA', val, 0); },
137
+ '--precB': (val) => { precB = parseIntOption('--precB', val, 0); },
138
+ '--apiKey': (val) => { config.apiKey = requireNonEmpty('--apiKey', val); },
139
+ '--start': (val) => { config.timeRange = { ...(config.timeRange || {}), gte: val }; },
140
+ '--end': (val) => { config.timeRange = { ...(config.timeRange || {}), lte: val }; },
141
+ '--out': (val) => { config.outPath = requireNonEmpty('--out', val); },
142
+ },
143
+ });
136
144
  return { poolId, botName, precA, precB, config };
137
145
  }
138
146
  // ─── Output path ──────────────────────────────────────────────────────────────
@@ -642,5 +650,7 @@ if (process.argv[1] && import.meta.url === pathToFileURL(process.argv[1]).href)
642
650
  process.exit(1);
643
651
  });
644
652
  }
645
- export { applyPrecisionOverrides, parseBotsConfig, selectBot, fetchCandlesSequentially, outputPath, loadCachedFetchContext };
653
+ export { fetchCandlesSequentially, outputPath };
654
+ /** Internal seams exercised directly by tests. */
655
+ export const __test = { applyPrecisionOverrides, parseBotsConfig, selectBot, loadCachedFetchContext, parseArgs };
646
656
  //# sourceMappingURL=fetch_lp_data.js.map
@@ -1,4 +1,3 @@
1
- declare const OP_TYPE_FEED = 19;
2
1
  interface AssetRef {
3
2
  id?: string;
4
3
  precision?: number;
@@ -135,5 +134,18 @@ declare function fetchFeedCandlesSequentially(feedCtx: FeedContext, assetA: Asse
135
134
  };
136
135
  outPath?: string;
137
136
  }): Promise<number[][]>;
138
- export { OP_TYPE_FEED, backingPerMpa, hitToFeedPrice, buildFeedDocumentQuery, crossPointsToRatios, bucketPricesToCandles, invertCandles, getFeedCandlesForMpa, getFeedCandlesForPair, getFeedCandlesForMpaCross, fetchFeedCandlesSequentially, };
137
+ export { fetchFeedCandlesSequentially };
138
+ /** Internal seams exercised directly by tests. */
139
+ export declare const __test: {
140
+ OP_TYPE_FEED: number;
141
+ backingPerMpa: typeof backingPerMpa;
142
+ hitToFeedPrice: typeof hitToFeedPrice;
143
+ buildFeedDocumentQuery: typeof buildFeedDocumentQuery;
144
+ crossPointsToRatios: typeof crossPointsToRatios;
145
+ bucketPricesToCandles: typeof bucketPricesToCandles;
146
+ invertCandles: typeof invertCandles;
147
+ getFeedCandlesForMpa: typeof getFeedCandlesForMpa;
148
+ getFeedCandlesForPair: typeof getFeedCandlesForPair;
149
+ getFeedCandlesForMpaCross: typeof getFeedCandlesForMpaCross;
150
+ };
139
151
  //# sourceMappingURL=kibana_feed_source.d.ts.map
@@ -584,5 +584,18 @@ async function fetchFeedCandlesSequentially(feedCtx, assetA, assetB, opts = {})
584
584
  });
585
585
  return flipped ? invertCandles(merged) : merged;
586
586
  }
587
- export { OP_TYPE_FEED, backingPerMpa, hitToFeedPrice, buildFeedDocumentQuery, crossPointsToRatios, bucketPricesToCandles, invertCandles, getFeedCandlesForMpa, getFeedCandlesForPair, getFeedCandlesForMpaCross, fetchFeedCandlesSequentially, };
587
+ export { fetchFeedCandlesSequentially };
588
+ /** Internal seams exercised directly by tests. */
589
+ export const __test = {
590
+ OP_TYPE_FEED,
591
+ backingPerMpa,
592
+ hitToFeedPrice,
593
+ buildFeedDocumentQuery,
594
+ crossPointsToRatios,
595
+ bucketPricesToCandles,
596
+ invertCandles,
597
+ getFeedCandlesForMpa,
598
+ getFeedCandlesForPair,
599
+ getFeedCandlesForMpaCross,
600
+ };
588
601
  //# sourceMappingURL=kibana_feed_source.js.map
@@ -87,9 +87,7 @@ interface RunCachedWindowsOptions {
87
87
  lte: string;
88
88
  }) => void;
89
89
  }
90
- declare const TAIL_REFRESH_HOURS = 48;
91
90
  declare const TAIL_SETTLE_LAG_MS: number;
92
- declare const GAP_SETTLE_HORIZON_MS: number;
93
91
  declare const MAX_COVERAGE_SPANS = 64;
94
92
  declare function readCacheChunk(chunkFile: string, requestKey: unknown, isMatch: (meta: unknown, requestKey: unknown) => boolean): CacheChunk | null;
95
93
  declare function loadBucketCache(outPath: string, requestKey: unknown, isMatch: (meta: unknown, requestKey: unknown) => boolean, range?: {
@@ -174,6 +172,19 @@ declare function formatWindowLine(unit: string, index: number, total: number, gt
174
172
  * touch nothing on disk.
175
173
  */
176
174
  declare function runCachedWindows(opts: RunCachedWindowsOptions): Promise<Candle[]>;
177
- export { TAIL_REFRESH_HOURS, TAIL_SETTLE_LAG_MS, GAP_SETTLE_HORIZON_MS, MAX_COVERAGE_SPANS, shardKeyForTimestamp, shardBoundsForKey, shardKeysForRange, shardPathFor, readCacheChunk, loadBucketCache, unionQueriedRanges, compactCoverage, rangesCoveredBy, coverageSatisfied, verifiedAt, timestampMs, allQueriedRanges, settleCoverage, buildFetchWindowsFromRange, findMissingBucketRanges, mergeGapRanges, pruneImmutableGaps, persistCacheChunk, planWindowReuse, formatWindowLine, runCachedWindows, };
175
+ export { TAIL_SETTLE_LAG_MS, MAX_COVERAGE_SPANS, shardKeyForTimestamp, shardBoundsForKey, shardKeysForRange, shardPathFor, unionQueriedRanges, compactCoverage, rangesCoveredBy, coverageSatisfied, verifiedAt, timestampMs, allQueriedRanges, buildFetchWindowsFromRange, formatWindowLine, runCachedWindows, };
176
+ /** Internal seams exercised directly by tests. */
177
+ export declare const __test: {
178
+ TAIL_REFRESH_HOURS: number;
179
+ GAP_SETTLE_HORIZON_MS: number;
180
+ readCacheChunk: typeof readCacheChunk;
181
+ loadBucketCache: typeof loadBucketCache;
182
+ settleCoverage: typeof settleCoverage;
183
+ findMissingBucketRanges: typeof findMissingBucketRanges;
184
+ mergeGapRanges: typeof mergeGapRanges;
185
+ pruneImmutableGaps: typeof pruneImmutableGaps;
186
+ persistCacheChunk: typeof persistCacheChunk;
187
+ planWindowReuse: typeof planWindowReuse;
188
+ };
178
189
  export type { QueriedRange } from '../utils/month_shards.js';
179
190
  //# sourceMappingURL=window_cache.d.ts.map
@@ -822,5 +822,18 @@ async function runCachedWindows(opts) {
822
822
  }
823
823
  return merged;
824
824
  }
825
- export { TAIL_REFRESH_HOURS, TAIL_SETTLE_LAG_MS, GAP_SETTLE_HORIZON_MS, MAX_COVERAGE_SPANS, shardKeyForTimestamp, shardBoundsForKey, shardKeysForRange, shardPathFor, readCacheChunk, loadBucketCache, unionQueriedRanges, compactCoverage, rangesCoveredBy, coverageSatisfied, verifiedAt, timestampMs, allQueriedRanges, settleCoverage, buildFetchWindowsFromRange, findMissingBucketRanges, mergeGapRanges, pruneImmutableGaps, persistCacheChunk, planWindowReuse, formatWindowLine, runCachedWindows, };
825
+ export { TAIL_SETTLE_LAG_MS, MAX_COVERAGE_SPANS, shardKeyForTimestamp, shardBoundsForKey, shardKeysForRange, shardPathFor, unionQueriedRanges, compactCoverage, rangesCoveredBy, coverageSatisfied, verifiedAt, timestampMs, allQueriedRanges, buildFetchWindowsFromRange, formatWindowLine, runCachedWindows, };
826
+ /** Internal seams exercised directly by tests. */
827
+ export const __test = {
828
+ TAIL_REFRESH_HOURS,
829
+ GAP_SETTLE_HORIZON_MS,
830
+ readCacheChunk,
831
+ loadBucketCache,
832
+ settleCoverage,
833
+ findMissingBucketRanges,
834
+ mergeGapRanges,
835
+ pruneImmutableGaps,
836
+ persistCacheChunk,
837
+ planWindowReuse,
838
+ };
826
839
  //# sourceMappingURL=window_cache.js.map
@@ -1,12 +1,4 @@
1
1
  import { findLatestLpData } from './utils/data_discovery.js';
2
- declare const DEFAULT_COMPARISON_STRATEGIES: {
3
- name: string;
4
- erPeriod: number;
5
- fastPeriod: number;
6
- slowPeriod: number;
7
- color: string;
8
- dash: string;
9
- }[];
10
2
  type NormalizedLpCandle = [number, number, number, number, number, number];
11
3
  interface LpCandleObject {
12
4
  timestamp: number;
@@ -117,5 +109,16 @@ declare function generateLpChartBundle(options?: BundleChartOptions): {
117
109
  marketChart: ReturnType<typeof generateMarketLpChart>;
118
110
  comparisonChart: ReturnType<typeof generateComparisonLpChart>;
119
111
  };
120
- export { DEFAULT_COMPARISON_STRATEGIES, calculateMetrics, defaultMarketChartPath, findLatestLpData, generateComparisonLpChart, generateLpChartBundle, generateMarketLpChart, loadLpDataFile, parseLpChartCliArgs };
112
+ export { calculateMetrics, defaultMarketChartPath, findLatestLpData, generateComparisonLpChart, generateLpChartBundle, generateMarketLpChart, loadLpDataFile, parseLpChartCliArgs };
113
+ /** Internal seams exercised directly by tests. */
114
+ export declare const __test: {
115
+ DEFAULT_COMPARISON_STRATEGIES: {
116
+ name: string;
117
+ erPeriod: number;
118
+ fastPeriod: number;
119
+ slowPeriod: number;
120
+ color: string;
121
+ dash: string;
122
+ }[];
123
+ };
121
124
  //# sourceMappingURL=lp_chart_runner.d.ts.map
@@ -323,5 +323,7 @@ function generateLpChartBundle(options = {}) {
323
323
  comparisonChart,
324
324
  };
325
325
  }
326
- export { DEFAULT_COMPARISON_STRATEGIES, calculateMetrics, defaultMarketChartPath, findLatestLpData, generateComparisonLpChart, generateLpChartBundle, generateMarketLpChart, loadLpDataFile, parseLpChartCliArgs };
326
+ export { calculateMetrics, defaultMarketChartPath, findLatestLpData, generateComparisonLpChart, generateLpChartBundle, generateMarketLpChart, loadLpDataFile, parseLpChartCliArgs };
327
+ /** Internal seams exercised directly by tests. */
328
+ export const __test = { DEFAULT_COMPARISON_STRATEGIES };
327
329
  //# sourceMappingURL=lp_chart_runner.js.map
@@ -40,5 +40,9 @@ declare function loadStrategiesForLpChart({ dataFile, meta, profilesFile, extraS
40
40
  profilesFile?: string | null;
41
41
  extraSearchDirs?: string[];
42
42
  }): AmaStrategy[] | null;
43
- export { loadStrategiesForLpChart, loadStrategiesFromProfiles };
43
+ export { loadStrategiesForLpChart };
44
+ /** Internal seams exercised directly by tests. */
45
+ export declare const __test: {
46
+ loadStrategiesFromProfiles: typeof loadStrategiesFromProfiles;
47
+ };
44
48
  //# sourceMappingURL=lp_chart_strategy_loader.d.ts.map
@@ -163,5 +163,7 @@ function loadStrategiesForLpChart({ dataFile, meta, profilesFile, extraSearchDir
163
163
  }
164
164
  return loadStrategiesFromProfiles(profilesFile, meta);
165
165
  }
166
- export { loadStrategiesForLpChart, loadStrategiesFromProfiles };
166
+ export { loadStrategiesForLpChart };
167
+ /** Internal seams exercised directly by tests. */
168
+ export const __test = { loadStrategiesFromProfiles };
167
169
  //# sourceMappingURL=lp_chart_strategy_loader.js.map
@@ -271,7 +271,7 @@ declare function buildAmaRecord(botAma: unknown, amaPrice: number): {
271
271
  }[];
272
272
  declare function fetchNativeMarketHistorySince(assetA: unknown, assetB: unknown, sinceMs: number, untilMs: number, intervalSeconds: number, options?: {
273
273
  fillCandleGaps?: (...args: unknown[]) => unknown;
274
- }): Promise<import("./utils/native_history.js").NativeHistoryCandle[]>;
274
+ }): Promise<[number, number, number, number, number, number][]>;
275
275
  declare function writeGridResetTrigger(bot: Record<string, unknown>, payload: Record<string, unknown>): string;
276
276
  /**
277
277
  * Atomically write the dynamic grid snapshot for a bot to profiles/orders/<botKey>.dynamicgrid.json.
@@ -324,5 +324,13 @@ declare function runOnceForAma(overrides?: object): Promise<{
324
324
  updatedAt: string;
325
325
  }>;
326
326
  declare function main(): Promise<0 | 1>;
327
- 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 };
327
+ export { main, runOnceForAma, DEFAULT_AMA, DEFAULTS, calculateBotThreshold, buildAmaRecord, computeCandleStaleness, normalizeMarketSource, sleepUntilAlignedBoundary, computeStartupDelayMs, evaluateStartupSleep, resolveAmaForBot, applyRuntimeDefaultsFromGeneralSettings, resolveBotCfg, usesAmaGridPrice, isBotWhitelisted, isBotDynamicWeightWhitelisted, isBotAsymmetricBoundsWhitelisted, writeCenterSnapshot, writeBotDynamicGrid, writeGridResetTrigger, normalizeNativeMarketHistoryCandles, fetchNativeMarketHistorySince, loadMarketAdapterSettings, findPairForBot };
328
+ /** Internal seams exercised directly by tests. */
329
+ export declare const __test: {
330
+ resolveDeltaThresholdPercentFromGeneralSettings: typeof resolveDeltaThresholdPercentFromGeneralSettings;
331
+ resolveAmaSlopeDeltaThresholdPercentFromGeneralSettings: typeof resolveAmaSlopeDeltaThresholdPercentFromGeneralSettings;
332
+ _resetCycleCache: typeof _resetCycleCache;
333
+ mergeGridResetMetadataFromDynamicGrid: typeof mergeGridResetMetadataFromDynamicGrid;
334
+ _setBitsharesClientForTests: typeof setBitsharesClientForTests;
335
+ };
328
336
  //# sourceMappingURL=market_adapter.d.ts.map