dexbot 1.6.10 → 1.6.11

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 (76) hide show
  1. package/CHANGELOG.md +16 -0
  2. package/README.md +1 -0
  3. package/analysis/README.md +49 -11
  4. package/analysis/bot_fitting/README.md +12 -0
  5. package/analysis/tradingview/README.md +2 -2
  6. package/analysis/trend_detection/DYNAMIC_WEIGHT_RESEARCH.md +10 -36
  7. package/analysis/trend_detection/README.md +31 -0
  8. package/claw/package.json +1 -1
  9. package/claw/runtimes/openclaw-plugin/openclaw.plugin.json +1 -1
  10. package/claw/runtimes/openclaw-plugin/package.json +1 -1
  11. package/dist/analysis/account_resolver.js +13 -1
  12. package/dist/analysis/analyze_dynamic_weight.js +0 -3
  13. package/dist/analysis/bot_fitting/backtest_ama_sweep.js +51 -7
  14. package/dist/analysis/bot_fitting/backtest_bot_fitting.js +65 -7
  15. package/dist/analysis/bot_fitting/backtest_lookback_drawdown.d.ts +21 -0
  16. package/dist/analysis/bot_fitting/backtest_lookback_drawdown.js +315 -0
  17. package/dist/analysis/bot_key_utils.js +3 -13
  18. package/dist/analysis/fills_cache.d.ts +64 -0
  19. package/dist/analysis/fills_cache.js +254 -0
  20. package/dist/analysis/fills_source.js +5 -2
  21. package/dist/analysis/pnl_report.d.ts +39 -0
  22. package/dist/analysis/pnl_report.js +325 -0
  23. package/dist/analysis/resolve_source.d.ts +0 -1
  24. package/dist/analysis/trade_profitability.d.ts +11 -2
  25. package/dist/analysis/trade_profitability.js +187 -61
  26. package/dist/analysis/tradingview/analyze_tradingview.js +3 -5
  27. package/dist/analysis/tradingview/grid_reset_config.d.ts +2 -0
  28. package/dist/analysis/tradingview/grid_reset_config.js +18 -1
  29. package/dist/analysis/tradingview/grid_reset_sim.d.ts +1 -0
  30. package/dist/analysis/tradingview/grid_reset_sim.js +38 -2
  31. package/dist/analysis/tradingview/tradingview_uplot_chart_generator.js +2 -1
  32. package/dist/analysis/trend_detection/backtest_ama_slope_huber.d.ts +102 -0
  33. package/dist/analysis/trend_detection/backtest_ama_slope_huber.js +725 -0
  34. package/dist/analysis/trend_detection/dynamic_weight_chart_generator.js +22 -108
  35. package/dist/analysis/trend_detection/huber_scale_variants.d.ts +34 -0
  36. package/dist/analysis/trend_detection/huber_scale_variants.js +176 -0
  37. package/dist/dexbot.js +6 -3
  38. package/dist/market_adapter/core/market_adapter_service.d.ts +15 -0
  39. package/dist/market_adapter/core/market_adapter_service.js +64 -5
  40. package/dist/market_adapter/core/strategies/ama.d.ts +1 -1
  41. package/dist/market_adapter/core/strategies/ama.js +5 -28
  42. package/dist/market_adapter/core/strategies/dynamic_weight_series.d.ts +2 -2
  43. package/dist/market_adapter/core/strategies/dynamic_weight_series.js +2 -2
  44. package/dist/market_adapter/inputs/fetch_cex_synthetic_data.js +1 -2
  45. package/dist/market_adapter/log_format.js +1 -2
  46. package/dist/market_adapter/market_adapter.d.ts +0 -1
  47. package/dist/market_adapter/market_adapter.js +2 -27
  48. package/dist/modules/constants.d.ts +3 -1
  49. package/dist/modules/constants.js +39 -15
  50. package/dist/modules/dexbot_maintenance_runtime.js +12 -0
  51. package/dist/modules/order/accounting.js +25 -0
  52. package/dist/modules/order/format.d.ts +35 -15
  53. package/dist/modules/order/format.js +62 -16
  54. package/dist/modules/order/manager.d.ts +1 -0
  55. package/dist/modules/order/manager.js +22 -1
  56. package/dist/modules/order/sync_engine.js +15 -1
  57. package/dist/modules/order/utils/order.d.ts +21 -1
  58. package/dist/modules/order/utils/order.js +80 -2
  59. package/dist/modules/paths.d.ts +2 -0
  60. package/dist/modules/paths.js +2 -0
  61. package/dist/modules/utils/time_range.d.ts +15 -0
  62. package/dist/modules/utils/time_range.js +18 -0
  63. package/dist/scripts/analyze-orders.js +1 -44
  64. package/dist/scripts/chart_command.js +3 -4
  65. package/dist/scripts/pnl.d.ts +3 -0
  66. package/dist/scripts/pnl.js +40 -0
  67. package/dist/unlock.js +34 -0
  68. package/docs/DEXBOT_COMPARISON.md +3 -3
  69. package/docs/EVOLUTION.md +10 -9
  70. package/docs/FUND_MOVEMENT_AND_ACCOUNTING.md +1 -1
  71. package/docs/GRID_RECALCULATION.md +12 -15
  72. package/docs/README.md +2 -2
  73. package/docs/WORKFLOW.md +1 -0
  74. package/market_adapter/README.md +4 -26
  75. package/package.json +1 -1
  76. package/scripts/README.md +14 -0
@@ -50,7 +50,11 @@ interface PairAnalysis {
50
50
  totalRealizedPnlNet: number;
51
51
  netPosition: number;
52
52
  }
