dexbot 1.6.12 → 1.6.14

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 (213) hide show
  1. package/CHANGELOG.md +65 -1
  2. package/README.md +2 -2
  3. package/analysis/README.md +9 -11
  4. package/analysis/ama_fitting/README.md +5 -3
  5. package/claw/README.md +1 -0
  6. package/claw/docs/AI_BOT_LIBRARY_API.md +3 -1
  7. package/claw/docs/DEXBOT2_TUNING_CHEAT_SHEET.md +4 -4
  8. package/claw/modules/claw_bridge.ts +0 -3
  9. package/claw/modules/claw_catalog.ts +8 -4
  10. package/claw/modules/claw_skill_md.ts +1 -0
  11. package/claw/modules/dexbot_profiles.ts +59 -15
  12. package/claw/modules/types.ts +2 -1
  13. package/claw/package.json +3 -3
  14. package/claw/runtimes/openclaw-plugin/openclaw.plugin.json +1 -1
  15. package/claw/runtimes/openclaw-plugin/package.json +1 -1
  16. package/claw/skills/margin-trading/SKILL.md +1 -1
  17. package/claw/skills/margin-trading/references/position-management.md +1 -1
  18. package/claw/tsconfig.json +2 -2
  19. package/dist/analysis/ama_fitting/analyze_lambda_vs_slow.js +1 -14
  20. package/dist/analysis/ama_fitting/fetch_lp_candles.js +51 -41
  21. package/dist/analysis/ama_fitting/generate_unified_comparison_chart.d.ts +1 -24
  22. package/dist/analysis/ama_fitting/generate_unified_comparison_chart.js +36 -18
  23. package/dist/analysis/ama_fitting/optimizer_high_resolution.js +18 -66
  24. package/dist/analysis/analyze_args.d.ts +12 -0
  25. package/dist/analysis/analyze_args.js +20 -0
  26. package/dist/analysis/bot_fitting/backtest_ama_sweep.d.ts +1 -16
  27. package/dist/analysis/bot_fitting/backtest_ama_sweep.js +20 -101
  28. package/dist/analysis/bot_fitting/backtest_bot_fitting.js +26 -92
  29. package/dist/analysis/bot_fitting/backtest_lookback_drawdown.js +19 -34
  30. package/dist/analysis/bot_fitting/shared_utils.d.ts +71 -3
  31. package/dist/analysis/bot_fitting/shared_utils.js +124 -8
  32. package/dist/analysis/chart_ui.d.ts +30 -1
  33. package/dist/analysis/chart_ui.js +37 -1
  34. package/dist/analysis/fills_cache.d.ts +3 -23
  35. package/dist/analysis/fills_cache.js +3 -84
  36. package/dist/analysis/fills_source.d.ts +31 -1
  37. package/dist/analysis/fills_source.js +69 -1
  38. package/dist/analysis/grid_correction_check.d.ts +1 -23
  39. package/dist/analysis/grid_correction_check.js +15 -58
  40. package/dist/analysis/math_utils.d.ts +85 -1
  41. package/dist/analysis/math_utils.js +116 -1
  42. package/dist/analysis/price_sources.d.ts +22 -1
  43. package/dist/analysis/price_sources.js +23 -0
  44. package/dist/analysis/resolve_source.js +31 -10
  45. package/dist/analysis/trade_profitability.d.ts +6 -0
  46. package/dist/analysis/trade_profitability.js +23 -97
  47. package/dist/analysis/tradingview/analyze_tradingview.d.ts +1 -17
  48. package/dist/analysis/tradingview/analyze_tradingview.js +1 -1
  49. package/dist/analysis/tradingview/tradingview_uplot_chart_generator.js +27 -40
  50. package/dist/analysis/trend_detection/backtest_ama_slope_huber.d.ts +1 -101
  51. package/dist/analysis/trend_detection/backtest_ama_slope_huber.js +22 -80
  52. package/dist/analysis/trend_detection/dynamic_weight_chart_generator.js +11 -37
  53. package/dist/analysis/trend_detection/volatility_chart_generator.js +9 -10
  54. package/dist/analysis/worker_pool.d.ts +38 -0
  55. package/dist/analysis/worker_pool.js +67 -0
  56. package/dist/dexbot.js +67 -48
  57. package/dist/market_adapter/ama_signal_runner.js +21 -54
  58. package/dist/market_adapter/candle_utils.d.ts +7 -1
  59. package/dist/market_adapter/candle_utils.js +11 -1
  60. package/dist/market_adapter/cli_args.d.ts +22 -0
  61. package/dist/market_adapter/cli_args.js +30 -0
  62. package/dist/market_adapter/core/config_normalizers.js +11 -6
  63. package/dist/market_adapter/core/kibana_candles.d.ts +3 -1
  64. package/dist/market_adapter/core/kibana_candles.js +3 -2
  65. package/dist/market_adapter/core/market_adapter_service.d.ts +85 -85
  66. package/dist/market_adapter/core/market_adapter_service.js +93 -158
  67. package/dist/market_adapter/core/signals/hurst_analyzer.d.ts +1 -6
  68. package/dist/market_adapter/core/signals/hurst_analyzer.js +1 -1
  69. package/dist/market_adapter/core/signals/permutation_entropy_analyzer.d.ts +1 -11
  70. package/dist/market_adapter/core/signals/permutation_entropy_analyzer.js +1 -1
  71. package/dist/market_adapter/inputs/fetch_book_data.js +0 -1
  72. package/dist/market_adapter/inputs/fetch_cex_synthetic_data.js +63 -107
  73. package/dist/market_adapter/inputs/fetch_lp_data.d.ts +8 -1
  74. package/dist/market_adapter/inputs/fetch_lp_data.js +25 -7
  75. package/dist/market_adapter/inputs/kibana_feed_source.js +4 -26
  76. package/dist/market_adapter/inputs/window_cache.d.ts +4 -72
  77. package/dist/market_adapter/inputs/window_cache.js +52 -177
  78. package/dist/market_adapter/interval_utils.d.ts +11 -1
  79. package/dist/market_adapter/interval_utils.js +16 -1
  80. package/dist/market_adapter/lp_chart_runner.d.ts +3 -0
  81. package/dist/market_adapter/lp_chart_runner.js +37 -19
  82. package/dist/market_adapter/market_adapter.js +27 -72
  83. package/dist/market_adapter/utils/data_discovery.d.ts +45 -1
  84. package/dist/market_adapter/utils/data_discovery.js +220 -27
  85. package/dist/market_adapter/utils/month_shards.d.ts +84 -0
  86. package/dist/market_adapter/utils/month_shards.js +237 -0
  87. package/dist/modules/account_bots.d.ts +8 -6
  88. package/dist/modules/account_bots.js +112 -131
  89. package/dist/modules/account_orders.d.ts +49 -4
  90. package/dist/modules/account_orders.js +114 -49
  91. package/dist/modules/bitshares-native/chain_client.d.ts +1 -1
  92. package/dist/modules/bitshares-native/chain_client.js +14 -13
  93. package/dist/modules/bitshares-native/crypto/ecc_core.d.ts +1 -2
  94. package/dist/modules/bitshares-native/crypto/ecc_core.js +1 -1
  95. package/dist/modules/bitshares-native/resolvers.js +22 -25
  96. package/dist/modules/bitshares-native/serial/chain_constants.d.ts +1 -2
  97. package/dist/modules/bitshares-native/serial/chain_constants.js +1 -2
  98. package/dist/modules/bitshares-native/serial/types.js +22 -50
  99. package/dist/modules/bitshares-native/signing_client.d.ts +1 -1
  100. package/dist/modules/bot_defaults.d.ts +18 -3
  101. package/dist/modules/bot_defaults.js +34 -8
  102. package/dist/modules/bot_settings.d.ts +5 -1
  103. package/dist/modules/bot_settings.js +55 -21
  104. package/dist/modules/broadcast_failure.d.ts +2 -1
  105. package/dist/modules/chain_orders.d.ts +1 -1
  106. package/dist/modules/chain_orders.js +51 -96
  107. package/dist/modules/cli_start_onboarding.d.ts +2 -1
  108. package/dist/modules/config.js +6 -1
  109. package/dist/modules/constants.d.ts +14 -6
  110. package/dist/modules/constants.js +32 -6
  111. package/dist/modules/cr_planner.d.ts +1 -1
  112. package/dist/modules/cr_planner.js +1 -5
  113. package/dist/modules/credit_pricing.d.ts +2 -1
  114. package/dist/modules/credit_pricing.js +36 -40
  115. package/dist/modules/credit_runtime.d.ts +7 -0
  116. package/dist/modules/credit_runtime.js +45 -73
  117. package/dist/modules/daemon_node_health.d.ts +4 -3
  118. package/dist/modules/dexbot_class.d.ts +33 -17
  119. package/dist/modules/dexbot_class.js +113 -61
  120. package/dist/modules/dexbot_cow_runtime.d.ts +62 -181
  121. package/dist/modules/dexbot_cow_runtime.js +380 -69
  122. package/dist/modules/dexbot_credential_client.d.ts +1 -23
  123. package/dist/modules/dexbot_credential_client.js +2 -3
  124. package/dist/modules/dexbot_fill_runtime.d.ts +2 -3
  125. package/dist/modules/dexbot_fill_runtime.js +17 -7
  126. package/dist/modules/dexbot_maintenance_runtime.d.ts +36 -81
  127. package/dist/modules/dexbot_maintenance_runtime.js +137 -133
  128. package/dist/modules/dexbot_startup_runtime.d.ts +0 -1
  129. package/dist/modules/dexbot_startup_runtime.js +25 -14
  130. package/dist/modules/dexbot_state_recovery.js +16 -0
  131. package/dist/modules/general_settings.d.ts +1 -1
  132. package/dist/modules/graceful_shutdown.js +17 -11
  133. package/dist/modules/key_store.d.ts +0 -5
  134. package/dist/modules/key_store.js +1 -2
  135. package/dist/modules/lazy_shim.d.ts +11 -0
  136. package/dist/modules/lazy_shim.js +16 -0
  137. package/dist/modules/node_connect_policy.d.ts +3 -2
  138. package/dist/modules/node_failure_ledger.d.ts +6 -5
  139. package/dist/modules/order/accounting.js +11 -11
  140. package/dist/modules/order/export.js +2 -2
  141. package/dist/modules/order/format.d.ts +26 -3
  142. package/dist/modules/order/format.js +33 -3
  143. package/dist/modules/order/genesis_policy.d.ts +4 -4
  144. package/dist/modules/order/genesis_policy.js +6 -3
  145. package/dist/modules/order/grid.d.ts +26 -12
  146. package/dist/modules/order/grid.js +468 -80
  147. package/dist/modules/order/grid_reconcile.d.ts +1 -1
  148. package/dist/modules/order/grid_reconcile.js +5 -5
  149. package/dist/modules/order/grid_reconcile_internal.js +48 -40
  150. package/dist/modules/order/index.d.ts +35 -8
  151. package/dist/modules/order/logger.d.ts +1 -8
  152. package/dist/modules/order/logger.js +2 -11
  153. package/dist/modules/order/manager.d.ts +18 -15
  154. package/dist/modules/order/manager.js +91 -74
  155. package/dist/modules/order/strategy.d.ts +2 -2
  156. package/dist/modules/order/strategy.js +51 -21
  157. package/dist/modules/order/sync_engine.js +4 -0
  158. package/dist/modules/order/utils/math.d.ts +3 -3
  159. package/dist/modules/order/utils/math.js +38 -27
  160. package/dist/modules/order/utils/order.d.ts +58 -58
  161. package/dist/modules/order/utils/order.js +158 -137
  162. package/dist/modules/order/utils/system.d.ts +202 -35
  163. package/dist/modules/order/utils/system.js +409 -31
  164. package/dist/modules/order/utils/validate.js +28 -6
  165. package/dist/modules/order/utils/withPoolRef.d.ts +2 -1
  166. package/dist/modules/paths.js +32 -34
  167. package/dist/modules/runtime_settings.d.ts +3 -5
  168. package/dist/modules/runtime_settings.js +3 -3
  169. package/dist/modules/settings_merge.d.ts +2 -2
  170. package/dist/modules/socket_json_client.d.ts +2 -1
  171. package/dist/modules/types.d.ts +89 -30
  172. package/dist/modules/utils/errors.js +1 -3
  173. package/dist/modules/version_notice.d.ts +11 -10
  174. package/dist/pm2.d.ts +0 -1
  175. package/dist/pm2.js +56 -35
  176. package/dist/scripts/analyze-git.js +2 -15
  177. package/dist/scripts/analyze-orders.d.ts +1 -1
  178. package/dist/scripts/analyze-orders.js +4 -4
  179. package/dist/scripts/chart_command.js +2 -2
  180. package/dist/scripts/check_any.d.ts +4 -0
  181. package/dist/scripts/check_any.js +53 -21
  182. package/dist/scripts/diagnose-pool-history.js +1 -6
  183. package/dist/scripts/divergence-calc.js +6 -6
  184. package/dist/scripts/run-tests.js +0 -1
  185. package/dist/scripts/sync-version.js +0 -10
  186. package/dist/scripts/validate_bots.d.ts +1 -1
  187. package/dist/scripts/validate_bots.js +3 -3
  188. package/dist/unlock.js +7 -2
  189. package/docs/BITSHARES_ONBOARDING.md +8 -12
  190. package/docs/COPY_ON_WRITE_MASTER_PLAN.md +2 -3
  191. package/docs/COW_INVARIANTS.md +6 -6
  192. package/docs/DEXBOT_COMPARISON.md +7 -7
  193. package/docs/EVOLUTION.md +10 -8
  194. package/docs/FUND_MOVEMENT_AND_ACCOUNTING.md +8 -6
  195. package/docs/GRID_PRICE_INVARIANT.md +3 -3
  196. package/docs/GRID_RECALCULATION.md +4 -1
  197. package/docs/GRID_RECONCILE.md +4 -4
  198. package/docs/LIFECYCLE.md +11 -11
  199. package/docs/LOGGING.md +14 -0
  200. package/docs/MPA_CREDIT_USAGE.md +1 -1
  201. package/docs/ORDER_ENGINE_POST_1.0_RETROSPECTIVE.md +12 -4
  202. package/docs/README.md +3 -3
  203. package/docs/WORKFLOW.md +1 -0
  204. package/docs/architecture.md +25 -16
  205. package/docs/developer_guide.md +7 -2
  206. package/market_adapter/README.md +6 -4
  207. package/package.json +6 -9
  208. package/scripts/README.md +43 -38
  209. package/tests/README.md +26 -11
  210. package/dist/scripts/diagnose-kibana-candles.d.ts +0 -3
  211. package/dist/scripts/diagnose-kibana-candles.js +0 -82
  212. package/scripts/git-viewer.sh +0 -489
  213. package/scripts/postinstall.js +0 -16
