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
@@ -0,0 +1,254 @@
1
+ 'use strict';
2
+ /**
3
+ * FILLS CACHE — persistent calendar-month shard cache for per-account
4
+ * `fill_order` fetches (`analysis/fills_source.ts`).
5
+ *
6
+ * `dexbot pnl` re-queries Kibana on every run; this layer lets a settled month
7
+ * be answered from disk. It mirrors the design principles of the candle cache
8
+ * (`market_adapter/inputs/window_cache.ts`) but is intentionally fills-specific:
9
+ * fills are sparse point events, so reuse is driven purely by recorded query
10
+ * COVERAGE (a month queried and found empty is still covered), not by a
11
+ * bucket-by-bucket presence grid.
12
+ *
13
+ * Storage: `<cacheDir>/fills/<accountId>.shard_YYYY-MM.json`, one file per UTC
14
+ * calendar month, holding `{ meta: { accountId, fetchedAt, queriedRanges },
15
+ * fills }`. `queriedRanges` records the spans actually queried together with
16
+ * `at` (when the query ran).
17
+ *
18
+ * Reuse rule: a recorded span is trusted only up to `at - TAIL_SETTLE_LAG_MS`,
19
+ * because Kibana indexes fills with a lag — a query cannot certify the last
20
+ * few hours before it ran. The unsettled tail is therefore re-queried on the
21
+ * next run (incremental refresh), while older settled spans are reused with
22
+ * zero queries and zero writes. `refresh` (from `--refresh-account`) ignores
23
+ * coverage and re-queries the whole requested range, but still merges what it
24
+ * gets back so a fresh query can never drop fills outside the requested span.
25
+ */
26
+ import path from 'node:path';
27
+ import { getStorage } from '../modules/storage/index.js';
28
+ import { PATHS } from '../modules/paths.js';
29
+ import { writeJsonAtomic } from '../market_adapter/utils/atomic_write.js';
30
+ import { fetchAllFills } from './fills_source.js';
31
+ const storage = getStorage();
32
+ const { readJSON } = storage;
33
+ /** How long after a query its trailing fills may still be late-indexed. */
34
+ const TAIL_SETTLE_LAG_MS = 6 * 3600 * 1000;
35
+ /** Upper bound on spans persisted per shard (keeps coverage bookkeeping small). */
36
+ const MAX_COVERAGE_SPANS = 64;
37
+ const SHARD_EXT = '.json';
38
+ const SHARD_MARKER = '.shard_';
39
+ function shardKeyForTimestamp(tsMs) {
40
+ const d = new Date(Number(tsMs));
41
+ return `${d.getUTCFullYear()}-${String(d.getUTCMonth() + 1).padStart(2, '0')}`;
42
+ }
43
+ function shardBoundsForKey(key) {
44
+ const parts = String(key).split('-').map(Number);
45
+ const start = Date.UTC(parts[0], parts[1] - 1, 1);
46
+ const end = parts[1] === 12 ? Date.UTC(parts[0] + 1, 0, 1) : Date.UTC(parts[0], parts[1], 1);
47
+ return { start, end };
48
+ }
49
+ function shardKeysForRange(gteMs, lteMs) {
50
+ const keys = [];
51
+ const cursor = new Date(Date.UTC(new Date(gteMs).getUTCFullYear(), new Date(gteMs).getUTCMonth(), 1));
52
+ const last = new Date(lteMs);
53
+ while (cursor <= last) {
54
+ keys.push(shardKeyForTimestamp(cursor.getTime()));
55
+ cursor.setUTCMonth(cursor.getUTCMonth() + 1);
56
+ }
57
+ return keys;
58
+ }
59
+ function accountFileBase(accountId) {
60
+ const s = String(accountId ?? '').trim();
61
+ if (/^1\.2\.\d+$/.test(s))
62
+ return s;
63
+ return s.replace(/[^a-zA-Z0-9._-]+/g, '-').replace(/^-+|-+$/g, '') || 'account';
64
+ }
65
+ function basePathFor(cacheDir, accountId) {
66
+ return path.join(cacheDir, 'fills', `${accountFileBase(accountId)}${SHARD_EXT}`);
67
+ }
68
+ function shardPathFor(basePath, shardKey) {
69
+ const parsed = path.parse(basePath);
70
+ return path.join(parsed.dir, `${parsed.name}${SHARD_MARKER}${shardKey}${parsed.ext}`);
71
+ }
72
+ function readShard(shardFile, accountId) {
73
+ try {
74
+ const parsed = readJSON(shardFile);
75
+ if (!parsed || parsed.meta?.accountId !== accountId)
76
+ return null;
77
+ if (!Array.isArray(parsed.fills))
78
+ return null;
79
+ return {
80
+ meta: {
81
+ accountId,
82
+ fetchedAt: String(parsed.meta?.fetchedAt || ''),
83
+ queriedRanges: Array.isArray(parsed.meta?.queriedRanges) ? parsed.meta.queriedRanges : [],
84
+ },
85
+ fills: parsed.fills,
86
+ };
87
+ }
88
+ catch (_) {
89
+ return null;
90
+ }
91
+ }
92
+ /** Sort, merge overlapping/adjacent same-`at` spans, cap the list length. */
93
+ function normalizeQueried(ranges) {
94
+ const clean = (ranges || [])
95
+ .filter((q) => q && Number.isFinite(Number(q.gte)) && Number.isFinite(Number(q.lte)) && Number(q.lte) >= Number(q.gte))
96
+ .map((q) => ({
97
+ gte: Number(q.gte),
98
+ lte: Number(q.lte),
99
+ at: Number.isFinite(Number(q.at)) ? Number(q.at) : null,
100
+ }))
101
+ .sort((a, b) => a.gte - b.gte || a.lte - b.lte);
102
+ const merged = [];
103
+ for (const q of clean) {
104
+ const top = merged[merged.length - 1];
105
+ if (top && q.gte <= top.lte + 1 && top.at === q.at) {
106
+ if (q.lte > top.lte)
107
+ top.lte = q.lte;
108
+ }
109
+ else {
110
+ merged.push({ ...q });
111
+ }
112
+ }
113
+ if (merged.length > MAX_COVERAGE_SPANS)
114
+ merged.splice(0, merged.length - MAX_COVERAGE_SPANS);
115
+ return merged;
116
+ }
117
+ /** Record a freshly queried span, dropping older spans it fully supersedes. */
118
+ function addCoverage(queried, span, atMs) {
119
+ const kept = queried.filter((q) => !(q.gte >= span.gte && q.lte <= span.lte));
120
+ return normalizeQueried([...kept, { gte: span.gte, lte: span.lte, at: atMs }]);
121
+ }
122
+ function mergeSpans(spans) {
123
+ const sorted = [...spans].sort((a, b) => a.gte - b.gte || a.lte - b.lte);
124
+ const merged = [];
125
+ for (const s of sorted) {
126
+ const top = merged[merged.length - 1];
127
+ if (top && s.gte <= top.lte + 1) {
128
+ if (s.lte > top.lte)
129
+ top.lte = s.lte;
130
+ }
131
+ else {
132
+ merged.push({ ...s });
133
+ }
134
+ }
135
+ return merged;
136
+ }
137
+ /**
138
+ * Portions of queried spans that are safe to reuse: the part up to
139
+ * `at - TAIL_SETTLE_LAG_MS`. A span with an unknown `at` certifies nothing.
140
+ */
141
+ function trustedSegments(queried, nowMs) {
142
+ const segs = [];
143
+ for (const q of queried) {
144
+ if (q.at == null)
145
+ continue;
146
+ const end = Math.min(q.lte, q.at - TAIL_SETTLE_LAG_MS, nowMs - TAIL_SETTLE_LAG_MS);
147
+ if (end >= q.gte)
148
+ segs.push({ gte: q.gte, lte: end });
149
+ }
150
+ return mergeSpans(segs);
151
+ }
152
+ /** `span` minus the union of `covered` (both as inclusive ms ranges). */
153
+ function subtractRanges(span, covered) {
154
+ let parts = [{ ...span }];
155
+ for (const c of mergeSpans(covered)) {
156
+ const next = [];
157
+ for (const p of parts) {
158
+ if (c.lte < p.gte || c.gte > p.lte) {
159
+ next.push(p);
160
+ continue;
161
+ }
162
+ if (c.gte > p.gte)
163
+ next.push({ gte: p.gte, lte: Math.min(p.lte, c.gte - 1) });
164
+ if (c.lte < p.lte)
165
+ next.push({ gte: Math.max(p.gte, c.lte + 1), lte: p.lte });
166
+ }
167
+ parts = next.filter(p => p.lte >= p.gte);
168
+ if (parts.length === 0)
169
+ break;
170
+ }
171
+ return parts;
172
+ }
173
+ function fillKey(f) {
174
+ return `${f.blockNum}:${f.opNum}`;
175
+ }
176
+ function compareFills(a, b) {
177
+ if (a.time !== b.time)
178
+ return a.time < b.time ? -1 : 1;
179
+ if (a.blockNum !== b.blockNum)
180
+ return a.blockNum - b.blockNum;
181
+ return a.opNum - b.opNum;
182
+ }
183
+ /** Union two fill lists, deduped by the unique operation identity. */
184
+ function mergeFills(existing, incoming) {
185
+ const byKey = new Map();
186
+ for (const f of existing)
187
+ byKey.set(fillKey(f), f);
188
+ for (const f of incoming)
189
+ byKey.set(fillKey(f), f);
190
+ return [...byKey.values()].sort(compareFills);
191
+ }
192
+ /**
193
+ * Fetch every fill_order for an account over [gteIso, lteIso], reusing cached
194
+ * month shards and querying only their missing spans. Falls back to a direct
195
+ * fetch when the range is malformed.
196
+ */
197
+ async function fetchFillsCached(config, accountId, gteIso, lteIso, options = {}) {
198
+ const gteMs = Date.parse(gteIso);
199
+ const lteMs = Date.parse(lteIso);
200
+ const doFetch = options.fetchRange ?? ((gte, lte) => fetchAllFills(config, accountId, gte, lte));
201
+ if (!Number.isFinite(gteMs) || !Number.isFinite(lteMs) || lteMs < gteMs) {
202
+ return doFetch(gteIso, lteIso);
203
+ }
204
+ const nowMs = options.nowMs ?? Date.now();
205
+ const cacheDir = options.cacheDir ?? PATHS.ANALYSIS.CACHE_DIR;
206
+ const basePath = basePathFor(cacheDir, accountId);
207
+ const collected = new Map();
208
+ let fetchedSpans = 0;
209
+ let queriedFills = 0;
210
+ let reusedMonths = 0;
211
+ for (const key of shardKeysForRange(gteMs, lteMs)) {
212
+ const { start, end } = shardBoundsForKey(key);
213
+ const shardGte = Math.max(gteMs, start);
214
+ const shardLte = Math.min(lteMs, end - 1);
215
+ if (shardLte < shardGte)
216
+ continue;
217
+ const shardFile = shardPathFor(basePath, key);
218
+ const shard = readShard(shardFile, accountId);
219
+ const existingQueried = shard ? normalizeQueried(shard.meta.queriedRanges) : [];
220
+ const trusted = options.refresh ? [] : trustedSegments(existingQueried, nowMs);
221
+ const missing = subtractRanges({ gte: shardGte, lte: shardLte }, trusted);
222
+ if (shard && missing.length === 0)
223
+ reusedMonths += 1;
224
+ let fills = shard ? shard.fills : [];
225
+ let queried = existingQueried;
226
+ let changed = false;
227
+ for (const span of missing) {
228
+ const incoming = await doFetch(new Date(span.gte).toISOString(), new Date(span.lte).toISOString());
229
+ queriedFills += incoming.length;
230
+ fetchedSpans += 1;
231
+ fills = mergeFills(fills, incoming);
232
+ queried = addCoverage(queried, span, nowMs);
233
+ changed = true;
234
+ }
235
+ for (const f of fills) {
236
+ const t = Date.parse(f.time);
237
+ if (Number.isFinite(t) && t >= gteMs && t <= lteMs)
238
+ collected.set(fillKey(f), f);
239
+ }
240
+ if (changed) {
241
+ writeJsonAtomic(shardFile, {
242
+ meta: { accountId, fetchedAt: new Date(nowMs).toISOString(), queriedRanges: queried },
243
+ fills,
244
+ });
245
+ }
246
+ }
247
+ if (!options.quiet && fetchedSpans > 0) {
248
+ const reuseNote = reusedMonths > 0 ? `; ${reusedMonths} month(s) reused from cache` : '';
249
+ console.log(` [cache] queried ${fetchedSpans} fill range(s) (${queriedFills} fill(s))${reuseNote}`);
250
+ }
251
+ return [...collected.values()].sort(compareFills);
252
+ }
253
+ export { fetchFillsCached, shardKeyForTimestamp, shardBoundsForKey, shardKeysForRange, basePathFor, shardPathFor, normalizeQueried, addCoverage, trustedSegments, subtractRanges, mergeFills, fillKey, TAIL_SETTLE_LAG_MS, MAX_COVERAGE_SPANS, };
254
+ //# sourceMappingURL=fills_cache.js.map
@@ -60,10 +60,11 @@ const ASSETS = {
60
60
  '1.3.6620': { symbol: 'XBTSX.A', precision: 6 },
61
61
  '1.3.6627': { symbol: 'XBTSX.LINK', precision: 6 },
62
62
  };