53
- declare function classifyFills(fills: FillRecord[], filterAsset: string | null): {
53
+ declare function parseArgs(argv?: string[]): any;
54
+ declare function classifyFills(fills: FillRecord[], filterAsset: string | null, pairFilter?: {
55
+ base: string;
56
+ quote: string;
57
+ } | null): {
54
58
  trades: TradeFill[];
55
59
  pairs: Set<string>;
56
60
  };
@@ -89,6 +93,8 @@ interface TradingMetrics {
89
93
  worstTradePct: number;
90
94
  mddPct: number;
91
95
  mddAbsBts: number;
96
+ /** Lowest cumulative equity before a stable peak formed (quote asset); 0 when a peak existed. */
97
+ prePeakMinEquity: number;
92
98
  mddHadStablePeak: boolean;
93
99
  isOngoingRecovery: boolean;
94
100
  currentDrawdownDays: number;
@@ -110,5 +116,8 @@ interface TradingMetrics {
110
116
  pctRLessNeg1: number;
111
117
  }
112
118
  declare function computeMetrics(pair: PairAnalysis, window?: WindowRange): TradingMetrics;
113
- export { analyzePair, classifyFills, computeMetrics, TradeFill, FillRecord, RealizedPnl, PairAnalysis, TradingMetrics };
119
+ /** Auto-named report file: bot/account + pair filter + requested range. */
120
+ declare function reportFileName(opts: any, accountRef: string, botName: string | null): string;
121
+ declare function run(argv?: string[]): Promise<void>;
122
+ export { analyzePair, classifyFills, computeMetrics, parseArgs, run, reportFileName, TradeFill, FillRecord, RealizedPnl, PairAnalysis, TradingMetrics, WindowRange };
114
123
  //# sourceMappingURL=trade_profitability.d.ts.map
@@ -1,9 +1,18 @@
1
1
  #!/usr/bin/env node
2
2
  'use strict';
3
3
  import fs from 'node:fs';
4
+ import path from 'node:path';
4
5
  import { pathToFileURL } from 'node:url';
5
6
  import { resolveAccountRef } from './account_resolver.js';
6
- import { BTS_ID, assetPrec as getPrec, assetSymbol, fetchAllFills, resolveAssetPrecisions, toReal, } from './fills_source.js';
7
+ import { BTS_ID, assetPrec as getPrec, assetSymbol, resolveAssetPrecisions, toReal, } from './fills_source.js';
8
+ import { writePnlReport } from './pnl_report.js';
9
+ import { fetchFillsCached } from './fills_cache.js';
10
+ import { toFileUrl } from './chart_utils.js';
11
+ import { PATHS } from '../modules/paths.js';
12
+ import { sanitizeKey } from '../modules/utils/sanitize_key.js';
13
+ import { monthsToHours } from '../modules/utils/time_range.js';
14
+ import { muteChainLogs } from '../modules/utils/chain_logs.js';
15
+ import { formatFundsValue } from '../modules/order/format.js';
7
16
  /**
8
17
  * TRADE PROFITABILITY ANALYZER
9
18
  *
@@ -13,12 +22,12 @@ import { BTS_ID, assetPrec as getPrec, assetSymbol, fetchAllFills, resolveAssetP
13
22
  *
14
23
  * Usage:
15
24
  * node dist/analysis/trade_profitability.js 1.2.3 --start 2025-01-01 --end 2025-06-01
16
- * node dist/analysis/trade_profitability.js 1.2.3 --hours 720
25
+ * node dist/analysis/trade_profitability.js 1.2.3 --month 3
17
26
  * node dist/analysis/trade_profitability.js 1.2.3 --start 2025-01-01T00:00:00Z --end 2025-06-01T00:00:00Z
18
27
  * node dist/analysis/trade_profitability.js 1.2.3 --hours 168 --asset 1.3.113
19
28
  * node dist/analysis/trade_profitability.js 1.2.3 --hours 168 --csv trades.csv
20
29
  * node dist/analysis/trade_profitability.js 1.2.3 --hours 168 --json results.json
21
- * node dist/analysis/trade_profitability.js "account-name" --hours 168
30
+ * node dist/analysis/trade_profitability.js "account-name" --month 3
22
31
  * node dist/analysis/trade_profitability.js 1.2.3 --hours 168 --trades
23
32
  * node dist/analysis/trade_profitability.js 1.2.3 --hours 168 --match-mode fifo
24
33
  */
@@ -27,47 +36,53 @@ let BLOCKCHAIN_FEE_PER_FILL = 0.09652; // BTS — flat blockchain operation fee
27
36
  // ─── CLI ──────────────────────────────────────────────────────────────────────
28
37
  function printHelp() {
29
38
  console.log(`\
30
- Usage: node dist/analysis/trade_profitability.js <accountId> [options]
39
+ Usage: node dist/analysis/trade_profitability.js <account|bot> [options]
31
40
 
32
41
  Analyzes filled orders for a BitShares account, computing realized PnL
33
42
  via FIFO or sequential (LIFO) inventory tracking.
34
43
 
35
44
  Arguments:
36
- accountId BitShares account ID (1.2.x) or name (auto-resolved in the background)
45
+ account|bot Local bot profile name, BitShares account name, or 1.2.x id.
46
+ Local profiles are checked first, then the chain.
37
47
 
38
48
  Options:
49
+ --month <n> Lookback months (730 h each; default 3; alias --months).
39
50
  --start <iso> Start time (ISO 8601, e.g. 2025-01-01 or 2025-01-01T00:00:00Z)
40
51
  --end <iso> End time (ISO 8601)
41
- --hours <n> Lookback hours from now (alternative to --start/--end)
52
+ --hours <n> Lookback hours from now (alternative to --month/--start/--end)
53
+ --pair <BASE/QUOTE> Filter to one pair, by symbol or 1.3.x id (e.g. TOKENA/BTS)
42
54
  --asset <assetId> Filter to one base asset (e.g. 1.3.113 for bitUSD)
43
- --refresh-account Force re-resolution and update the stored accountId
55
+ --refresh-account Force re-resolution and bypass the fills cache (re-query the range)
56
+ --html Write a self-contained HTML report instead of terminal tables
57
+ --report <file> Override the auto-named HTML report path (implies --html)
44
58
  --csv <file> Export trade list as CSV
45
59
  --json <file> Export full analysis as JSON
46
- --trades Show per-order PnL detail (hidden by default)
60
+ --trades Show per-order PnL detail (terminal mode only)
47
61
  --match-mode <mode> Matching mode: sequential (default, LIFO) or fifo
48
62
  --fee-per-order <bts> Blockchain fee per limit_order_create op in BTS (default: 0.09652)
49
63
  --verbose Print extra debug info
50
64
  --help, -h Show this help
51
65
 
52
66
  Examples:
67
+ dexbot pnl my-bot --month 3
68
+ dexbot pnl 1.2.123456 --month 6 --pair TOKENA/BTS
53
69
  node dist/analysis/trade_profitability.js 1.2.123456 --hours 720
54
70
  node dist/analysis/trade_profitability.js 1.2.123456 --start 2025-01-01 --end 2025-06-01
55
- node dist/analysis/trade_profitability.js "my-bot-account" --hours 168
56
- node dist/analysis/trade_profitability.js 1.2.123456 --hours 720 --asset 1.3.113 --csv trades.csv
57
- node dist/analysis/trade_profitability.js 1.2.123456 --hours 720 --match-mode sequential`);
71
+ node dist/analysis/trade_profitability.js 1.2.123456 --hours 720 --asset 1.3.113 --csv trades.csv`);
58
72
  }
59
- function parseArgs() {
60
- const args = process.argv.slice(2);
61
- if (args.length === 0 || args[0] === '--help' || args[0] === '-h') {
73
+ function parseArgs(argv = process.argv.slice(2)) {
74
+ if (argv.length === 0 || argv[0] === '--help' || argv[0] === '-h') {
62
75
  printHelp();
63
76
  process.exit(0);
64
77
  }
65
78
  const opts = {
66
- accountId: args[0],
79
+ accountId: argv[0],
67
80
  hours: null,
81
+ months: null,
68
82
  start: null,
69
83
  end: null,
70
84
  asset: null,
85
+ pair: null,
71
86
  refreshAccount: false,
72
87
  csv: null,
73
88
  json: null,
@@ -75,55 +90,113 @@ function parseArgs() {
75
90
  showPnlDetail: false,
76
91
  verbose: false,
77
92
  feePerOrder: null,
93
+ html: false,
94
+ report: null,
78
95
  };
79
- for (let i = 1; i < args.length; i++) {
80
- switch (args[i]) {
96
+ // Reject a missing flag value explicitly (e.g. `--pair` at end of argv)
97
+ // instead of silently letting `undefined` disable the option.
98
+ const requireValue = (name, raw) => {
99
+ const v = raw == null ? '' : String(raw);
100
+ if (!v || v.startsWith('--'))
101
+ throw new Error(`${name}: missing value`);
102
+ return v;
103
+ };
104
+ const setMonths = (raw) => {
105
+ const n = Number(raw);
106
+ if (!Number.isFinite(n) || n <= 0)
107
+ throw new Error(`--month: invalid value "${raw}" (expected positive months, e.g. --month 6)`);
108
+ opts.months = n;
109
+ };
110
+ const setHours = (raw) => {
111
+ const n = Number(raw);
112
+ if (!Number.isFinite(n) || n <= 0)
113
+ throw new Error(`--hours: invalid value "${raw}" (expected positive hours)`);
114
+ opts.hours = n;
115
+ };
116
+ for (let i = 1; i < argv.length; i++) {
117
+ const arg = argv[i];
118
+ switch (arg) {
81
119
  case '--hours':
82
- opts.hours = parseInt(args[++i], 10);
120
+ setHours(requireValue('--hours', argv[++i]));
121
+ break;
122
+ case '--month':
123
+ case '--months':
124
+ setMonths(requireValue('--month', argv[++i]));
83
125
  break;
84
126
  case '--start':
85
- opts.start = args[++i];
127
+ opts.start = requireValue('--start', argv[++i]);
86
128
  break;
87
129
  case '--end':
88
- opts.end = args[++i];
130
+ opts.end = requireValue('--end', argv[++i]);
89
131
  break;
90
132
  case '--asset':
91
- opts.asset = args[++i];
133
+ opts.asset = requireValue('--asset', argv[++i]);
134
+ break;
135
+ case '--pair':
136
+ opts.pair = requireValue('--pair', argv[++i]);
92
137
  break;
93
138
  case '--refresh-account':
94
139
  opts.refreshAccount = true;
95
140
  break;
96
141
  case '--csv':
97
- opts.csv = args[++i];
142
+ opts.csv = requireValue('--csv', argv[++i]);
98
143
  break;
99
144
  case '--json':
100
- opts.json = args[++i];
145
+ opts.json = requireValue('--json', argv[++i]);
101
146
  break;
102
147
  case '--trades':
103
148
  opts.showPnlDetail = true;
104
149
  break;
150
+ case '--html':
151
+ opts.html = true;
152
+ break;
153
+ case '--report':
154
+ opts.report = requireValue('--report', argv[++i]);
155
+ opts.html = true;
156
+ break;
105
157
  case '--fee-per-order':
106
- opts.feePerOrder = parseFloat(args[++i]);
158
+ opts.feePerOrder = parseFloat(requireValue('--fee-per-order', argv[++i]));
107
159
  break;
108
160
  case '--match-mode': {
109
- const m = args[++i];
110
- if (m !== 'sequential' && m !== 'fifo') {
111
- console.error(`Invalid --match-mode: ${m} (expected: sequential | fifo)`);
112
- process.exit(1);
113
- }
161
+ const m = requireValue('--match-mode', argv[++i]);
162
+ if (m !== 'sequential' && m !== 'fifo')
163
+ throw new Error(`Invalid --match-mode: ${m} (expected: sequential | fifo)`);
114
164
  opts.matchMode = m;
115
165
  break;
116
166
  }
117
167
  case '--verbose':
118
168
  opts.verbose = true;
119
169
  break;
120
- default:
121
- console.error(`Unknown option: ${args[i]}`);
122
- process.exit(1);
170
+ default: {
171
+ // `--flag=value` spellings, same validation as the space form.
172
+ const eq = /^--(month|months|hours|start|end|asset|pair|csv|json|report)=(.*)$/.exec(arg);
173
+ if (eq) {
174
+ const [, name, rawValue] = eq;
175
+ if (name === 'month' || name === 'months')
176
+ setMonths(rawValue);
177
+ else if (name === 'hours')
178
+ setHours(rawValue);
179
+ else if (name === 'report') {
180
+ opts.report = requireValue('--report', rawValue);
181
+ opts.html = true;
182
+ }
183
+ else
184
+ opts[name] = requireValue(`--${name}`, rawValue);
185
+ break;
186
+ }
187
+ throw new Error(`Unknown option: ${arg}`);
188
+ }
123
189
  }
124
190
  }
125
- if (!opts.hours && !opts.start) {
126
- opts.hours = 168; // default: 7 days
191
+ if (!opts.hours && !opts.start && opts.months == null) {
192
+ opts.months = 3; // default: 3 months
193
+ }
194
+ if (opts.pair) {
195
+ const parts = String(opts.pair).split('/');
196
+ if (parts.length !== 2 || !parts[0].trim() || !parts[1].trim()) {
197
+ throw new Error(`--pair: expected BASE/QUOTE (e.g. --pair TOKENA/BTS), got "${opts.pair}"`);
198
+ }
199
+ opts.pair = { base: parts[0].trim(), quote: parts[1].trim() };
127
200
  }
128
201
  return opts;
129
202
  }
@@ -137,7 +210,14 @@ function isValidFillAmounts(baseAmount, quoteAmount) {
137
210
  return Number.isFinite(baseAmount) && Number.isFinite(quoteAmount)
138
211
  && baseAmount > 0 && quoteAmount > 0;
139
212
  }
140
- function classifyFills(fills, filterAsset) {
213
+ /** Match a user-supplied pair leg against a chain asset id or its symbol. */
214
+ function matchesAssetRef(ref, assetId) {
215
+ const want = String(ref).trim().toUpperCase();
216
+ if (!want)
217
+ return false;
218
+ return assetId.toUpperCase() === want || assetSymbol(assetId).toUpperCase() === want;
219
+ }
220
+ function classifyFills(fills, filterAsset, pairFilter = null) {
141
221
  const trades = [];
142
222
  const pairs = new Set();
143
223
  let skipped = 0;
@@ -211,6 +291,8 @@ function classifyFills(fills, filterAsset) {
211
291
  }
212
292
  if (filterAsset && baseAsset !== filterAsset)
213
293
  continue;
294
+ if (pairFilter && !(matchesAssetRef(pairFilter.base, baseAsset) && matchesAssetRef(pairFilter.quote, quoteAsset)))
295
+ continue;
214
296
  // Validate market fee asset: fee is always deducted from receives
215
297
  // (base for buys, quote for sells). Warn if unexpected.
216
298
  if (marketFeeReal > 0 && marketFeeAsset !== '' && marketFeeAsset !== rAsset) {
@@ -393,10 +475,10 @@ function analyzePair(trades, matchMode = 'sequential') {
393
475
  };
394
476
  }
395
477
  // ─── Output Helpers ──────────────────────────────────────────────────────────
396
- function fmt(n, decimals = 4) {
397
- if (!Number.isFinite(n))
398
- return 'NaN';
399
- return n.toLocaleString('en-US', { minimumFractionDigits: decimals, maximumFractionDigits: decimals });
478
+ function fmt(n, _decimals = 4) {
479
+ // Shared 4-significant-figure formatter (see modules/order/format.ts) so
480
+ // terminal output matches the HTML report and `dexbot order`.
481
+ return Number.isFinite(n) ? formatFundsValue(n) : 'NaN';
400
482
  }
401
483
  function fmtPct(n) {
402
484
  if (!Number.isFinite(n))
@@ -417,8 +499,8 @@ function printSummary(pairs, _accountId, _start, _end, _matchMode = 'sequential'
417
499
  console.log(` ── ${pairLabel}`);
418
500
  console.log(` Buys: ${fmt(totalBought, 4)} @ ${fmt(avgBuy, 6)} = ${fmt(pair.totalBuyQuote, 4)} ${fmtAsset(pair.quoteAsset)}`);
419
501
  console.log(` Sells: ${fmt(totalSold, 4)} @ ${fmt(avgSell, 6)} = ${fmt(pair.totalSellQuote, 4)} ${fmtAsset(pair.quoteAsset)}`);
420
- console.log(` Net traded: ${fmt(pair.netPosition, 4)} ${fmtAsset(pair.baseAsset)} (window flow)`);
421
- console.log(` Trades: ${pair.realizedPnls.length} matched lots, ${pair.buys.length} buys, ${pair.sells.length} sells`);
502
+ console.log(` Net inventory \u0394: ${fmt(pair.netPosition, 4)} ${fmtAsset(pair.baseAsset)} (bought \u2212 sold in window)`);
503
+ console.log(` Trades: ${pair.realizedPnls.length} realized lots, ${pair.buys.length} buys, ${pair.sells.length} sells`);
422
504
  if (pair.unmatchedSellBase > 0.0001) {
423
505
  console.log(` Unmatched: ${fmt(pair.unmatchedSellBase, 4)} ${fmtAsset(pair.baseAsset)} (sold without prior buy in window — expected if inventory predates window)`);
424
506
  }
@@ -472,7 +554,7 @@ function printSummary(pairs, _accountId, _start, _end, _matchMode = 'sequential'
472
554
  console.log(` fees are converted to quote asset. Buy lots are entered at net`);
473
555
  console.log(` receives (gross minus buy-side market fee) so inventory matching`);
474
556
  console.log(` reflects what the account actually held. If inventory predates the`);
475
- console.log(` window or crosses asset pairs, the matched lots may not reflect`);
557
+ console.log(` window or crosses asset pairs, the realized lots may not reflect`);
476
558
  console.log(` true trade economics.`);
477
559
  console.log('');
478
560
  }
@@ -539,6 +621,7 @@ function computeMetrics(pair, window) {
539
621
  bestTradePct: 0, worstTradePct: 0,
540
622
  mddPct: 0,
541
623
  mddAbsBts: 0,
624
+ prePeakMinEquity: 0,
542
625
  mddHadStablePeak: false,
543
626
  isOngoingRecovery: false,
544
627
  currentDrawdownDays: 0,
@@ -793,10 +876,12 @@ function computeMetrics(pair, window) {
793
876
  }
794
877
  if (hadStablePeak) {
795
878
  mddPct *= 100;
879
+ prePeakMinEquity = 0;
796
880
  }
797
881
  else {
798
- mddPct = hasPrePeakEquity ? prePeakMinEquity : 0;
882
+ mddPct = 0;
799
883
  mddAbsBts = 0;
884
+ prePeakMinEquity = hasPrePeakEquity ? prePeakMinEquity : 0;
800
885
  }
801
886
  // Payoff distribution stats
802
887
  const pnlPcts = [...pnls.map(r => r.pnlPct)].sort((a, b) => a - b);
@@ -844,6 +929,7 @@ function computeMetrics(pair, window) {
844
929
  worstTradePct,
845
930
  mddPct,
846
931
  mddAbsBts,
932
+ prePeakMinEquity,
847
933
  mddHadStablePeak: hadStablePeak,
848
934
  isOngoingRecovery,
849
935
  currentDrawdownDays,
@@ -916,7 +1002,7 @@ function printMetrics(pairs, window) {
916
1002
  console.log(` Max Drawdown: ${fmt(m.mddAbsBts, 4)} ${qSymbol} (${fmtPct(m.mddPct)} of peak cumulative profit)`);
917
1003
  }
918
1004
  else {
919
- console.log(` Min Equity: ${fmt(m.mddPct, 4)} ${fmtAsset(pair.quoteAsset)}`);
1005
+ console.log(` Min Equity: ${fmt(m.prePeakMinEquity, 4)} ${fmtAsset(pair.quoteAsset)}`);
920
1006
  }
921
1007
  const recLabel = m.maxRecoveryDays > 0 ? m.maxRecoveryDays.toFixed(1) + ' days' + (m.isOngoingRecovery ? ' (ongoing)' : '') : '—';
922
1008
  console.log(` Max Recovery Time: ${recLabel}`);
@@ -1044,21 +1130,37 @@ function normalizeTimeBound(raw, isEnd) {
1044
1130
  }
1045
1131
  return new Date(ms).toISOString();
1046
1132
  }
1047
- async function run() {
1048
- const opts = parseArgs();
1133
+ /** Auto-named report file: bot/account + pair filter + requested range. */
1134
+ function reportFileName(opts, accountRef, botName) {
1135
+ const slugBase = botName ? sanitizeKey(botName) : sanitizeKey(accountRef);
1136
+ const pairSlug = opts.pair ? `_${sanitizeKey(opts.pair.base)}-${sanitizeKey(opts.pair.quote)}` : '';
1137
+ let rangeSlug;
1138
+ if (opts.months != null)
1139
+ rangeSlug = `_${String(opts.months).replace('.', 'p')}m`;
1140
+ else if (opts.start)
1141
+ rangeSlug = `_${String(opts.start).slice(0, 10)}${opts.end ? '_' + String(opts.end).slice(0, 10) : ''}`;
1142
+ else
1143
+ rangeSlug = `_${opts.hours || 168}h`;
1144
+ return `pnl_${slugBase}${pairSlug}${rangeSlug}.html`;
1145
+ }
1146
+ async function run(argv = process.argv.slice(2)) {
1147
+ muteChainLogs();
1148
+ const opts = parseArgs(argv);
1049
1149
  let accountId = opts.accountId;
1150
+ let resolvedBotName = null;
1050
1151
  if (!/^1\.2\.\d+$/.test(String(accountId))) {
1051
1152
  // The Kibana query below filters on the 1.2.x account_id field, so a
1052
1153
  // name must always resolve first (a raw name would silently return
1053
- // zero fills). Shared resolver: reuses a stored accountId from
1054
- // profiles/bots.json when one matches the name and stamps the result
1055
- // back onto the bot entry on a fresh lookup.
1154
+ // zero fills). Shared resolver: a local bot profile is checked first
1155
+ // (no chain call), then a stored accountId, then a fresh lookup; the
1156
+ // result is stamped back onto the bot entry.
1056
1157
  const resolved = await resolveAccountRef(accountId, { refresh: opts.refreshAccount });
1057
1158
  if (!resolved.accountId) {
1058
1159
  console.error(` Could not resolve "${accountId}" to an account ID`);
1059
1160
  process.exit(1);
1060
1161
  }
1061
1162
  accountId = resolved.accountId;
1163
+ resolvedBotName = resolved.botMeta?.name ?? null;
1062
1164
  }
1063
1165
  // Build time range
1064
1166
  const now = new Date();
@@ -1072,13 +1174,15 @@ async function run() {
1072
1174
  lte = now.toISOString();
1073
1175
  }
1074
1176
  else {
1075
- const hours = opts.hours || 168;
1177
+ const hours = opts.months != null ? monthsToHours(opts.months) : (opts.hours || 168);
1076
1178
  const start = new Date(now.getTime() - hours * 3600 * 1000);
1077
1179
  gte = start.toISOString();
1078
1180
  lte = now.toISOString();
1079
1181
  }
1080
1182
  const KIBANA_CFG = { timeout: 60000 };
1081
- const fills = await fetchAllFills(KIBANA_CFG, accountId, gte, lte);
1183
+ // Month-shard cache keyed by the resolved accountId; --refresh-account
1184
+ // bypasses coverage trust and re-queries the requested range.
1185
+ const fills = await fetchFillsCached(KIBANA_CFG, accountId, gte, lte, { refresh: opts.refreshAccount });
1082
1186
  if (fills.length === 0) {
1083
1187
  console.log(' No fills found in the specified time range.');
1084
1188
  process.exit(0);
@@ -1086,12 +1190,12 @@ async function run() {
1086
1190
  // Resolve unknown asset precisions from blockchain
1087
1191
  await resolveAssetPrecisions(fills);
1088
1192
  // Classify fills
1089
- const { trades, pairs } = classifyFills(fills, opts.asset);
1193
+ const { trades, pairs } = classifyFills(fills, opts.asset, opts.pair);
1090
1194
  if (trades.length === 0) {
1091
- console.log(' No trades could be classified (check asset filter or time range).');
1195
+ console.log(' No trades could be classified (check pair/asset filter or time range).');
1092
1196
  process.exit(0);
1093
1197
  }
1094
- console.log(`Account: ${accountId}`);
1198
+ console.log(`Account: ${accountId}${resolvedBotName ? ` (bot: ${resolvedBotName})` : ''}`);
1095
1199
  console.log(`Period: ${gte.slice(0, 10)} → ${lte.slice(0, 10)}`);
1096
1200
  console.log(`Pairs: ${pairs.size}, ${trades.length} classified trades`);
1097
1201
  const hasCrossPair = [...pairs].some(p => p.split(':')[1] !== BTS_ID);
@@ -1122,17 +1226,39 @@ async function run() {
1122
1226
  analyses.push(analysis);
1123
1227
  if (opts.verbose) {
1124
1228
  const [base, quote] = key.split(':');
1125
- console.log(` ${fmtAsset(base)}/${fmtAsset(quote)}: ${pairTrades.filter(t => t.direction === 'buy').length} buys, ${pairTrades.filter(t => t.direction === 'sell').length} sells, ${analysis.realizedPnls.length} matched lots`);
1229
+ console.log(` ${fmtAsset(base)}/${fmtAsset(quote)}: ${pairTrades.filter(t => t.direction === 'buy').length} buys, ${pairTrades.filter(t => t.direction === 'sell').length} sells, ${analysis.realizedPnls.length} realized lots`);
1126
1230
  }
1127
1231
  }
1128
1232
  // Sort pairs by volume (total quote)
1129
1233
  analyses.sort((a, b) => (b.totalBuyQuote + b.totalSellQuote) - (a.totalBuyQuote + a.totalSellQuote));
1130
- // Output: summaries → grand total → per-match detail
1131
- printSummary(analyses, accountId, gte, lte, opts.matchMode);
1132
- if (opts.showPnlDetail) {
1133
- printPnlDetail(analyses);
1234
+ const reportWindow = { startMs: Date.parse(gte), endMs: Date.parse(lte) };
1235
+ if (opts.html) {
1236
+ // HTML is the primary output of `dexbot pnl`: write the self-contained
1237
+ // report and print the file link, skipping the terminal tables.
1238
+ const reportPath = opts.report
1239
+ ? path.resolve(String(opts.report))
1240
+ : path.join(PATHS.ANALYSIS.CHARTS_DIR, reportFileName(opts, String(opts.accountId), resolvedBotName));
1241
+ writePnlReport({
1242
+ accountRef: String(opts.accountId),
1243
+ accountId,
1244
+ botName: resolvedBotName,
1245
+ start: gte,
1246
+ end: lte,
1247
+ matchMode: opts.matchMode,
1248
+ pairFilter: opts.pair ? `${opts.pair.base}/${opts.pair.quote}` : null,
1249
+ assetFilter: opts.asset,
1250
+ pairs: analyses.map(pair => ({ pair, metrics: computeMetrics(pair, reportWindow) })),
1251
+ }, reportPath);
1252
+ console.log(`\n📄 PnL report saved. Open report: (${toFileUrl(reportPath)})`);
1253
+ }
1254
+ else {
1255
+ // Output: summaries → grand total → per-match detail
1256
+ printSummary(analyses, accountId, gte, lte, opts.matchMode);
1257
+ if (opts.showPnlDetail) {
1258
+ printPnlDetail(analyses);
1259
+ }
1260
+ printMetrics(analyses, reportWindow);
1134
1261
  }
1135
- printMetrics(analyses, { startMs: Date.parse(gte), endMs: Date.parse(lte) });
1136
1262
  if (opts.csv) {
1137
1263
  exportCsv(analyses, opts.csv);
1138
1264
  }
@@ -1140,7 +1266,7 @@ async function run() {
1140
1266
  exportJson(accountId, gte, lte, analyses, opts.json);
1141
1267
  }
1142
1268
  }
1143
- export { analyzePair, classifyFills, computeMetrics };
1269
+ export { analyzePair, classifyFills, computeMetrics, parseArgs, run, reportFileName };
1144
1270
  if (import.meta.url === pathToFileURL(process.argv[1]).href) {
1145
1271
  run().then(() => process.exit(0)).catch(e => {
1146
1272
  console.error('\n[fatal]', e.message);
@@ -286,11 +286,9 @@ async function main() {
286
286
  },
287
287
  smaPeriod: config.smaPeriod,
288
288
  amaDefaults: {
289
- // Intentionally the 3-param AMA (er/fast/slow) only: the in-page
290
- // recomputation has no erSmoothPeriod input by decision — `dexbot tv`
291
- // stays a plain candle chart. The dw research chart and the live
292
- // adapter are the mirrors of the full bot AMA config (incl.
293
- // ama.erSmoothPeriod); the knob is inert by default (global 0).
289
+ // Canonical 3-param AMA (er/fast/slow). The in-page AMA
290
+ // recomputation mirrors the live adapter exactly; `dexbot tv`
291
+ // stays a plain candle chart.
294
292
  erPeriod: config.amaErPeriod ?? amaConfig.erPeriod,
295
293
  fastPeriod: config.amaFastPeriod ?? amaConfig.fastPeriod,
296
294
  slowPeriod: config.amaSlowPeriod ?? amaConfig.slowPeriod,
@@ -15,6 +15,7 @@ declare function resolveGridResetSimConfig({ botKey, bot, ama, overrides }?: any
15
15
  slopeEnabled: boolean;
16
16
  dynamicWeightEnabled: boolean;
17
17
  lookbackBars: any;
18
+ slopePersistBars: number;
18
19
  maxSlopePct: any;
19
20
  neutralZonePct: number;
20
21
  maxSlopeOffset: any;
@@ -43,6 +44,7 @@ declare function toGridSimPayload(cfg: any): {
43
44
  slopeEnabled: boolean;
44
45
  dynamicWeightEnabled: boolean;
45
46
  lookbackBars: any;
47
+ slopePersistBars: any;
46
48
  maxSlopePct: any;
47
49
  neutralZonePct: any;
48
50
  maxSlopeOffset: any;
@@ -143,9 +143,24 @@ function resolveGridResetSimConfig({ botKey, bot, ama, overrides } = {}) {
143
143
  }
144
144
  const erPeriod = firstPositive([ama?.erPeriod, botCfg?.erPeriod], MARKET_ADAPTER.AMAS.AMA3.erPeriod);
145
145
  const lookbackBars = firstPositive([botCfg?.amaSlope?.lookbackBars], MARKET_ADAPTER.DYNAMIC_WEIGHT_AMA_LOOKBACK_BARS);
146
+ // Slope-delta persistence gate: mirror resolveAmaSlopePersistBars in the
147
+ // adapter service so the chart replay fires the same Δs resets production
148
+ // does. Per-bot override wins; else the global enable + value; else legacy 1.
149
+ const resolveSlopePersistBars = () => {
150
+ const explicit = Number(botCfg?.amaSlope?.persistBars ?? botCfg?.amaSlopePersistBars);
151
+ if (Number.isFinite(explicit) && explicit >= 1)
152
+ return Math.round(explicit);
153
+ const enabled = botCfg?.amaSlope?.persistEnabled === true
154
+ || botCfg?.amaSlopePersistEnabled === true
155
+ || MARKET_ADAPTER.AMA_SLOPE_PERSIST_ENABLED === true;
156
+ if (!enabled)
157
+ return 1;
158
+ const bars = Number(MARKET_ADAPTER.AMA_SLOPE_PERSIST_BARS);
159
+ return Number.isFinite(bars) && bars >= 1 ? Math.round(bars) : 1;
160
+ };
146
161
  let warmupBars = 0;
147
162
  try {
148
- warmupBars = getAmaWarmupBars(erPeriod, firstPositive([ama?.slowPeriod], MARKET_ADAPTER.AMAS.AMA3.slowPeriod), lookbackBars, firstPositive([ama?.fastPeriod], MARKET_ADAPTER.AMAS.AMA3.fastPeriod), Number(ama?.erSmoothPeriod) > 0 ? Number(ama.erSmoothPeriod) : 0);
163
+ warmupBars = getAmaWarmupBars(erPeriod, firstPositive([ama?.slowPeriod], MARKET_ADAPTER.AMAS.AMA3.slowPeriod), lookbackBars, firstPositive([ama?.fastPeriod], MARKET_ADAPTER.AMAS.AMA3.fastPeriod));
149
164
  }
150
165
  catch (_err) {
151
166
  // getAmaWarmupBars validates strictly; a research-only AMA tweak must
@@ -180,6 +195,7 @@ function resolveGridResetSimConfig({ botKey, bot, ama, overrides } = {}) {
180
195
  slopeEnabled,
181
196
  dynamicWeightEnabled,
182
197
  lookbackBars,
198
+ slopePersistBars: resolveSlopePersistBars(),
183
199
  maxSlopePct: firstPositive([botCfg?.amaSlope?.maxSlopePct], MARKET_ADAPTER.DYNAMIC_WEIGHT_AMA_MAX_SLOPE_PCT),
184
200
  neutralZonePct: Number.isFinite(Number(botCfg?.amaSlope?.neutralZonePct))
185
201
  ? Number(botCfg.amaSlope.neutralZonePct)
@@ -216,6 +232,7 @@ function toGridSimPayload(cfg) {
216
232
  slopeEnabled: cfg.slopeEnabled === true,
217
233
  dynamicWeightEnabled: cfg.dynamicWeightEnabled === true,
218
234
  lookbackBars: cfg.lookbackBars,
235
+ slopePersistBars: cfg.slopePersistBars,
219
236
  maxSlopePct: cfg.maxSlopePct,
220
237
  neutralZonePct: cfg.neutralZonePct,
221
238
  maxSlopeOffset: cfg.maxSlopeOffset,
@@ -70,6 +70,7 @@ declare function simulateGridResetSeries(amaSeries: any, cfg: any): {
70
70
  warmupBars: any;
71
71
  priceDeltaThresholdPercent: number | null;
72
72
  slopeDeltaThresholdPercent: number | null;
73
+ slopePersistBars: any;
73
74
  slopeTriggerArmed: boolean;
74
75
  };
75
76
  };
@@ -135,6 +135,10 @@ function simulateGridResetSeries(amaSeries, cfg) {
135
135
  const clipPercentile = Number(cfg?.clipPercentile);
136
136
  const clampMinValue = Number(cfg?.clampMin);
137
137
  const clampMaxValue = Number(cfg?.clampMax);
138
+ // Persistence gate on the slope-delta trigger (trigger B): consecutive
139
+ // confirming bars required before it fires. 1 = legacy behavior (fire on the
140
+ // first threshold crossing); >1 filters short-lived slope excursions.
141
+ const slopePersistBars = gridSimNonNegativeInt(cfg?.slopePersistBars, 1);
138
142
  // Mirrors clampGridPriceToBounds: only absolute bot bounds pin the center,
139
143
  // and each side binds independently (a mixed absolute/"Nx" config clamps
140
144
  // only on the absolute side).
@@ -174,6 +178,7 @@ function simulateGridResetSeries(amaSeries, cfg) {
174
178
  warmupBars,
175
179
  priceDeltaThresholdPercent: priceTriggerArmed ? priceThreshold : null,
176
180
  slopeDeltaThresholdPercent: slopeTriggerArmed ? slopeThreshold : null,
181
+ slopePersistBars,
177
182
  slopeTriggerArmed,
178
183
  },
179
184
  };
@@ -189,6 +194,9 @@ function simulateGridResetSeries(amaSeries, cfg) {
189
194
  let resetCount = 0;
190
195
  let priceResets = 0;
191
196
  let slopeResets = 0;
197
+ // Persistence-gate state for trigger B.
198
+ let slopePersistCount = 0;
199
+ let slopePersistDir = 0;
192
200
  for (let i = 0; i < n; i++) {
193
201
  const ama = Number(amaSeries[i]);
194
202
  const hasAma = Number.isFinite(ama) && ama > 0;
@@ -245,10 +253,37 @@ function simulateGridResetSeries(amaSeries, cfg) {
245
253
  else if (priceTriggerArmed && driftPct[i] >= priceThreshold) {
246
254
  fired = GRID_RESET_PRICE;
247
255
  }
248
- else if (slopeTriggerArmed && slopeDeltaPct[i] != null && slopeDeltaPct[i] >= slopeThreshold) {
249
- fired = GRID_RESET_SLOPE;
256
+ else {
257
+ // Trigger B, now persistence-gated: require the threshold to be
258
+ // crossed for `slopePersistBars` consecutive bars in the same
259
+ // direction before firing. A single-bar excursion never charges the
260
+ // counter; a sustained move is confirmed K bars after onset (up to
261
+ // K-1 bars later than the ungated trigger).
262
+ const delta = slopeDeltaPct[i];
263
+ const candidate = slopeTriggerArmed && delta != null && delta >= slopeThreshold;
264
+ if (!candidate) {
265
+ slopePersistCount = 0;
266
+ slopePersistDir = 0;
267
+ }
268
+ else {
269
+ const dir = acceptedSlope != null && slopePct != null ? Math.sign(slopePct - acceptedSlope) : 0;
270
+ if (slopePersistBars <= 1) {
271
+ fired = GRID_RESET_SLOPE;
272
+ }
273
+ else if (dir !== 0 && dir === slopePersistDir) {
274
+ slopePersistCount++;
275
+ if (slopePersistCount >= slopePersistBars)
276
+ fired = GRID_RESET_SLOPE;
277
+ }
278
+ else {
279
+ slopePersistDir = dir;
280
+ slopePersistCount = 1;
281
+ }
282
+ }
250
283
  }
251
284
  if (fired !== GRID_RESET_NONE) {
285
+ slopePersistCount = 0;
286
+ slopePersistDir = 0;
252
287
  const previousCenter = acceptedCenter;
253
288
  acceptedCenter = currentCenter;
254
289
  // Re-seed the accepted slope on EVERY reset (price and slope alike),
@@ -312,6 +347,7 @@ function simulateGridResetSeries(amaSeries, cfg) {
312
347
  warmupBars,
313
348
  priceDeltaThresholdPercent: priceTriggerArmed ? priceThreshold : null,
314
349
  slopeDeltaThresholdPercent: slopeTriggerArmed ? slopeThreshold : null,
350
+ slopePersistBars,
315
351
  slopeTriggerArmed,
316
352
  },
317
353
  };