@@ -1,19 +1,20 @@
1
1
  'use strict';
2
2
  import path from 'node:path';
3
3
  import os from 'node:os';
4
- import { pathToFileURL, fileURLToPath } from 'node:url';
5
- import { Worker, isMainThread, parentPort, workerData } from 'node:worker_threads';
4
+ import { pathToFileURL } from 'node:url';
5
+ import { isMainThread, parentPort, workerData } from 'node:worker_threads';
6
6
  import { calculateAMA, getAmaWarmupBars } from '../../market_adapter/core/strategies/ama.js';
7
7
  import { computeHuberWindowSlopePct } from '../../market_adapter/core/strategies/ama_slope_model.js';
8
8
  import { range } from '../math_utils.js';
9
- import { parseListOrRange, loadLpData, fmt } from './shared_utils.js';
9
+ import { runModuleWorker } from '../worker_pool.js';
10
+ import { loadLpData, fmt, loadAmaStrategies, consumeBacktestArg, slopeResetThresholdPct, DEFAULT_FEE_ROUNDTRIP_PCT, DEFAULT_MIN_SPREAD_FACTOR, DEFAULT_BTS_CREATE_FEE, DEFAULT_BTS_CANCEL_FEE, DEFAULT_BTS_MAKER_CREATE_FACTOR, DEFAULT_TX_FEE_PRICE, DEFAULT_REPOSITION_PCT, SLOPE_LOOKBACK_BARS } from './shared_utils.js';
10
11
  import { getStorage } from '../../modules/storage/index.js';