63
- /** Precisions learned on-chain this run (populated by resolveAssetPrecisions). */
63
+ /** Precisions/symbols learned on-chain this run (populated by resolveAssetPrecisions). */
64
64
  const resolvedPrecisions = {};
65
+ const resolvedSymbols = {};
65
66
  function assetSymbol(id) {
66
- return ASSETS[id]?.symbol ?? id;
67
+ return ASSETS[id]?.symbol ?? resolvedSymbols[id] ?? id;
67
68
  }
68
69
  function assetPrec(id) {
69
70
  return ASSETS[id]?.precision ?? resolvedPrecisions[id];
@@ -98,6 +99,8 @@ async function resolveAssetPrecisions(fills) {
98
99
  for (const asset of assets) {
99
100
  if (asset?.id && asset.precision != null) {
100
101
  resolvedPrecisions[asset.id] = asset.precision;
102
+ if (asset.symbol)
103
+ resolvedSymbols[asset.id] = String(asset.symbol);
101
104
  console.log(` ${asset.id} → ${asset.symbol || '?'} (precision ${asset.precision})`);
102
105
  }
103
106
  }
@@ -0,0 +1,39 @@
1
+ /**
2
+ * PROFESSIONAL PnL REPORT (HTML)
3
+ *
4
+ * Renders the output of analysis/trade_profitability.ts (PairAnalysis +
5
+ * realized lots + performance metrics) into a single self-contained HTML
6
+ * report: no sibling assets, no CDN, no network — it opens from a file://
7
+ * link on any machine.
8
+ *
9
+ * Centralises the report so every consumer (the `dexbot pnl` command and
10
+ * direct `node dist/analysis/trade_profitability.js --html` runs) emits the
11
+ * exact same layout. The type-only import from trade_profitability is erased
12
+ * at compile time, so there is no runtime import cycle.
13
+ */
14
+ import type { PairAnalysis, TradingMetrics } from './trade_profitability.js';
15
+ interface PnlReportPair {
16
+ pair: PairAnalysis;
17
+ metrics: TradingMetrics;
18
+ }
19
+ interface PnlReportInput {
20
+ /** The reference the user typed (bot name, account name or 1.2.x id). */
21
+ accountRef: string;
22
+ /** Resolved chain account id (1.2.x). */
23
+ accountId: string;
24
+ /** Local bot profile name, when the reference resolved to one. */
25
+ botName?: string | null;
26
+ start: string;
27
+ end: string;
28
+ matchMode: string;
29
+ pairFilter?: string | null;
30
+ assetFilter?: string | null;
31
+ generatedAt?: string;
32
+ pairs: PnlReportPair[];
33
+ }
34
+ declare function renderPnlReportHtml(input: PnlReportInput): string;
35
+ /** Render + atomically write the report; returns the resolved file path. */
36
+ declare function writePnlReport(input: PnlReportInput, outputPath: string): string;
37
+ export { renderPnlReportHtml, writePnlReport };
38
+ export type { PnlReportInput, PnlReportPair };
39
+ //# sourceMappingURL=pnl_report.d.ts.map
@@ -0,0 +1,325 @@
1
+ 'use strict';
2
+ import { escapeHtml, writeChartFile } from './chart_utils.js';
3
+ import { assetSymbol } from './fills_source.js';
4
+ import { formatFundsValue } from '../modules/order/format.js';
5
+ const MAX_DETAIL_ROWS = 2000;
6
+ /**
7
+ * Numbers go through the shared `formatFundsValue` (4 significant figures,
8
+ * K/M compaction, significant trailing zeros kept) so the report matches
9
+ * `dexbot order` instead of printing 8-decimal tails. The legacy `decimals`
10
+ * argument is retained for call-site compatibility but ignored.
11
+ */
12
+ function num(n, _decimals = 4) {
13
+ return Number.isFinite(n) ? formatFundsValue(n) : 'NaN';
14
+ }
15
+ function signed(n, decimals = 4) {
16
+ if (!Number.isFinite(n))
17
+ return 'NaN';
18
+ if (n === 0)
19
+ return num(0, decimals);
20
+ return (n >= 0 ? '+' : '') + num(n, decimals);
21
+ }
22
+ function pct(n, decimals = 2) {
23
+ if (!Number.isFinite(n))
24
+ return 'NaN%';
25
+ return (n >= 0 ? '+' : '') + n.toFixed(decimals) + '%';
26
+ }
27
+ function ratio(n) {
28
+ if (n === Infinity)
29
+ return '∞';
30
+ if (Number.isNaN(n))
31
+ return '—';
32
+ return n.toFixed(2);
33
+ }
34
+ /** Signed-value CSS class used for colouring. */
35
+ function pnlClass(n) {
36
+ if (!Number.isFinite(n) || n === 0)
37
+ return 'muted';
38
+ return n > 0 ? 'pos' : 'neg';
39
+ }
40
+ function asset(id) {
41
+ return escapeHtml(assetSymbol(id));
42
+ }
43
+ function statCard(label, value, sub = '', cls = '') {
44
+ return `<div class="card ${cls}">
45
+ <div class="card-label">${escapeHtml(label)}</div>
46
+ <div class="card-value ${cls}">${value}</div>
47
+ ${sub ? `<div class="card-sub">${sub}</div>` : ''}
48
+ </div>`;
49
+ }
50
+ function metricRow(label, value, hint = '') {
51
+ return `<div class="metric">
52
+ <span class="metric-label">${escapeHtml(label)}</span>
53
+ <span class="metric-value"${hint ? ` title="${escapeHtml(hint)}"` : ''}>${value}</span>
54
+ </div>`;
55
+ }
56
+ function renderMetrics(metrics, quoteSymbol) {
57
+ const q = escapeHtml(quoteSymbol);
58
+ if (metrics.totalLots === 0) {
59
+ return '<p class="empty">No realized lots in the selected window — no performance metrics to compute.</p>';
60
+ }
61
+ const edge = [
62
+ metricRow('Win rate', (metrics.winRate * 100).toFixed(1) + '%'),
63
+ metricRow('Profit factor', ratio(metrics.profitFactor)),
64
+ metricRow('Avg win / avg loss', ratio(metrics.avgWinLossRatio)),
65
+ metricRow('Fee drag', metrics.feeDragPct > 0 ? metrics.feeDragPct.toFixed(2) + '% of gross profit' : '—'),
66
+ metricRow('Expectancy (net)', `${num(metrics.netExpectancyBts, 4)} ${q} / trade`),
67
+ metricRow('Expectancy (gross)', `${num(metrics.expectancyBts, 4)} ${q} (${pct(metrics.expectancyPct)})`),
68
+ metricRow('Expectancy (R)', metrics.expectancyR === Infinity ? '∞' : metrics.expectancyR.toFixed(3) + 'R'),
69
+ ].join('');
70
+ const risk = [
71
+ metricRow('Sharpe (annualised)', `${ratio(metrics.sharpeAnn)}${Number.isFinite(metrics.sharpeAnnSE) ? ` ± ${metrics.sharpeAnnSE.toFixed(2)}` : ''}`, `${metrics.periodLabel} bins, n=${metrics.periodCount}`),
72
+ metricRow('Sortino (annualised)', ratio(metrics.sortinoAnn) + (metrics.sortinoAnn === Infinity ? ' (no losing periods)' : '')),
73
+ metricRow('Projected net PnL', `${num(metrics.projectedNetPnlAnn, 2)} ${q}/yr`, `${num(metrics.projectedNetPnlPerDay, 2)}/day`),
74
+ metrics.mddHadStablePeak
75
+ ? metricRow('Max drawdown', `${num(metrics.mddAbsBts, 4)} ${q} (${pct(metrics.mddPct)})`)
76
+ : metricRow('Min equity', `${num(metrics.prePeakMinEquity, 4)} ${q}`),
77
+ metricRow('Max recovery time', metrics.maxRecoveryDays > 0 ? metrics.maxRecoveryDays.toFixed(1) + ' days' + (metrics.isOngoingRecovery ? ' (ongoing)' : '') : '—'),
78
+ metrics.currentDrawdownDays > 0
79
+ ? metricRow('Current drawdown', metrics.currentDrawdownDays.toFixed(1) + ' days (active)')
80
+ : '',
81
+ ].join('');
82
+ const distribution = [
83
+ metricRow('Median PnL', pct(metrics.medianPnlPct)),
84
+ metricRow('P25 / P75', `${pct(metrics.p25PnlPct)} / ${pct(metrics.p75PnlPct)}`),
85
+ metricRow('Best / worst trade', `${pct(metrics.bestTradePct)} / ${pct(metrics.worstTradePct)}`),
86
+ metricRow('Median R', metrics.medianR.toFixed(2)),
87
+ metricRow('Trades > 1R / > 2R', `${(metrics.pctRGreater1 * 100).toFixed(1)}% / ${(metrics.pctRGreater2 * 100).toFixed(1)}%`),
88
+ metricRow('Trades < -1R', `${(metrics.pctRLessNeg1 * 100).toFixed(1)}%`),
89
+ ].join('');
90
+ const behavior = [
91
+ metricRow('Max consecutive W / L', `${metrics.maxConsecWins} / ${metrics.maxConsecLosses}`),
92
+ metricRow('Avg hold time', metrics.avgHoldHours > 0 ? metrics.avgHoldHours.toFixed(1) + ' h' : '—'),
93
+ metricRow('Maker / taker', `${(metrics.limitOrderRatio * 100).toFixed(1)}% / ${((1 - metrics.limitOrderRatio) * 100).toFixed(1)}%`),
94
+ metricRow('Sell orders filled', String(metrics.sellOrdersFilled)),
95
+ metricRow('Partial fills / order', `${metrics.fillsPerOrderMean.toFixed(2)} mean, ${metrics.fillsPerOrderMedian.toFixed(1)} med, ${metrics.fillsPerOrderMax} max`),
96
+ metricRow('One-shot orders', `${(metrics.oneShotOrderRatio * 100).toFixed(0)}%`),
97
+ metricRow('Fills / day', metrics.fillsPerDay.toFixed(2)),
98
+ metricRow('Avg volume / day', `${num(metrics.avgVolumePerDay, 2)} ${q}`),
99
+ ].join('');
100
+ return `
101
+ <div class="metrics-grid">
102
+ <div class="metrics-col"><h4>Edge</h4>${edge}</div>
103
+ <div class="metrics-col"><h4>Risk</h4>${risk}</div>
104
+ <div class="metrics-col"><h4>Distribution</h4>${distribution}</div>
105
+ <div class="metrics-col"><h4>Behavior &amp; activity</h4>${behavior}</div>
106
+ </div>`;
107
+ }
108
+ function renderPairsTable(pair, quoteSymbol) {
109
+ const lots = pair.realizedPnls;
110
+ if (lots.length === 0)
111
+ return '';
112
+ const shown = lots.slice(0, MAX_DETAIL_ROWS);
113
+ const rows = shown.map((r, i) => {
114
+ const net = r.pnlNet;
115
+ const legs = `${r.entryIsMaker ? 'M' : 'T'}/${r.exitIsMaker ? 'M' : 'T'}`;
116
+ return `<tr>
117
+ <td class="num">${i + 1}</td>
118
+ <td>${escapeHtml((r.entryTime || '').slice(0, 19).replace('T', ' '))}</td>
119
+ <td>${escapeHtml((r.exitTime || '').slice(0, 19).replace('T', ' '))}</td>
120
+ <td class="num">${num(r.amount, 4)}</td>
121
+ <td class="num">${num(r.buyPrice, 8)}</td>
122
+ <td class="num">${num(r.sellPrice, 8)}</td>
123
+ <td class="num ${pnlClass(r.pnl)}">${signed(r.pnl, 6)}</td>
124
+ <td class="num ${pnlClass(r.pnlPct)}">${pct(r.pnlPct)}</td>
125
+ <td class="num">${num(r.marketFeeEntry + r.marketFeeExit, 4)}</td>
126
+ <td class="num">${num(r.feeBts, 4)}</td>
127
+ <td class="num ${pnlClass(net)}">${signed(net, 6)}</td>
128
+ <td class="num ${pnlClass(r.pnlNetPct)}">${pct(r.pnlNetPct)}</td>
129
+ <td class="center">${legs}</td>
130
+ </tr>`;
131
+ }).join('');
132
+ const truncated = lots.length > shown.length
133
+ ? `<p class="empty">Showing the first ${shown.length.toLocaleString('en-US')} of ${lots.length.toLocaleString('en-US')} lots — use <code>--csv</code> for the full list.</p>`
134
+ : '';
135
+ return `
136
+ <details class="lots">
137
+ <summary>Realized lots (${lots.length.toLocaleString('en-US')})</summary>
138
+ <div class="table-wrap">
139
+ <table>
140
+ <thead><tr>
141
+ <th>#</th><th>Entry time</th><th>Exit time</th>
142
+ <th>Amount</th><th>Buy</th><th>Sell</th>
143
+ <th>Gross PnL</th><th>Gross %</th>
144
+ <th>Mkt fee</th><th>Op fee (BTS)</th>
145
+ <th>Net PnL</th><th>Net %</th><th>Legs</th>
146
+ </tr></thead>
147
+ <tbody>${rows}</tbody>
148
+ </table>
149
+ </div>
150
+ ${truncated}
151
+ <p class="empty">All PnL values are in ${escapeHtml(quoteSymbol)} unless marked BTS.</p>
152
+ </details>`;
153
+ }
154
+ function renderPairSection(entry) {
155
+ const { pair, metrics } = entry;
156
+ const base = asset(pair.baseAsset);
157
+ const quote = asset(pair.quoteAsset);
158
+ const quoteSymbol = assetSymbol(pair.quoteAsset);
159
+ const avgBuy = pair.totalBuyBase > 0 ? pair.totalBuyQuote / pair.totalBuyBase : 0;
160
+ const avgSell = pair.totalSellBase > 0 ? pair.totalSellQuote / pair.totalSellBase : 0;
161
+ const q = escapeHtml(quoteSymbol);
162
+ // Exactly one fee card keeps the left block a clean 2x2 when both fee
163
+ // kinds are present. Two currencies can't be summed, so the market fee is
164
+ // the headline and the op fee sits in the sub-line.
165
+ const hasMarketFee = pair.totalMarketFees > 0.0001;
166
+ const hasChainFee = pair.totalBlockchainFees > 0.0001;
167
+ const feeCard = hasMarketFee && hasChainFee
168
+ ? statCard('Fees', `${num(-pair.totalMarketFees, 4)} ${q}`, `op ${num(-pair.totalBlockchainFees, 4)} BTS`, 'neg')
169
+ : hasChainFee
170
+ ? statCard('Blockchain fees', `${num(-pair.totalBlockchainFees, 4)} BTS`, '', 'neg')
171
+ : hasMarketFee
172
+ ? statCard('Market fees', `${num(-pair.totalMarketFees, 4)} ${q}`, '', 'neg')
173
+ : '';
174
+ // Two 2x2 blocks: PnL/volume/fees, then position/activity. A 2-column grid
175
+ // keeps each card readable instead of squeezing six across one row.
176
+ const pnlCards = [
177
+ statCard('Gross PnL', `${signed(pair.totalRealizedPnl, 4)} ${q}`, '', pnlClass(pair.totalRealizedPnl)),
178
+ statCard('Net PnL', `${signed(pair.totalRealizedPnlNet, 4)} ${q}`, 'after market + op fees', pnlClass(pair.totalRealizedPnlNet)),
179
+ statCard('Volume', `${num(pair.totalBuyQuote + pair.totalSellQuote, 4)} ${q}`, `${num(pair.totalBuyQuote, 4)} bought · ${num(pair.totalSellQuote, 4)} sold`),
180
+ feeCard,
181
+ ].filter(Boolean).join('');
182
+ const positionCards = [
183
+ statCard('Realized lots', String(pair.realizedPnls.length), `from ${pair.buys.length} buys · ${pair.sells.length} sells`),
184
+ statCard('Net inventory \u0394', `${num(pair.netPosition, 4)} ${base}`, 'bought \u2212 sold in window'),
185
+ statCard('Avg buy / sell', `${num(avgBuy, 8)} / ${num(avgSell, 8)}`, `in ${q} per ${base}`),
186
+ pair.unmatchedSellBase > 0.0001 ? statCard('Unmatched sold', `${num(pair.unmatchedSellBase, 4)} ${base}`, 'inventory predates window', 'muted') : '',
187
+ ].filter(Boolean).join('');
188
+ return `
189
+ <article class="pair">
190
+ <header class="pair-head">
191
+ <h2>${base}<span class="slash">/</span>${quote}</h2>
192
+ </header>
193
+ <div class="cards-row">
194
+ <div class="cards two-col">${pnlCards}</div>
195
+ <div class="cards two-col">${positionCards}</div>
196
+ </div>
197
+ ${renderMetrics(metrics, quoteSymbol)}
198
+ ${renderPairsTable(pair, quoteSymbol)}
199
+ </article>`;
200
+ }
201
+ function renderTotals(pairs) {
202
+ if (pairs.length <= 1)
203
+ return '';
204
+ const groups = new Map();
205
+ for (const e of pairs) {
206
+ const q = e.pair.quoteAsset;
207
+ if (!groups.has(q))
208
+ groups.set(q, []);
209
+ groups.get(q).push(e);
210
+ }
211
+ const cards = [...groups.entries()].map(([quoteAsset, group]) => {
212
+ const gross = group.reduce((s, e) => s + e.pair.totalRealizedPnl, 0);
213
+ const net = group.reduce((s, e) => s + e.pair.totalRealizedPnlNet, 0);
214
+ const fees = group.reduce((s, e) => s + e.pair.totalMarketFees, 0);
215
+ const lots = group.reduce((s, e) => s + e.pair.realizedPnls.length, 0);
216
+ const quote = escapeHtml(assetSymbol(quoteAsset));
217
+ return statCard(`Total (${quote}) · ${group.length} pair${group.length === 1 ? '' : 's'}`, `${signed(net, 4)} ${quote}`, `gross ${signed(gross, 4)} · mkt fees ${num(fees, 4)} · ${lots} lots`, pnlClass(net));
218
+ }).join('');
219
+ return `<section class="totals"><div class="cards">${cards}</div></section>`;
220
+ }
221
+ const REPORT_CSS = `
222
+ :root {
223
+ --bg: #0d1117; --panel: #161b22; --panel-2: #1c2230; --border: #30363d;
224
+ --text: #c9d1d9; --muted: #8b949e; --accent: #58a6ff;
225
+ --pos: #3fb950; --neg: #f85149;
226
+ }
227
+ *, *::before, *::after { box-sizing: border-box; }
228
+ html, body { margin: 0; padding: 0; }
229
+ body { background: var(--bg); color: var(--text);
230
+ font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Helvetica, Arial, sans-serif;
231
+ font-size: 14px; line-height: 1.5; }
232
+ code { font-family: ui-monospace, SFMono-Regular, 'SF Mono', Menlo, Consolas, monospace; background: var(--panel-2); padding: 1px 5px; border-radius: 4px; }
233
+ .hero { display: flex; flex-wrap: wrap; gap: 16px; justify-content: space-between; align-items: flex-end;
234
+ padding: 28px 32px; border-bottom: 1px solid var(--border); background: linear-gradient(180deg, #161b22 0%, #0d1117 100%); }
235
+ .hero h1 { margin: 0; font-size: 24px; letter-spacing: .2px; color: #f0f6fc; }
236
+ .hero .sub { margin: 6px 0 0; color: var(--muted); font-size: 13px; }
237
+ .hero .sub b { color: var(--text); font-weight: 600; }
238
+ .generated { color: var(--muted); font-size: 12px; text-align: right; }
239
+ main { padding: 24px 32px 48px; max-width: 1500px; margin: 0 auto; }
240
+ .cards { display: grid; grid-template-columns: repeat(auto-fit, minmax(200px, 1fr)); gap: 12px; }
241
+ .cards-row { display: grid; grid-template-columns: 1fr 1fr; gap: 12px; }
242
+ .cards.two-col { grid-template-columns: repeat(2, minmax(0, 1fr)); }
243
+ .card { background: var(--panel); border: 1px solid var(--border); border-radius: 10px; padding: 14px 16px; }
244
+ .card-label { color: var(--muted); font-size: 11px; text-transform: uppercase; letter-spacing: .6px; }
245
+ .card-value { font-size: 20px; font-weight: 600; margin-top: 6px; font-variant-numeric: tabular-nums; }
246
+ .card-sub { color: var(--muted); font-size: 12px; margin-top: 4px; }
247
+ .card-value.pos, .pos { color: var(--pos); }
248
+ .card-value.neg, .neg { color: var(--neg); }
249
+ .muted, .card-value.muted { color: var(--muted); }
250
+ .totals { margin-bottom: 24px; }
251
+ .pair { background: var(--panel); border: 1px solid var(--border); border-radius: 12px; padding: 20px 22px; margin-bottom: 20px; }
252
+ .pair-head { display: flex; align-items: center; justify-content: space-between; margin-bottom: 16px; }
253
+ .pair-head h2 { margin: 0; font-size: 18px; color: #f0f6fc; }
254
+ .pair-head .slash { color: var(--muted); margin: 0 2px; }
255
+ .metrics-grid { display: grid; grid-template-columns: repeat(auto-fit, minmax(280px, 1fr)); gap: 18px 28px; margin: 20px 0 4px; }
256
+ .metrics-col h4 { margin: 0 0 8px; font-size: 12px; text-transform: uppercase; letter-spacing: .7px; color: var(--accent); border-bottom: 1px solid var(--border); padding-bottom: 6px; }
257
+ .metric { display: flex; justify-content: space-between; gap: 12px; padding: 3px 0; border-bottom: 1px dashed rgba(48,54,61,.5); }
258
+ .metric-label { color: var(--muted); font-size: 13px; }
259
+ .metric-value { font-variant-numeric: tabular-nums; font-size: 13px; text-align: right; }
260
+ details.lots { margin-top: 18px; }
261
+ details.lots > summary { cursor: pointer; color: var(--accent); font-weight: 600; font-size: 13px; padding: 6px 0; user-select: none; }
262
+ .table-wrap { overflow-x: auto; margin-top: 10px; border: 1px solid var(--border); border-radius: 8px; }
263
+ table { border-collapse: collapse; width: 100%; font-size: 12px; font-variant-numeric: tabular-nums; }
264
+ th, td { padding: 6px 10px; text-align: right; white-space: nowrap; border-bottom: 1px solid var(--border); }
265
+ th { position: sticky; top: 0; background: var(--panel-2); color: var(--muted); text-transform: uppercase; font-size: 10px; letter-spacing: .5px; z-index: 1; }
266
+ td:first-child, th:first-child, td:nth-child(2), th:nth-child(2), td:nth-child(3), th:nth-child(3) { text-align: left; }
267
+ td.center, th.center { text-align: center; }
268
+ tbody tr:hover { background: rgba(88,166,255,.06); }
269
+ .empty { color: var(--muted); font-size: 13px; margin: 10px 0; }
270
+ footer { border-top: 1px solid var(--border); padding: 18px 32px 40px; color: var(--muted); font-size: 12px; max-width: 1500px; margin: 0 auto; }
271
+ footer p { margin: 4px 0; }
272
+ @media (max-width: 900px) { .cards-row { grid-template-columns: 1fr; } }
273
+ @media (max-width: 640px) { main, .hero, footer { padding-left: 16px; padding-right: 16px; } .generated { text-align: left; } .cards.two-col { grid-template-columns: 1fr; } }
274
+ `;
275
+ function renderPnlReportHtml(input) {
276
+ const accountLabel = input.botName
277
+ ? `${input.botName} (${input.accountId})`
278
+ : input.accountId;
279
+ const filters = [];
280
+ if (input.pairFilter)
281
+ filters.push(`pair ${input.pairFilter}`);
282
+ if (input.assetFilter)
283
+ filters.push(`asset ${input.assetFilter}`);
284
+ const filterLabel = filters.length > 0 ? ` · filter: ${filters.join(', ')}` : '';
285
+ const generatedAt = input.generatedAt ?? new Date().toISOString();
286
+ const totalLots = input.pairs.reduce((s, e) => s + e.pair.realizedPnls.length, 0);
287
+ const pairsBody = input.pairs.map(renderPairSection).join('\n');
288
+ const periodLabel = `${escapeHtml(input.start.slice(0, 10))} → ${escapeHtml(input.end.slice(0, 10))}`;
289
+ return `<!DOCTYPE html>
290
+ <html lang="en">
291
+ <head>
292
+ <meta charset="UTF-8">
293
+ <meta name="viewport" content="width=device-width, initial-scale=1.0">
294
+ <meta name="darkreader-lock">
295
+ <title>PnL Report · ${escapeHtml(accountLabel)}</title>
296
+ <style>${REPORT_CSS}</style>
297
+ </head>
298
+ <body>
299
+ <header class="hero">
300
+ <div>
301
+ <h1>PnL Report</h1>
302
+ <p class="sub">Account <b>${escapeHtml(accountLabel)}</b> · ${periodLabel} · ${input.pairs.length} pair${input.pairs.length === 1 ? '' : 's'} · ${totalLots} realized lot${totalLots === 1 ? '' : 's'} · match mode <b>${escapeHtml(input.matchMode)}</b>${escapeHtml(filterLabel)}</p>
303
+ </div>
304
+ <div class="generated">Generated ${escapeHtml(generatedAt.replace('T', ' ').slice(0, 19))} UTC</div>
305
+ </header>
306
+ <main>
307
+ ${renderTotals(input.pairs)}
308
+ ${pairsBody || '<p class="empty">No classified trades in the selected window.</p>'}
309
+ </main>
310
+ <footer>
311
+ <p>PnL uses gross fill prices. Net PnL deducts market fees (issuer + network portions, converted to the pair's quote asset) and blockchain operation fees (BTS per limit_order_create). Buy lots enter at net receives, so inventory matching reflects what the account actually held.</p>
312
+ <p>If inventory predates the window or crosses asset pairs, realized lots may not reflect true trade economics. Non-BTS quote pairs report PnL in that quote asset, not BTS.</p>
313
+ <p>Amounts are shown with 4 significant figures (compact K/M) for readability.</p>
314
+ <p>Generated by DEXBot2 · <code>dexbot pnl</code></p>
315
+ </footer>
316
+ </body>
317
+ </html>`;
318
+ }
319
+ /** Render + atomically write the report; returns the resolved file path. */
320
+ function writePnlReport(input, outputPath) {
321
+ writeChartFile(outputPath, renderPnlReportHtml(input));
322
+ return outputPath;
323
+ }
324
+ export { renderPnlReportHtml, writePnlReport };
325
+ //# sourceMappingURL=pnl_report.js.map
@@ -12,7 +12,6 @@ interface SourceResolution {
12
12
  erPeriod: number;
13
13
  fastPeriod: number;
14
14
  slowPeriod: number;
15
- erSmoothPeriod: number;
16
15
  };
17
16
  amaKey: string;
18
17
  meta: any;