11
12
  import { PATHS } from '../../modules/paths.js';
12
- import { GRID_LIMITS, MARKET_ADAPTER } from '../../modules/constants.js';
13
+ import { MARKET_ADAPTER } from '../../modules/constants.js';
13
14
  // Production grid geometry + slope-ratio offset — shared with bot_fitting so
14
15
  // both tools build byte-identical grids for identical params (#12).
15
16
  import { buildProductionGrid, computeGridPriceOffsetPct } from './backtest_bot_fitting.js';
16
- const { readJSON, writeJSON } = getStorage();
17
+ const { writeJSON } = getStorage();
17
18
  /**
18
19
  * AMA SWEEP BACKTEST — persistent grid simulation
19
20
  *
@@ -33,14 +34,7 @@ const { readJSON, writeJSON } = getStorage();
33
34
  * node dist/analysis/bot_fitting/backtest_ama_sweep.js --data <path-to-lp-candles.json> --spread 4:16:1 --increment 0.5:4:0.25
34
35
  */
35
36
  const DEFAULT_MAX_ORDERS = 20; // weight-profile sizing cap per side (search abstraction)
36
- const DEFAULT_FEE_ROUNDTRIP_PCT = 0.20;
37
- // Canonical spread floor from production grid limits (modules/constants.ts).
38
- const DEFAULT_MIN_SPREAD_FACTOR = GRID_LIMITS.MIN_SPREAD_FACTOR;
39
37
  const DEFAULT_CAPITAL = 10000; // notional units per side
40
- const DEFAULT_BTS_CREATE_FEE = 0.48260;
41
- const DEFAULT_BTS_CANCEL_FEE = 0.00482;
42
- const DEFAULT_BTS_MAKER_CREATE_FACTOR = 0.10;
43
- const DEFAULT_TX_FEE_PRICE = 1.0;
44
38
  // Weight profiles (symmetric for both sides)
45
39
  // valley: heavier at edges (outer levels), lighter near center
46
40
  // neutral: equal across all levels
@@ -57,14 +51,6 @@ const WEIGHT_PROFILES = {
57
51
  const DEFAULT_SPREAD_VALUES = [...range(0.5, 4, 0.25), ...range(5, 12, 1)];
58
52
  const DEFAULT_INCREMENT_VALUES = [...range(0.2, 2, 0.1), ...range(2.5, 8, 0.5)];
59
53
  const DEFAULT_RATIO_VALUES = [1.05, 1.1, 1.15, 1.2, 1.3, 1.5, 2, 3, 5, 10];
60
- // Reposition threshold: production default (MARKET_ADAPTER
61
- // AMA_DELTA_THRESHOLD_PERCENT = 1%); --reposition overrides.
62
- const DEFAULT_REPOSITION_PCT = MARKET_ADAPTER.AMA_DELTA_THRESHOLD_PERCENT;
63
- // Trigger B / grid-price offset (asymmetricBounds whitelist) — same constants
64
- // as bot_fitting, shared semantics with the live adapter.
65
- const SLOPE_TRIGGER_FACTOR = MARKET_ADAPTER.AMA_SLOPE_DELTA_THRESHOLD_PERCENT;
66
- const SLOPE_MAX_PCT = MARKET_ADAPTER.DYNAMIC_WEIGHT_AMA_MAX_SLOPE_PCT;
67
- const SLOPE_LOOKBACK_BARS = MARKET_ADAPTER.DYNAMIC_WEIGHT_AMA_LOOKBACK_BARS;
68
54
  function parseArgs() {
69
55
  const args = process.argv.slice(2);
70
56
  const out = {
@@ -99,63 +85,23 @@ function parseArgs() {
99
85
  }
100
86
  if (!val)
101
87
  continue;
88
+ if (consumeBacktestArg(arg, val, out, {
89
+ spreadValues: DEFAULT_SPREAD_VALUES,
90
+ incrementValues: DEFAULT_INCREMENT_VALUES,
91
+ ratioValues: DEFAULT_RATIO_VALUES,
92
+ })) {
93
+ i++;
94
+ continue;
95
+ }
102
96
  switch (arg) {
103
- case '--data':
104
- out.dataPath = path.resolve(val);
105
- i++;
106
- break;
107
- case '--results':
108
- out.resultsPath = path.resolve(val);
109
- i++;
110
- break;
111
- case '--spread':
112
- out.spreadValues = parseListOrRange(val, DEFAULT_SPREAD_VALUES);
113
- i++;
114
- break;
115
- case '--increment':
116
- out.incrementValues = parseListOrRange(val, DEFAULT_INCREMENT_VALUES);
117
- i++;
118
- break;
119
- case '--ratio':
120
- out.ratioValues = parseListOrRange(val, DEFAULT_RATIO_VALUES);
121
- i++;
122
- break;
123
97
  case '--max-orders':
124
98
  out.maxOrders = Number(val);
125
99
  i++;
126
100
  break;
127
- case '--fee':
128
- out.feeRoundtripPct = Number(val);
129
- i++;
130
- break;
131
- case '--min-spread-factor':
132
- out.minSpreadFactor = Number(val);
133
- i++;
134
- break;
135
101
  case '--capital':
136
102
  out.capital = Number(val);
137
103
  i++;
138
104
  break;
139
- case '--reposition':
140
- out.repositionPct = Number(val);
141
- i++;
142
- break;
143
- case '--bts-create-fee':
144
- out.btsCreateFee = Number(val);
145
- i++;
146
- break;
147
- case '--bts-cancel-fee':
148
- out.btsCancelFee = Number(val);
149
- i++;
150
- break;
151
- case '--maker-create-factor':
152
- out.makerCreateFactor = Number(val);
153
- i++;
154
- break;
155
- case '--tx-fee-price':
156
- out.txFeePrice = Number(val);
157
- i++;
158
- break;
159
105
  case '--top':
160
106
  out.topN = Number(val);
161
107
  i++;
@@ -199,23 +145,6 @@ function printHelp() {
199
145
  console.log(' --top <n> Show top N results (default: 15)');
200
146
  console.log(` --lookback <bars> Huber slope lookback override (default: ${SLOPE_LOOKBACK_BARS})`);
201
147
  }
202
- function loadAmaStrategies(resultsPath) {
203
- const json = readJSON(resultsPath);
204
- const amas = json.meta?.amas;
205
- if (!amas)
206
- throw new Error('No meta.amas found in results file.');
207
- const out = [];
208
- for (const [key, val] of Object.entries(amas)) {
209
- const v = val;
210
- if (!v || !Number.isFinite(Number(v.er)))
211
- continue;
212
- out.push({ id: key, name: String(v.label || key), er: Number(v.er), fast: Number(v.fast), slow: Number(v.slow) });
213
- }
214
- out.sort((a, b) => a.id.localeCompare(b.id));
215
- if (out.length === 0)
216
- throw new Error('No valid AMA strategies found');
217
- return out;
218
- }
219
148
  // ── Order sizing with weight profiles ────────────────────────────────────────
220
149
  /**
221
150
  * Allocate capital across N levels using weight profile.
@@ -317,7 +246,7 @@ function simulatePersistentGrid(candles, amaValues, params, weightName, weightFa
317
246
  const skip = Math.min(warmupParam, Math.max(0, candles.length - 2));
318
247
  const capitalPerSide = capital;
319
248
  const makerCreateFeeBts = btsCreateFee * makerCreateFactor;
320
- const slopeDeltaThresholdPct = (SLOPE_TRIGGER_FACTOR / 100) * SLOPE_MAX_PCT;
249
+ const slopeDeltaThresholdPct = slopeResetThresholdPct();
321
250
  // First tradable bar: need a finite positive AMA to anchor the grid.
322
251
  let startIdx = Math.min(skip, candles.length - 1);
323
252
  let gridCenter = Number.NaN;
@@ -753,18 +682,8 @@ function runParallel(strategies, candles, closes, weightEntries, cfg) {
753
682
  const numCpus = Math.min(os.cpus().length, strategies.length);
754
683
  console.log(` Workers: ${numCpus} threads (${os.cpus().length} CPUs available)\n`);
755
684
  return Promise.all(strategies.map((strategy) => {
756
- return new Promise((resolve, reject) => {
757
- // ESM: resolve this module's path from import.meta.url
758
- // (__filename is undefined in ES modules).
759
- const worker = new Worker(fileURLToPath(import.meta.url), {
760
- workerData: { strategy, candles, closes, weightEntries, cfg },
761
- });
762
- worker.on('message', (msg) => resolve(msg));
763
- worker.on('error', reject);
764
- worker.on('exit', (code) => {
765
- if (code !== 0)
766
- reject(new Error(`Worker exited with code ${code}`));
767
- });
685
+ return runModuleWorker(import.meta.url, { strategy, candles, closes, weightEntries, cfg }, {
686
+ resolveOn: (msg) => ({ done: true, value: msg }),
768
687
  });
769
688
  }));
770
689
  }
@@ -774,7 +693,7 @@ async function run() {
774
693
  const loaded = loadLpData(cfg.dataPath);
775
694
  const candles = loaded.candles;
776
695
  const closes = candles.map((c) => c.close);
777
- const strategies = loadAmaStrategies(cfg.resultsPath);
696
+ const strategies = loadAmaStrategies(cfg.resultsPath, { sort: true });
778
697
  const weightEntries = Object.entries(WEIGHT_PROFILES);
779
698
  const totalCombos = cfg.spreadValues.length * cfg.incrementValues.length *
780
699
  cfg.ratioValues.length * weightEntries.length;
@@ -791,7 +710,7 @@ async function run() {
791
710
  console.log(` Spread floor: > fee (${cfg.feeRoundtripPct}%)`);
792
711
  console.log(` Reset (A): ${cfg.repositionPct}% AMA drift from grid center (ratchet)`);
793
712
  console.log(` Asym. bounds: ${cfg.asymmetricBounds ? 'ON — slope reset (B) + grid price offset enabled (whitelist semantics)' : 'OFF — typical non-whitelisted bot (production default)'}`);
794
- console.log(` Reset (B): |slope - slope@lastReset| >= ${fmt((SLOPE_TRIGGER_FACTOR / 100) * SLOPE_MAX_PCT, 4)}% (lookback ${cfg.lookbackBars ?? SLOPE_LOOKBACK_BARS})${cfg.asymmetricBounds ? '' : ' [gated off]'}`);
713
+ console.log(` Reset (B): |slope - slope@lastReset| >= ${fmt(slopeResetThresholdPct(), 4)}% (lookback ${cfg.lookbackBars ?? SLOPE_LOOKBACK_BARS})${cfg.asymmetricBounds ? '' : ' [gated off]'}`);
795
714
  console.log(` Tx model: create=${fmt(cfg.btsCreateFee, 5)} BTS, cancel=${fmt(cfg.btsCancelFee, 5)} BTS, maker=${fmt(cfg.makerCreateFactor * 100, 1)}%, 1 BTS=${fmt(cfg.txFeePrice, 2)} units`);
796
715
  console.log(` Combos/AMA: ${totalCombos} | Total: ${totalCombos * strategies.length}\n`);
797
716
  // ── Run AMA sweeps in parallel (one worker per AMA strategy) ──────
@@ -971,5 +890,5 @@ async function run() {
971
890
  if (isMainThread && process.argv[1] && import.meta.url === pathToFileURL(process.argv[1]).href) {
972
891
  run().catch((err) => { console.error(err); process.exit(1); });
973
892
  }
974
- export { WEIGHT_PROFILES, allocateFundsByWeights, buildGrid, markInventoryAtPrice, simulatePersistentGrid, sweepOneAma };
893
+ export { WEIGHT_PROFILES, allocateFundsByWeights, buildGrid, simulatePersistentGrid, sweepOneAma };
975
894
  //# sourceMappingURL=backtest_ama_sweep.js.map
@@ -6,25 +6,23 @@ import { calculateAMA, getAmaWarmupBars } from '../../market_adapter/core/strate
6
6
  import { computeHuberWindowSlopePct } from '../../market_adapter/core/strategies/ama_slope_model.js';
7
7
  import { applyAsymmetricBounds } from '../../market_adapter/core/asymmetric_bounds.js';
8
8
  import { range } from '../math_utils.js';
9
- import { parseListOrRange, loadLpData, fmt } from './shared_utils.js';
9
+ import { loadLpData, fmt, loadAmaStrategies, consumeBacktestArg, slopeResetThresholdPct, DEFAULT_FEE_ROUNDTRIP_PCT, DEFAULT_MIN_SPREAD_FACTOR, DEFAULT_BTS_CREATE_FEE, DEFAULT_BTS_CANCEL_FEE, DEFAULT_BTS_MAKER_CREATE_FACTOR, DEFAULT_TX_FEE_PRICE, DEFAULT_REPOSITION_PCT, SLOPE_TRIGGER_FACTOR, SLOPE_MAX_PCT, SLOPE_LOOKBACK_BARS } from './shared_utils.js';
10
10
  import { getStorage } from '../../modules/storage/index.js';
11
11
  import { PATHS } from '../../modules/paths.js';
12
12
  import { GRID_LIMITS, MARKET_ADAPTER } from '../../modules/constants.js';
13
- const { ensureDir, readJSON, writeJSON } = getStorage();
13
+ const { ensureDir, writeJSON } = getStorage();
14
14
  // Default mirrors production sizing: createOrderGrid sizes EVERY rail slot in
15
15
  // bounds (modules/order/grid.ts), it does not cap per side. Infinity = all
16
16
  // slots; --active-orders N restores a bounded run.
17
17
  const DEFAULT_ACTIVE_ORDERS = Infinity;
18
- const DEFAULT_FEE_ROUNDTRIP_PCT = 0.20;
19
- // BTS operation fees — same model as backtest_ama_sweep. Every placement
20
- // (initial grid, reset rebuild, per-cycle slot refill) pays a maker create
21
- // fee, every cancel pays a cancel fee. Fees are converted into percentage
22
- // points against --bts-fee-capital so they deduct from net capture in the
23
- // same units as the rest of the accounting.
24
- const DEFAULT_BTS_CREATE_FEE = 0.48260;
25
- const DEFAULT_BTS_CANCEL_FEE = 0.00482;
26
- const DEFAULT_BTS_MAKER_CREATE_FACTOR = 0.10;
27
- const DEFAULT_TX_FEE_PRICE = 1.0;
18
+ // BTS operation fees are shared with backtest_ama_sweep via shared_utils; the
19
+ // fee-capital base (the notional the fee percentage is measured against) is
20
+ // bot_fitting-specific.
21
+ //
22
+ // Every placement (initial grid, reset rebuild, per-cycle slot refill) pays a
23
+ // maker create fee, every cancel pays a cancel fee. Fees are converted into
24
+ // percentage points against --bts-fee-capital so they deduct from net capture
25
+ // in the same units as the rest of the accounting.
28
26
  const DEFAULT_BTS_FEE_CAPITAL = 10000;
29
27
  // ── Production grid-reset triggers (MARKET_ADAPTER, modules/constants.ts) ────
30
28
  //
@@ -33,7 +31,6 @@ const DEFAULT_BTS_FEE_CAPITAL = 10000;
33
31
  // from that recorded center; the center re-records only when a trigger fires
34
32
  // (ratchet semantics — see analyze_ama_price_changes.trackRepositions).
35
33
  // --reposition-pct overrides the default.
36
- const DEFAULT_REPOSITION_PCT = MARKET_ADAPTER.AMA_DELTA_THRESHOLD_PERCENT;
37
34
  //
38
35
  // Trigger B — AMA slope delta, plus the grid price offset, are BOTH gated in
39
36
  // production behind the per-bot asymmetricBounds whitelist
@@ -47,16 +44,11 @@ const DEFAULT_REPOSITION_PCT = MARKET_ADAPTER.AMA_DELTA_THRESHOLD_PERCENT;
47
44
  // where slopePct is the Huber-robust per-bar AMA slope over
48
45
  // DYNAMIC_WEIGHT_AMA_LOOKBACK_BARS (computeHuberWindowSlopePct) and the
49
46
  // baseline mirrors botState.gridRangeScalingAmaSlope (re-seeded every reset).
50
- const SLOPE_TRIGGER_FACTOR = MARKET_ADAPTER.AMA_SLOPE_DELTA_THRESHOLD_PERCENT;
51
- const SLOPE_MAX_PCT = MARKET_ADAPTER.DYNAMIC_WEIGHT_AMA_MAX_SLOPE_PCT;
52
- const SLOPE_LOOKBACK_BARS = MARKET_ADAPTER.DYNAMIC_WEIGHT_AMA_LOOKBACK_BARS;
53
47
  const SLOPE_NEUTRAL_ZONE_PCT = MARKET_ADAPTER.DYNAMIC_WEIGHT_AMA_NEUTRAL_ZONE_PCT;
54
48
  // Spread-gap floor knobs (GRID_LIMITS): the effective target spread is
55
49
  // clamped up to incrementPercent × MIN_SPREAD_FACTOR and the gap is never
56
50
  // narrower than MIN_SPREAD_ORDERS slots — mirrored from calculateGapSlots
57
51
  // (modules/order/utils/math.ts).
58
- const DEFAULT_MIN_SPREAD_FACTOR = GRID_LIMITS.MIN_SPREAD_FACTOR;
59
- // Inventory-risk penalty weights (in score points)
60
52
  const RISK_W_DURATION = 1.0; // avg open bars
61
53
  const RISK_W_PEAK_OPEN = 2.0; // peak simultaneous open orders
62
54
  const RISK_W_IMBALANCE = 1.2; // avg |openBuy-openSell|
@@ -98,59 +90,19 @@ function parseArgs() {
98
90
  const val = args[i + 1];
99
91
  if (!val)
100
92
  continue;
93
+ if (consumeBacktestArg(arg, val, out, {
94
+ spreadValues: DEFAULT_SPREAD_VALUES,
95
+ incrementValues: DEFAULT_INCREMENT_VALUES,
96
+ ratioValues: DEFAULT_RATIO_VALUES,
97
+ })) {
98
+ i++;
99
+ continue;
100
+ }
101
101
  switch (arg) {
102
- case '--data':
103
- out.dataPath = path.resolve(val);
104
- i++;
105
- break;
106
- case '--results':
107
- out.resultsPath = path.resolve(val);
108
- i++;
109
- break;
110
- case '--spread':
111
- out.spreadValues = parseListOrRange(val, DEFAULT_SPREAD_VALUES);
112
- i++;
113
- break;
114
- case '--increment':
115
- out.incrementValues = parseListOrRange(val, DEFAULT_INCREMENT_VALUES);
116
- i++;
117
- break;
118
- case '--ratio':
119
- out.ratioValues = parseListOrRange(val, DEFAULT_RATIO_VALUES);
120
- i++;
121
- break;
122
102
  case '--active-orders':
123
103
  out.activeOrders = Number(val);
124
104
  i++;
125
105
  break;
126
- case '--fee':
127
- out.feeRoundtripPct = Number(val);
128
- i++;
129
- break;
130
- case '--min-spread-factor':
131
- out.minSpreadFactor = Number(val);
132
- i++;
133
- break;
134
- case '--reposition-pct':
135
- out.repositionPct = Number(val);
136
- i++;
137
- break;
138
- case '--bts-create-fee':
139
- out.btsCreateFee = Number(val);
140
- i++;
141
- break;
142
- case '--bts-cancel-fee':
143
- out.btsCancelFee = Number(val);
144
- i++;
145
- break;
146
- case '--maker-create-factor':
147
- out.makerCreateFactor = Number(val);
148
- i++;
149
- break;
150
- case '--tx-fee-price':
151
- out.txFeePrice = Number(val);
152
- i++;
153
- break;
154
106
  case '--bts-fee-capital':
155
107
  out.btsFeeCapital = Number(val);
156
108
  i++;
@@ -217,28 +169,6 @@ function resolveAutoResultsPath(dataPath) {
217
169
  return newest.file;
218
170
  return path.join(PATHS.ANALYSIS.RESULTS_DIR, `optimization_results_${base}.json`);
219
171
  }
220
- function loadAmaStrategies(resultsPath) {
221
- const json = readJSON(resultsPath);
222
- const amas = json.meta?.amas ?? {};
223
- const labels = { AMA1: 'AMA1', AMA2: 'AMA2', AMA3: 'AMA3', AMA4: 'AMA4' };
224
- const out = [];
225
- for (const [key, val] of Object.entries(amas)) {
226
- const a = val;
227
- if (!a || !Number.isFinite(Number(a.er)) || !Number.isFinite(Number(a.fast)) || !Number.isFinite(Number(a.slow)))
228
- continue;
229
- out.push({
230
- id: key,
231
- name: labels[key] ?? key,
232
- er: Number(a.er),
233
- fast: Number(a.fast),
234
- slow: Number(a.slow),
235
- });
236
- }
237
- if (out.length !== 4) {
238
- throw new Error(`Expected 4 AMA strategies in results meta.amas, found ${out.length}`);
239
- }
240
- return out;
241
- }
242
172
  /**
243
173
  * Spread-gap width in slots — direct port of calculateGapSlots
244
174
  * (modules/order/utils/math.ts:1228). The effective target spread is clamped
@@ -343,7 +273,7 @@ function simulateForParams(candles, amaValues, params) {
343
273
  // start on SMA-warmup values when the fitted ER period is large.
344
274
  const skip = Math.min(params.warmupBars, Math.max(0, candles.length - 2));
345
275
  const singleLegFeePct = feeRoundtripPct / 2;
346
- const slopeDeltaThresholdPct = (SLOPE_TRIGGER_FACTOR / 100) * SLOPE_MAX_PCT;
276
+ const slopeDeltaThresholdPct = slopeResetThresholdPct();
347
277
  const makerCreateFeeBts = btsCreateFee * makerCreateFactor;
348
278
  const stepUpFrac = 1 + incrementPct; // one-rail-step rotation distance
349
279
  // Optional gate/band overrides. `slopePersistBars` follows the production
@@ -696,7 +626,11 @@ function run() {
696
626
  const loaded = loadLpData(cfg.dataPath);
697
627
  const candles = loaded.candles;
698
628
  const closes = candles.map((c) => c.close);
699
- const strategies = loadAmaStrategies(cfg.resultsPath);
629
+ const strategies = loadAmaStrategies(cfg.resultsPath, {
630
+ requireAllFields: true,
631
+ exactCount: 4,
632
+ labels: { AMA1: 'AMA1', AMA2: 'AMA2', AMA3: 'AMA3', AMA4: 'AMA4' },
633
+ });
700
634
  if (!Number.isFinite(cfg.repositionPct) || cfg.repositionPct <= 0) {
701
635
  throw new Error(`Invalid reposition threshold: ${cfg.repositionPct}`);
702
636
  }
@@ -714,7 +648,7 @@ function run() {
714
648
  console.log(` Spread floor: spread >= ${cfg.minSpreadFactor} x increment`);
715
649
  console.log(` Reset (A): AMA drift >= ${cfg.repositionPct}% from recorded center${cfg.repositionPct === DEFAULT_REPOSITION_PCT ? ' (AMA_DELTA_THRESHOLD_PERCENT)' : ''}`);
716
650
  console.log(` Asym. bounds: ${cfg.asymmetricBounds ? 'ON — slope reset (B) + grid price offset enabled (whitelist semantics)' : 'OFF — typical non-whitelisted bot (production default)'}`);
717
- console.log(` Reset (B): |slope - slope@lastReset| >= ${(SLOPE_TRIGGER_FACTOR / 100) * SLOPE_MAX_PCT}% (${SLOPE_TRIGGER_FACTOR}% x ${SLOPE_MAX_PCT}, lookback ${SLOPE_LOOKBACK_BARS})${cfg.asymmetricBounds ? '' : ' [gated off]'}`);
651
+ console.log(` Reset (B): |slope - slope@lastReset| >= ${slopeResetThresholdPct()}% (${SLOPE_TRIGGER_FACTOR}% x ${SLOPE_MAX_PCT}, lookback ${SLOPE_LOOKBACK_BARS})${cfg.asymmetricBounds ? '' : ' [gated off]'}`);
718
652
  console.log(` Tx fees: create=${fmt(cfg.btsCreateFee * cfg.makerCreateFactor, 5)} BTS, cancel=${fmt(cfg.btsCancelFee, 5)} BTS, 1 BTS=${fmt(cfg.txFeePrice, 2)} units, capital=${fmt(cfg.btsFeeCapital, 0)}`);
719
653
  console.log(` Risk W: duration=${cfg.riskWDuration}, peakOpen=${cfg.riskWPeakOpen}, imbalance=${cfg.riskWImbalance}, cancel=${cfg.riskWCancel}`);
720
654
  console.log(` Combos/AMA: ${totalCombos}\n`);
@@ -810,7 +744,7 @@ function run() {
810
744
  baseScore: 'totalNetCaptureAfterFeesPct * (fillEfficiency / 100)',
811
745
  gridModel: 'persistent fixed chain prices (createOrderGrid port): master rail at sqrt(1±inc) offsets bounded by [center/ratio, center*ratio], gapSlots spread zone centered on center; prices never follow AMA after placement',
812
746
  spreadParam: 'targetSpreadPercent for calculateGapSlots (floored at increment * MIN_SPREAD_FACTOR)',
813
- resetTriggers: `(A) AMA drift >= ${cfg.repositionPct}% from recorded center (ratchet)${cfg.asymmetricBounds ? ` OR (B) |slope - slopeAtLastReset| >= ${(SLOPE_TRIGGER_FACTOR / 100) * SLOPE_MAX_PCT}% over ${SLOPE_LOOKBACK_BARS}-bar average slope (baseline re-seeded on every reset)` : ' (trigger B gated off — asymmetricBounds whitelist)'}`,
747
+ resetTriggers: `(A) AMA drift >= ${cfg.repositionPct}% from recorded center (ratchet)${cfg.asymmetricBounds ? ` OR (B) |slope - slopeAtLastReset| >= ${slopeResetThresholdPct()}% over ${SLOPE_LOOKBACK_BARS}-bar average slope (baseline re-seeded on every reset)` : ' (trigger B gated off — asymmetricBounds whitelist)'}`,
814
748
  gridPriceOffset: cfg.asymmetricBounds ? 'slope-ratio offset applied to placement center (direction * min(|slope|/maxSlopePct,1) * targetSpread/2) on every grid build' : 'disabled (asymmetricBounds whitelist)',
815
749
  repositionAccounting: 'unfilled orders canceled + counted (incl armed refills/rebids); bought-and-held base carries across resets in a weighted-average-entry inventory pool (resync never market-sells); end-of-run inventory mark is informational and excluded from scoring',
816
750
  cycleEconomics: 'slot rotation: filled buy re-offers one rail step up; that refill selling books ~increment% minus round-trip fee and the freed quote re-bids one step down; unlinked initial-grid sells only execute against held inventory at weighted-average entry (no shorting)',
@@ -33,8 +33,9 @@ import fs from 'node:fs';
33
33
  import path from 'node:path';
34
34
  import { pathToFileURL } from 'node:url';
35
35
  import { calculateAMA, getAmaWarmupBars } from '../../market_adapter/core/strategies/ama.js';
36
- import { loadCandles } from '../trend_detection/backtest_ama_slope_huber.js';
37
36
  import { parseListOrRange } from './shared_utils.js';
37
+ import { printHelpHeader, helpRow } from '../analyze_args.js';
38
+ import { median, percentile, fmtNum as fmt, loadCandleSeries } from '../math_utils.js';
38
39
  import { simulatePersistentGrid, WEIGHT_PROFILES } from './backtest_ama_sweep.js';
39
40
  import { getStorage } from '../../modules/storage/index.js';
40
41
  import { PATHS } from '../../modules/paths.js';
@@ -157,23 +158,19 @@ function parseArgs() {
157
158
  return out;
158
159
  }
159
160
  function printHelp() {
160
- console.log('Lookback -> fill-model drawdown backtest (paired persistent-grid simulation)');
161
- console.log('');
162
- console.log('Usage: node dist/analysis/bot_fitting/backtest_lookback_drawdown.js [options]');
163
- console.log('');
164
- console.log('Options:');
165
- console.log(' --data <path> LP candle file or shard directory (required)');
166
- console.log(` --ama <AMA1..AMA4> Built-in AMA preset (default: ${MA.DEFAULT_AMA_KEY})`);
167
- console.log(` --lookbacks <spec> Lookbacks to compare: 12,14,16,20 (default: ${DEFAULT_LOOKBACKS.join(',')})`);
168
- console.log(` --spread <spec> Spread grid (default: ${DEFAULT_SPREADS.join(',')})`);
169
- console.log(` --increment <spec> Increment grid (default: ${DEFAULT_INCREMENTS.join(',')})`);
170
- console.log(` --ratio <spec> Max/min ratio grid (default: ${DEFAULT_RATIOS.join(',')})`);
171
- console.log(' --max-orders <n> Size cap per side (default: 20)');
172
- console.log(' --fee <pct> Round-trip fee % (default: 0.20)');
173
- console.log(' --capital <n> Notional capital per side (default: 10000)');
174
- console.log(` --reposition <pct> AMA drift % to re-center (default: ${MA.AMA_DELTA_THRESHOLD_PERCENT})`);
175
- console.log(' --no-asymmetric-bounds Disable trigger B + slope offset (default: enabled)');
176
- console.log(' --out <path> JSON output path');
161
+ printHelpHeader('Lookback -> fill-model drawdown backtest (paired persistent-grid simulation)', 'bot_fitting/backtest_lookback_drawdown.js');
162
+ console.log(helpRow('--data <path>', 'LP candle file or shard directory (required)', 25));
163
+ console.log(helpRow('--ama <AMA1..AMA4>', `Built-in AMA preset (default: ${MA.DEFAULT_AMA_KEY})`, 25));
164
+ console.log(helpRow('--lookbacks <spec>', `Lookbacks to compare: 12,14,16,20 (default: ${DEFAULT_LOOKBACKS.join(',')})`, 25));
165
+ console.log(helpRow('--spread <spec>', `Spread grid (default: ${DEFAULT_SPREADS.join(',')})`, 25));
166
+ console.log(helpRow('--increment <spec>', `Increment grid (default: ${DEFAULT_INCREMENTS.join(',')})`, 25));
167
+ console.log(helpRow('--ratio <spec>', `Max/min ratio grid (default: ${DEFAULT_RATIOS.join(',')})`, 25));
168
+ console.log(helpRow('--max-orders <n>', 'Size cap per side (default: 20)', 25));
169
+ console.log(helpRow('--fee <pct>', 'Round-trip fee % (default: 0.20)', 25));
170
+ console.log(helpRow('--capital <n>', 'Notional capital per side (default: 10000)', 25));
171
+ console.log(helpRow('--reposition <pct>', `AMA drift % to re-center (default: ${MA.AMA_DELTA_THRESHOLD_PERCENT})`, 25));
172
+ console.log(helpRow('--no-asymmetric-bounds', 'Disable trigger B + slope offset (default: enabled)', 25));
173
+ console.log(helpRow('--out <path>', 'JSON output path', 25));
177
174
  }
178
175
  function resolveAma(name) {
179
176
  const presets = MA.AMAS;
@@ -182,22 +179,10 @@ function resolveAma(name) {
182
179
  throw new Error(`Unknown AMA preset '${name}' (expected ${Object.keys(presets).join(', ')})`);
183
180
  return { name, er: preset.erPeriod, fast: preset.fastPeriod, slow: preset.slowPeriod };
184
181
  }
185
- function median(values) {
186
- const s = values.slice().sort((a, b) => a - b);
187
- const mid = s.length >> 1;
188
- return s.length % 2 ? s[mid] : (s[mid - 1] + s[mid]) / 2;
189
- }
190
- function percentile(values, pct) {
191
- const s = values.slice().sort((a, b) => a - b);
192
- return s[Math.min(s.length - 1, Math.max(0, Math.floor((pct / 100) * (s.length - 1))))];
193
- }
194
- function fmt(x, d = 2) {
195
- return Number.isFinite(Number(x)) ? Number(x).toFixed(d) : 'n/a';
196
- }
197
182
  function run() {
198
183
  const cfg = parseArgs();
199
184
  const amaDef = resolveAma(cfg.amaName);
200
- const { candles, files } = loadCandles(cfg.dataPath);
185
+ const { candles, files } = loadCandleSeries(cfg.dataPath);
201
186
  const closes = candles.map((c) => c.close);
202
187
  const amaValues = calculateAMA(closes, { erPeriod: amaDef.er, fastPeriod: amaDef.fast, slowPeriod: amaDef.slow });
203
188
  const warmupBars = getAmaWarmupBars(amaDef.er, amaDef.slow, 0, amaDef.fast);
@@ -260,7 +245,7 @@ function run() {
260
245
  for (const [label, field, mul, d] of fields) {
261
246
  let row = ` ${label.padEnd(20).slice(0, 20)} |`;
262
247
  for (const lb of cfg.lookbacks) {
263
- row += fmt(median(keys.map((k) => byLookback[lb][k][field] * mul)), d).padStart(12);
248
+ row += fmt(median(keys.map((k) => byLookback[lb][k][field] * mul)) ?? Number.NaN, d).padStart(12);
264
249
  }
265
250
  console.log(row);
266
251
  }
@@ -272,8 +257,8 @@ function run() {
272
257
  const deltas = keys.map((k) => byLookback[lb][k].maxDrawdownPct - ref[k].maxDrawdownPct);
273
258
  const lower = deltas.filter((d) => d < 0).length;
274
259
  console.log(` ${String(lb).padStart(2)} | ` +
275
- `${fmt(median(deltas)).padStart(12)} | ` +
276
- `${fmt(percentile(deltas, 25))} .. ${fmt(percentile(deltas, 75))} | ` +
260
+ `${fmt(median(deltas) ?? Number.NaN).padStart(12)} | ` +
261
+ `${fmt(percentile(deltas, 25, { interpolation: 'nearest', rounding: 'floor', empty: Number.NaN }))} .. ${fmt(percentile(deltas, 75, { interpolation: 'nearest', rounding: 'floor', empty: Number.NaN }))} | ` +
277
262
  `${lower}/${deltas.length} (${fmt((100 * lower) / deltas.length, 0)}%)`);
278
263
  }
279
264
  console.log('\n Reminder: the sign is pool-dependent and the absolute level is model-shaped');
@@ -1,3 +1,45 @@
1
+ /**
2
+ * Shared utilities for bot-fitting scripts.
3
+ *
4
+ * Also owns the backtest defaults/fee model shared by backtest_ama_sweep and
5
+ * backtest_bot_fitting, which previously declared byte-identical local copies.
6
+ */
7
+ declare const DEFAULT_FEE_ROUNDTRIP_PCT = 0.2;
8
+ declare const DEFAULT_MIN_SPREAD_FACTOR: number;
9
+ declare const DEFAULT_BTS_CREATE_FEE = 0.4826;
10
+ declare const DEFAULT_BTS_CANCEL_FEE = 0.00482;
11
+ declare const DEFAULT_BTS_MAKER_CREATE_FACTOR = 0.1;
12
+ declare const DEFAULT_TX_FEE_PRICE = 1;
13
+ declare const DEFAULT_REPOSITION_PCT: number;
14
+ declare const SLOPE_TRIGGER_FACTOR: number;
15
+ declare const SLOPE_MAX_PCT: number;
16
+ declare const SLOPE_LOOKBACK_BARS: number;
17
+ /** Slope-reset threshold in percent: (trigger factor/100) * max slope pct. */
18
+ declare function slopeResetThresholdPct(): number;
19
+ interface AmaStrategy {
20
+ id: string;
21
+ name: string;
22
+ er: number;
23
+ fast: number;
24
+ slow: number;
25
+ }
26
+ interface LoadAmaStrategiesOptions {
27
+ /** Require `fast` and `slow` to be finite too (default: only `er`). */
28
+ requireAllFields?: boolean;
29
+ /** Throw unless exactly this many strategies parse (default: no exact check). */
30
+ exactCount?: number | null;
31
+ /** Sort by `id` ascending. */
32
+ sort?: boolean;
33
+ /** Display-name lookup; when omitted use the entry's `label` field. */
34
+ labels?: Record<string, string> | null;
35
+ }
36
+ /**
37
+ * Read the `meta.amas` preset table from an optimization results file and map
38
+ * it to strategy descriptors. Single home for the loader previously copied into
39
+ * backtest_bot_fitting and backtest_ama_sweep; the options preserve each
40
+ * caller's validation and naming rules.
41
+ */
42
+ declare function loadAmaStrategies(resultsPath: string, options?: LoadAmaStrategiesOptions): AmaStrategy[];
1
43
  declare function parseListOrRange(spec: string | null | undefined, fallback: number[]): number[];
2
44
  declare function loadLpData(filePath: string): {
3
45
  candles: {
@@ -8,8 +50,34 @@ declare function loadLpData(filePath: string): {
8
50
  close: number;
9
51
  volume: number;
10
52
  }[];
11
- meta: {} | null;
53
+ meta: Record<string, unknown> | null;
12
54
  };
13
- declare function fmt(x: number, d?: number): string;
14
- export { parseListOrRange, loadLpData, fmt };
55
+ declare const fmt: (x: number, d?: number) => string;
56
+ interface BacktestArgTarget {
57
+ dataPath?: string | null;
58
+ resultsPath?: string | null;
59
+ spreadValues?: number[];
60
+ incrementValues?: number[];
61
+ ratioValues?: number[];
62
+ feeRoundtripPct?: number;
63
+ minSpreadFactor?: number;
64
+ repositionPct?: number;
65
+ btsCreateFee?: number;
66
+ btsCancelFee?: number;
67
+ makerCreateFactor?: number;
68
+ txFeePrice?: number;
69
+ }
70
+ interface BacktestListDefaults {
71
+ spreadValues: number[];
72
+ incrementValues: number[];
73
+ ratioValues: number[];
74
+ }
75
+ /**
76
+ * Consume one flag shared by backtest_ama_sweep and backtest_bot_fitting.
77
+ * Returns true when `arg` was handled, so the caller advances past its value.
78
+ * Both `--reposition` and `--reposition-pct` spellings are accepted so the two
79
+ * tools converge without breaking either CLI.
80
+ */
81
+ declare function consumeBacktestArg(arg: string, val: string, out: BacktestArgTarget, defaults: BacktestListDefaults): boolean;
82
+ export { parseListOrRange, loadLpData, fmt, loadAmaStrategies, consumeBacktestArg, slopeResetThresholdPct, DEFAULT_FEE_ROUNDTRIP_PCT, DEFAULT_MIN_SPREAD_FACTOR, DEFAULT_BTS_CREATE_FEE, DEFAULT_BTS_CANCEL_FEE, DEFAULT_BTS_MAKER_CREATE_FACTOR, DEFAULT_TX_FEE_PRICE, DEFAULT_REPOSITION_PCT, SLOPE_TRIGGER_FACTOR, SLOPE_MAX_PCT, SLOPE_LOOKBACK_BARS, };
15
83
  //# sourceMappingURL=shared_utils.d.ts.map