dexbot 1.6.9 → 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 (96) hide show
  1. package/CHANGELOG.md +34 -0
  2. package/README.md +1 -0
  3. package/analysis/README.md +50 -12
  4. package/analysis/bot_fitting/README.md +12 -0
  5. package/analysis/tradingview/README.md +15 -10
  6. package/analysis/trend_detection/DYNAMIC_WEIGHT_RESEARCH.md +10 -36
  7. package/analysis/trend_detection/README.md +31 -0
  8. package/claw/modules/chain_queries.ts +9 -4
  9. package/claw/modules/claw_bridge.ts +9 -9
  10. package/claw/package.json +1 -1
  11. package/claw/runtimes/openclaw-plugin/openclaw.plugin.json +1 -1
  12. package/claw/runtimes/openclaw-plugin/package.json +1 -1
  13. package/dist/analysis/account_resolver.js +13 -1
  14. package/dist/analysis/ama_fitting/optimizer_high_resolution.js +2 -1
  15. package/dist/analysis/analyze_dynamic_weight.js +0 -3
  16. package/dist/analysis/bot_fitting/backtest_ama_sweep.js +52 -8
  17. package/dist/analysis/bot_fitting/backtest_bot_fitting.js +68 -10
  18. package/dist/analysis/bot_fitting/backtest_lookback_drawdown.d.ts +21 -0
  19. package/dist/analysis/bot_fitting/backtest_lookback_drawdown.js +315 -0
  20. package/dist/analysis/bot_key_utils.js +17 -17
  21. package/dist/analysis/fills_cache.d.ts +64 -0
  22. package/dist/analysis/fills_cache.js +254 -0
  23. package/dist/analysis/fills_source.js +5 -2
  24. package/dist/analysis/pnl_report.d.ts +39 -0
  25. package/dist/analysis/pnl_report.js +325 -0
  26. package/dist/analysis/resolve_source.d.ts +0 -1
  27. package/dist/analysis/trade_profitability.d.ts +11 -2
  28. package/dist/analysis/trade_profitability.js +187 -61
  29. package/dist/analysis/tradingview/analyze_tradingview.d.ts +0 -3
  30. package/dist/analysis/tradingview/analyze_tradingview.js +6 -19
  31. package/dist/analysis/tradingview/grid_reset_config.d.ts +2 -0
  32. package/dist/analysis/tradingview/grid_reset_config.js +18 -1
  33. package/dist/analysis/tradingview/grid_reset_sim.d.ts +12 -1
  34. package/dist/analysis/tradingview/grid_reset_sim.js +60 -11
  35. package/dist/analysis/tradingview/tradingview_uplot_chart_generator.js +180 -33
  36. package/dist/analysis/trend_detection/backtest_ama_slope_huber.d.ts +102 -0
  37. package/dist/analysis/trend_detection/backtest_ama_slope_huber.js +725 -0
  38. package/dist/analysis/trend_detection/dynamic_weight_chart_generator.js +29 -110
  39. package/dist/analysis/trend_detection/huber_scale_variants.d.ts +34 -0
  40. package/dist/analysis/trend_detection/huber_scale_variants.js +176 -0
  41. package/dist/dexbot.js +19 -11
  42. package/dist/market_adapter/core/market_adapter_service.d.ts +15 -0
  43. package/dist/market_adapter/core/market_adapter_service.js +64 -5
  44. package/dist/market_adapter/core/strategies/ama.d.ts +1 -1
  45. package/dist/market_adapter/core/strategies/ama.js +5 -28
  46. package/dist/market_adapter/core/strategies/ama_slope_model.d.ts +2 -2
  47. package/dist/market_adapter/core/strategies/ama_slope_model.js +12 -10
  48. package/dist/market_adapter/core/strategies/dynamic_weight_series.d.ts +41 -14
  49. package/dist/market_adapter/core/strategies/dynamic_weight_series.js +138 -30
  50. package/dist/market_adapter/inputs/fetch_cex_synthetic_data.js +1 -2
  51. package/dist/market_adapter/log_format.js +1 -2
  52. package/dist/market_adapter/lp_chart_strategy_loader.js +2 -1
  53. package/dist/market_adapter/market_adapter.d.ts +0 -1
  54. package/dist/market_adapter/market_adapter.js +2 -27
  55. package/dist/market_adapter/utils/chain.d.ts +1 -1
  56. package/dist/market_adapter/utils/chain.js +8 -6
  57. package/dist/modules/account_bots.js +5 -4
  58. package/dist/modules/bitshares-native/resolvers.js +5 -0
  59. package/dist/modules/bot_settings.js +13 -1
  60. package/dist/modules/chain_orders.js +2 -1
  61. package/dist/modules/constants.d.ts +9 -1
  62. package/dist/modules/constants.js +55 -9
  63. package/dist/modules/credential_policy.js +4 -1
  64. package/dist/modules/credit_runtime.js +5 -1
  65. package/dist/modules/dexbot_maintenance_runtime.js +12 -0
  66. package/dist/modules/order/accounting.js +25 -0
  67. package/dist/modules/order/format.d.ts +35 -15
  68. package/dist/modules/order/format.js +62 -16
  69. package/dist/modules/order/manager.d.ts +1 -0
  70. package/dist/modules/order/manager.js +22 -1
  71. package/dist/modules/order/sync_engine.js +15 -1
  72. package/dist/modules/order/utils/order.d.ts +21 -1
  73. package/dist/modules/order/utils/order.js +80 -2
  74. package/dist/modules/order/utils/system.js +11 -1
  75. package/dist/modules/paths.d.ts +2 -0
  76. package/dist/modules/paths.js +2 -0
  77. package/dist/modules/utils/asset_symbols.d.ts +59 -0
  78. package/dist/modules/utils/asset_symbols.js +128 -0
  79. package/dist/modules/utils/time_range.d.ts +15 -0
  80. package/dist/modules/utils/time_range.js +18 -0
  81. package/dist/scripts/analyze-credit.js +10 -7
  82. package/dist/scripts/analyze-orders.js +1 -44
  83. package/dist/scripts/chart_command.js +15 -8
  84. package/dist/scripts/pnl.d.ts +3 -0
  85. package/dist/scripts/pnl.js +40 -0
  86. package/dist/scripts/verify-browser-bundle.js +8 -0
  87. package/dist/unlock.js +34 -0
  88. package/docs/DEXBOT_COMPARISON.md +3 -3
  89. package/docs/EVOLUTION.md +12 -10
  90. package/docs/FUND_MOVEMENT_AND_ACCOUNTING.md +1 -1
  91. package/docs/GRID_RECALCULATION.md +33 -17
  92. package/docs/README.md +2 -2
  93. package/docs/WORKFLOW.md +1 -0
  94. package/market_adapter/README.md +6 -28
  95. package/package.json +1 -1
  96. package/scripts/README.md +14 -0
@@ -0,0 +1,59 @@
1
+ /**
2
+ * Central asset-symbol / asset-ref normalization.
3
+ *
4
+ * BitShares stores asset symbols canonically UPPERCASE, so the assetA and
5
+ * assetB symbols of a bot pair are always UPPERCASE on chain.
6
+ * Nodes accept a lowercase lookup and answer it without error, so a lowercase
7
+ * symbol never fails — it just travels on as lowercase into everything built
8
+ * from it: the `symbol` field we attach to resolved assets, chart titles,
9
+ * cache-file names, Kibana query terms, and strict in-process comparisons such
10
+ * as the core-asset side check `assetA === 'CORE'`. That is a
11
+ * silent-wrong-answer class of bug, not a loud
12
+ * one, so the conversion is done ONCE here and applied at every boundary that
13
+ * accepts a pair from a human (CLI prompts, `dexbot tv`/`dw` targets) or hands
14
+ * a symbol to the chain (`lookup_asset_symbols`).
15
+ *
16
+ * Rules:
17
+ * - Asset OBJECT IDs ("1.3.x") are not symbols: they are returned verbatim so
18
+ * ref-routing callers (get_assets vs lookup_asset_symbols) keep working.
19
+ * - Everything else is trimmed and uppercased.
20
+ * - Non-strings / empty input normalize to '' (never "undefined"/"null").
21
+ *
22
+ * Browser-safe: no node built-ins.
23
+ */
24
+ /** True when the value is a BitShares asset object id, not a symbol. */
25
+ export declare function isAssetObjectId(value: unknown): boolean;
26
+ /**
27
+ * Canonicalize an asset symbol (or pass an asset object id through untouched).
28
+ * This is the single conversion used before a symbol reaches the blockchain
29
+ * and before it is compared, cached, or rendered.
30
+ */
31
+ export declare function normalizeAssetSymbol(value: unknown): string;
32
+ /**
33
+ * Same as {@link normalizeAssetSymbol}; reads better at call sites that pass a
34
+ * mixed "id or symbol" reference (credit runtime, credential policy, pools).
35
+ */
36
+ export declare function normalizeAssetRef(value: unknown): string;
37
+ /** Case- and whitespace-insensitive asset-symbol equality. */
38
+ export declare function isSameAssetSymbol(a: unknown, b: unknown): boolean;
39
+ /**
40
+ * Split an "assetA/assetB" CLI target into the two normalized symbols.
41
+ * Whitespace around either leg is dropped and both legs are uppercased, so
42
+ * "assetb/asseta" and "ASSETB / ASSETA" produce the same assetA/assetB pair.
43
+ * @returns exactly two symbols, or [] when the target is not a usable pair.
44
+ */
45
+ export declare function splitPairTarget(target: unknown): string[];
46
+ /**
47
+ * Canonicalize the asset symbols of a bot config entry, recursively into
48
+ * `debtPolicy.lending[]`. This is the single definition of WHICH config keys
49
+ * hold symbols, shared by every config reader:
50
+ * - `modules/bot_settings.normalizeBotEntry` (production read funnel)
51
+ * - `analysis/bot_key_utils.loadBotMeta` (analysis/tools read funnel)
52
+ *
53
+ * Returns the SAME reference when there is nothing to canonicalize, so the
54
+ * common already-uppercase case costs one pass and no allocation, and a
55
+ * hand-edited lowercase entry never leaks into a chain call, a comparison or
56
+ * a rendered label. The input is never mutated.
57
+ */
58
+ export declare function canonicalizeBotAssetSymbols<T extends Record<string, any>>(entry: T): T;
59
+ //# sourceMappingURL=asset_symbols.d.ts.map
@@ -0,0 +1,128 @@
1
+ /**
2
+ * Central asset-symbol / asset-ref normalization.
3
+ *
4
+ * BitShares stores asset symbols canonically UPPERCASE, so the assetA and
5
+ * assetB symbols of a bot pair are always UPPERCASE on chain.
6
+ * Nodes accept a lowercase lookup and answer it without error, so a lowercase
7
+ * symbol never fails — it just travels on as lowercase into everything built
8
+ * from it: the `symbol` field we attach to resolved assets, chart titles,
9
+ * cache-file names, Kibana query terms, and strict in-process comparisons such
10
+ * as the core-asset side check `assetA === 'CORE'`. That is a
11
+ * silent-wrong-answer class of bug, not a loud
12
+ * one, so the conversion is done ONCE here and applied at every boundary that
13
+ * accepts a pair from a human (CLI prompts, `dexbot tv`/`dw` targets) or hands
14
+ * a symbol to the chain (`lookup_asset_symbols`).
15
+ *
16
+ * Rules:
17
+ * - Asset OBJECT IDs ("1.3.x") are not symbols: they are returned verbatim so
18
+ * ref-routing callers (get_assets vs lookup_asset_symbols) keep working.
19
+ * - Everything else is trimmed and uppercased.
20
+ * - Non-strings / empty input normalize to '' (never "undefined"/"null").
21
+ *
22
+ * Browser-safe: no node built-ins.
23
+ */
24
+ /** BitShares asset object id, e.g. "1.3.0" (the core asset) or "1.3.529". */
25
+ const ASSET_OBJECT_ID_PATTERN = /^1\.3\.\d+$/;
26
+ /** True when the value is a BitShares asset object id, not a symbol. */
27
+ export function isAssetObjectId(value) {
28
+ return ASSET_OBJECT_ID_PATTERN.test(String(value ?? '').trim());
29
+ }
30
+ /**
31
+ * Canonicalize an asset symbol (or pass an asset object id through untouched).
32
+ * This is the single conversion used before a symbol reaches the blockchain
33
+ * and before it is compared, cached, or rendered.
34
+ */
35
+ export function normalizeAssetSymbol(value) {
36
+ if (value === null || value === undefined)
37
+ return '';
38
+ const text = String(value).trim();
39
+ if (!text)
40
+ return '';
41
+ if (ASSET_OBJECT_ID_PATTERN.test(text))
42
+ return text;
43
+ return text.toUpperCase();
44
+ }
45
+ /**
46
+ * Same as {@link normalizeAssetSymbol}; reads better at call sites that pass a
47
+ * mixed "id or symbol" reference (credit runtime, credential policy, pools).
48
+ */
49
+ export function normalizeAssetRef(value) {
50
+ return normalizeAssetSymbol(value);
51
+ }
52
+ /** Case- and whitespace-insensitive asset-symbol equality. */
53
+ export function isSameAssetSymbol(a, b) {
54
+ const na = normalizeAssetSymbol(a);
55
+ const nb = normalizeAssetSymbol(b);
56
+ return na !== '' && na === nb;
57
+ }
58
+ /**
59
+ * Split an "assetA/assetB" CLI target into the two normalized symbols.
60
+ * Whitespace around either leg is dropped and both legs are uppercased, so
61
+ * "assetb/asseta" and "ASSETB / ASSETA" produce the same assetA/assetB pair.
62
+ * @returns exactly two symbols, or [] when the target is not a usable pair.
63
+ */
64
+ export function splitPairTarget(target) {
65
+ return String(target ?? '')
66
+ .split('/')
67
+ .map((part) => normalizeAssetSymbol(part))
68
+ .filter((part) => part !== '');
69
+ }
70
+ // ── Config-level canonicalization (the one place that knows the key names) ────
71
+ /** bots.json keys holding an asset SYMBOL at the top level of a bot entry. */
72
+ const BOT_ASSET_SYMBOL_KEYS = ['assetA', 'assetB'];
73
+ /** `debtPolicy.lending[]` keys holding an asset SYMBOL. */
74
+ const LENDING_ASSET_SYMBOL_KEYS = ['asset', 'collateralAsset'];
75
+ /**
76
+ * Canonicalize the asset symbols of a bot config entry, recursively into
77
+ * `debtPolicy.lending[]`. This is the single definition of WHICH config keys
78
+ * hold symbols, shared by every config reader:
79
+ * - `modules/bot_settings.normalizeBotEntry` (production read funnel)
80
+ * - `analysis/bot_key_utils.loadBotMeta` (analysis/tools read funnel)
81
+ *
82
+ * Returns the SAME reference when there is nothing to canonicalize, so the
83
+ * common already-uppercase case costs one pass and no allocation, and a
84
+ * hand-edited lowercase entry never leaks into a chain call, a comparison or
85
+ * a rendered label. The input is never mutated.
86
+ */
87
+ export function canonicalizeBotAssetSymbols(entry) {
88
+ if (!entry || typeof entry !== 'object')
89
+ return entry;
90
+ let changed = false;
91
+ const out = { ...entry };
92
+ for (const key of BOT_ASSET_SYMBOL_KEYS) {
93
+ if (typeof out[key] === 'string') {
94
+ const canonical = normalizeAssetSymbol(out[key]);
95
+ if (canonical !== out[key]) {
96
+ out[key] = canonical;
97
+ changed = true;
98
+ }
99
+ }
100
+ }
101
+ if ('debtPolicy' in out) {
102
+ const policy = out.debtPolicy;
103
+ if (policy && typeof policy === 'object' && Array.isArray(policy.lending)) {
104
+ let lendingChanged = false;
105
+ const lending = policy.lending.map((item) => {
106
+ if (!item || typeof item !== 'object')
107
+ return item;
108
+ const canonicalItem = { ...item };
109
+ for (const key of LENDING_ASSET_SYMBOL_KEYS) {
110
+ if (typeof canonicalItem[key] === 'string') {
111
+ const canonical = normalizeAssetSymbol(canonicalItem[key]);
112
+ if (canonical !== canonicalItem[key]) {
113
+ canonicalItem[key] = canonical;
114
+ lendingChanged = true;
115
+ }
116
+ }
117
+ }
118
+ return canonicalItem;
119
+ });
120
+ if (lendingChanged) {
121
+ out.debtPolicy = { ...policy, lending };
122
+ changed = true;
123
+ }
124
+ }
125
+ }
126
+ return (changed ? out : entry);
127
+ }
128
+ //# sourceMappingURL=asset_symbols.js.map
@@ -0,0 +1,15 @@
1
+ /**
2
+ * Shared lookback-unit conversion for the analysis commands that accept a
3
+ * month-based range (`dexbot tv|dw|pnl --month N`).
4
+ *
5
+ * A "month" is the fixed 730-hour unit the chart pipeline already used, not a
6
+ * calendar month: it keeps a `--month 3` window exactly 3 × 730 h regardless
7
+ * of the run date, so two runs a day apart cover the same span. Centralised
8
+ * here so the chart and PnL commands can never disagree on what `--month`
9
+ * means.
10
+ */
11
+ declare const HOURS_PER_MONTH = 730;
12
+ /** Whole months → whole hours, floored at 1 so `--month 0.x` still fetches. */
13
+ declare function monthsToHours(months: number): number;
14
+ export { HOURS_PER_MONTH, monthsToHours };
15
+ //# sourceMappingURL=time_range.d.ts.map
@@ -0,0 +1,18 @@
1
+ 'use strict';
2
+ /**
3
+ * Shared lookback-unit conversion for the analysis commands that accept a
4
+ * month-based range (`dexbot tv|dw|pnl --month N`).
5
+ *
6
+ * A "month" is the fixed 730-hour unit the chart pipeline already used, not a
7
+ * calendar month: it keeps a `--month 3` window exactly 3 × 730 h regardless
8
+ * of the run date, so two runs a day apart cover the same span. Centralised
9
+ * here so the chart and PnL commands can never disagree on what `--month`
10
+ * means.
11
+ */
12
+ const HOURS_PER_MONTH = 730;
13
+ /** Whole months → whole hours, floored at 1 so `--month 0.x` still fetches. */
14
+ function monthsToHours(months) {
15
+ return Math.max(1, Math.round(months * HOURS_PER_MONTH));
16
+ }
17
+ export { HOURS_PER_MONTH, monthsToHours };
18
+ //# sourceMappingURL=time_range.js.map
@@ -33,6 +33,7 @@ const { FEE_PARAMETERS } = require('../modules/constants');
33
33
  const { PATHS } = require('../modules/paths');
34
34
  const { getErrorMessage } = require('../modules/utils/errors');
35
35
  const { sanitizeKey } = require('../modules/utils/sanitize_key');
36
+ const { normalizeAssetRef, normalizeAssetSymbol, isSameAssetSymbol } = require('../modules/utils/asset_symbols');
36
37
  const { loadSettingsFile, resolveRawBotEntries, normalizeBotEntries } = require('../modules/bot_settings');
37
38
  import { pathToFileURL } from 'node:url';
38
39
  // Terminal colors: centralized palette (modules/cli_colors.ts), shared with
@@ -239,7 +240,9 @@ async function main() {
239
240
  return (await assetInfo(assetId)).symbol;
240
241
  }
241
242
  async function resolveLendingRef(ref) {
242
- const s = String(ref);
243
+ // Refs come from bots.json debtPolicy.lending AND from --mpa/--collateral
244
+ // filters; canonicalize so a lowercase filter still matches the pair.
245
+ const s = normalizeAssetRef(ref);
243
246
  if (/^1\.3\.\d+$/.test(s)) {
244
247
  try {
245
248
  return { id: s, symbol: await symbolOf(s) };
@@ -387,9 +390,9 @@ async function main() {
387
390
  const resolvedMpa = await Promise.all(mpaFilterRefs.map(resolveLendingRef));
388
391
  const resolvedCredit = await Promise.all(creditFilterRefs.map(resolveLendingRef));
389
392
  const mpaIds = new Set(resolvedMpa.map((r) => r.id).filter(Boolean));
390
- const mpaSyms = new Set(resolvedMpa.map((r) => r.symbol.toUpperCase()));
393
+ const mpaSyms = new Set(resolvedMpa.map((r) => normalizeAssetSymbol(r.symbol)));
391
394
  const creditIds = new Set(resolvedCredit.map((r) => r.id).filter(Boolean));
392
- const creditSyms = new Set(resolvedCredit.map((r) => r.symbol.toUpperCase()));
395
+ const creditSyms = new Set(resolvedCredit.map((r) => normalizeAssetSymbol(r.symbol)));
393
396
  const filterActive = unionRefs.length > 0;
394
397
  async function debtMatches(debtAssetId, ids, syms) {
395
398
  if (!filterActive)
@@ -399,7 +402,7 @@ async function main() {
399
402
  if (ids.has(debtAssetId))
400
403
  return true;
401
404
  try {
402
- const sym = (await symbolOf(debtAssetId)).toUpperCase();
405
+ const sym = normalizeAssetSymbol(await symbolOf(debtAssetId));
403
406
  return syms.has(sym);
404
407
  }
405
408
  catch {
@@ -421,7 +424,7 @@ async function main() {
421
424
  symOk = true;
422
425
  else if (debtId) {
423
426
  try {
424
- symOk = creditSyms.has((await symbolOf(debtId)).toUpperCase());
427
+ symOk = creditSyms.has(normalizeAssetSymbol(await symbolOf(debtId)));
425
428
  }
426
429
  catch {
427
430
  symOk = false;
@@ -528,7 +531,7 @@ async function main() {
528
531
  });
529
532
  }
530
533
  const pairIdKeys = new Set(creditPairs.filter((p) => p.debtId && p.collId).map((p) => `${p.debtId}←${p.collId}`));
531
- const pairSymKeys = new Set(creditPairs.map((p) => `${p.debtSym.toUpperCase()}←${p.collSym.toUpperCase()}`));
534
+ const pairSymKeys = new Set(creditPairs.map((p) => `${normalizeAssetSymbol(p.debtSym)}←${normalizeAssetSymbol(p.collSym)}`));
532
535
  // Offer objects for the deals' conversion rates (debt per collateral).
533
536
  const dealOfferIds = creditDeals.map((d) => d?.offer_id).filter(Boolean).map(String);
534
537
  const offerById = await fetchOfferObjects(dealOfferIds);
@@ -643,7 +646,7 @@ async function main() {
643
646
  const feeDenom = Number(FEE_PARAMETERS?.GRAPHENE_FEE_RATE_DENOM) || 1000000;
644
647
  const walletRaw = await fetchWalletRaw(account);
645
648
  const matchPair = (pair, r) => (pair.debtId !== null && r.debtId !== null && pair.debtId === r.debtId && pair.collId !== null && r.collId !== null && pair.collId === r.collId) ||
646
- (pair.debtSym.toUpperCase() === r.debtSym.toUpperCase() && pair.collSym.toUpperCase() === r.collSym.toUpperCase());
649
+ (isSameAssetSymbol(pair.debtSym, r.debtSym) && isSameAssetSymbol(pair.collSym, r.collSym));
647
650
  if (avgCr !== null) {
648
651
  // Label in orange to distinguish from Curr. CR; value keeps the
649
652
  // original health color (single shared max → green/red, mixed or
@@ -15,7 +15,7 @@
15
15
  */
16
16
  import fs from 'node:fs';
17
17
  import path from 'node:path';
18
- import { formatCurrency } from '../modules/order/format.js';
18
+ import { formatCurrency, formatFundsValue } from '../modules/order/format.js';
19
19
  import { resolveConfiguredPriceBound } from '../modules/order/utils/order.js';
20
20
  import { ORDER_TYPES, ORDER_STATES, MARKET_ADAPTER } from '../modules/constants.js';
21
21
  import { applyAsymmetricBounds } from '../market_adapter/core/asymmetric_bounds.js';
@@ -253,49 +253,6 @@ function getModifiedTime(filePath) {
253
253
  function formatPercent(value) {
254
254
  return (value * 100).toFixed(2) + '%';
255
255
  }
256
- /**
257
- * formatFundsValue: Format a fund amount with compact notation (K/M for ≥1000)
258
- * and up to 4 significant figures, trimming uninformative trailing zeros.
259
- * Examples:
260
- * 194395 -> "194.4K"
261
- * 10000 -> "10K"
262
- * 1000 -> "1K"
263
- * 332.33 -> "332.3"
264
- * 10.389 -> "10.39"
265
- * 1500000 -> "1.5M"
266
- * @param {number} value
267
- * @returns {string}
268
- */
269
- function formatFundsValue(value) {
270
- if (value === 0)
271
- return '0';
272
- const absValue = Math.abs(value);
273
- let quotient;
274
- let suffix = '';
275
- if (absValue >= 1000000) {
276
- quotient = value / 1000000;
277
- suffix = 'M';
278
- }
279
- else if (absValue >= 1000) {
280
- quotient = value / 1000;
281
- suffix = 'K';
282
- }
283
- else {
284
- quotient = value;
285
- }
286
- const absQ = Math.abs(quotient);
287
- const intDigits = Math.floor(Math.log10(Math.max(absQ, 1e-10))) + 1;
288
- let formatted;
289
- if (intDigits >= 4) {
290
- formatted = String(Math.round(quotient));
291
- }
292
- else {
293
- const decimalPlaces = Math.max(0, 4 - intDigits);
294
- formatted = quotient.toFixed(decimalPlaces);
295
- formatted = formatted.replace(/(\.[0-9]*?)0+$/, '$1').replace(/\.$/, '');
296
- }
297
- return formatted + suffix;
298
- }
299
256
  /**
300
257
  * stripColorCodes: Remove ANSI color codes from a string
301
258
  * @param {string} str - String that may contain color codes
@@ -32,18 +32,19 @@ const __dirname = path.dirname(__filename);
32
32
  import { loadBotMeta, loadBotSettings, computeBotKey } from '../analysis/bot_key_utils.js';
33
33
  import { PATHS } from '../modules/paths.js';
34
34
  import { normalizePoolId, resolveAsset, findPoolByAssets } from '../market_adapter/utils/chain.js';
35
+ import { normalizeAssetSymbol, splitPairTarget } from '../modules/utils/asset_symbols.js';
35
36
  import { fetchCandlesSequentially, outputPath } from '../market_adapter/inputs/fetch_lp_data.js';
36
37
  import { fetchMarketCandlesSequentially } from '../market_adapter/inputs/fetch_book_data.js';
37
38
  import { fetchFeedCandlesSequentially } from '../market_adapter/inputs/kibana_feed_source.js';
38
39
  import { muteChainLogs } from '../modules/utils/chain_logs.js';
39
40
  import { isSameBotName, sanitizeKey } from '../modules/utils/sanitize_key.js';
40
41
  import { slugPart } from '../market_adapter/interval_utils.js';
42
+ import { monthsToHours } from '../modules/utils/time_range.js';
41
43
  const INTERVAL_SECONDS = 3600;
42
44
  const DEFAULT_MONTHS = 3;
43
45
  // Explicit --feed warns when the settlement feed is older than this
44
46
  // (a stale feed draws a flat/misleading chart). Default: 7 days.
45
47
  const FEED_STALE_WARN_AGE_MS = 7 * 24 * 3600 * 1000;
46
- const HOURS_PER_MONTH = 730;
47
48
  const CHUNK_MONTHS = 1;
48
49
  const RENDERERS = {
49
50
  tv: {
@@ -73,6 +74,7 @@ function printUsage(cmd = 'tv') {
73
74
  console.log(' <bot> Bot name or key from profiles/bots.json');
74
75
  console.log(' <pool-id> Liquidity pool id, e.g. 133 or 1.19.133 (always pool candles)');
75
76
  console.log(' AssetA/AssetB Pair symbols, e.g. TOKENA/TOKENB (pool-first, orderbook fallback)');
77
+ console.log(' Case-insensitive: assetA/assetB is uppercased before it reaches the chain');
76
78
  console.log(' MPA pairs (e.g. BTS/HONEST.USD) can chart price-feed history via --feed');
77
79
  console.log('');
78
80
  console.log('Options:');
@@ -87,6 +89,9 @@ async function resolveMpaBacking(mpaSymbol, bitsharesClient) {
87
89
  const db = bitsharesClient.BitShares?.db;
88
90
  if (!db || typeof db.lookup_asset_symbols !== 'function')
89
91
  return null;
92
+ // Canonical UPPERCASE symbol for the chain call and for every message
93
+ // below, so a lowercase assetA/assetB pair is reported UPPERCASE.
94
+ mpaSymbol = normalizeAssetSymbol(mpaSymbol);
90
95
  let mpa = null;
91
96
  try {
92
97
  const found = await db.lookup_asset_symbols([mpaSymbol]);
@@ -315,7 +320,7 @@ async function run(cmd) {
315
320
  process.exit(1);
316
321
  process.exit(0);
317
322
  }
318
- const lookbackHours = Math.max(1, Math.round(months * HOURS_PER_MONTH));
323
+ const lookbackHours = monthsToHours(months);
319
324
  const bucketMs = INTERVAL_SECONDS * 1000;
320
325
  const endMs = Math.floor(Date.now() / bucketMs) * bucketMs;
321
326
  const startMs = endMs - lookbackHours * 3600 * 1000;
@@ -325,7 +330,10 @@ async function run(cmd) {
325
330
  const botHit = findBotByTarget(target);
326
331
  const poolTarget = !botHit && isPoolIdTarget(target);
327
332
  const pairTarget = !botHit && !poolTarget && target.includes('/');
328
- const pairParts = pairTarget ? target.split('/').map((s) => s.trim()).filter(Boolean) : [];
333
+ // A pair target may be typed in any case ("assetb/asseta"); the legs are
334
+ // canonicalized here so the chain call, the cache keys, the chart title and
335
+ // the exported HTML all speak the same UPPERCASE symbols.
336
+ const pairParts = pairTarget ? splitPairTarget(target) : [];
329
337
  if (!botHit && !poolTarget && !pairTarget) {
330
338
  const settings = loadBotSettings();
331
339
  const entries = Array.isArray(settings?.bots) ? settings.bots : [];
@@ -333,7 +341,7 @@ async function run(cmd) {
333
341
  throw new Error(`Unknown target "${target}". Use a bot name/key${keys.length ? ` (${keys.slice(0, 8).join(', ')}${keys.length > 8 ? ', …' : ''})` : ''}, a pool id (e.g. 133), or AssetA/AssetB.`);
334
342
  }
335
343
  if (pairTarget && pairParts.length !== 2)
336
- throw new Error(`Invalid pair "${target}". Use AssetA/AssetB, e.g. TOKENA/TOKENB`);
344
+ throw new Error(`Invalid pair "${target}". Use AssetA/AssetB, e.g. TOKENA/TOKENB (case is normalized to uppercase)`);
337
345
  const bitsharesClient = await import('../modules/bitshares_client.js');
338
346
  const { waitForConnected } = bitsharesClient;
339
347
  await waitForConnected();
@@ -349,8 +357,8 @@ async function run(cmd) {
349
357
  if (botHit) {
350
358
  botKey = botHit.botKey;
351
359
  botMeta = botHit.meta;
352
- const symA = botMeta.assetA;
353
- const symB = botMeta.assetB;
360
+ const symA = normalizeAssetSymbol(botMeta.assetA);
361
+ const symB = normalizeAssetSymbol(botMeta.assetB);
354
362
  if (!symA || !symB)
355
363
  throw new Error(`Bot '${target}' has no assetA/assetB pair in profiles/bots.json`);
356
364
  const [metaA, metaB] = await Promise.all([resolveAsset(symA, bitsharesClient), resolveAsset(symB, bitsharesClient)]);
@@ -477,8 +485,7 @@ async function run(cmd) {
477
485
  // Both renderers resolve bot-scoped config themselves from the SAME
478
486
  // --bot-key (AMA config via resolveAmaConfig; tv additionally grid
479
487
  // bounds + order overlay). Explicit --ama-*-period forwarding was
480
- // dropped on purpose: it duplicated that resolution and forwarded only
481
- // 3 of 4 fields (silently losing erSmoothPeriod).
488
+ // dropped on purpose: it duplicated that resolution.
482
489
  if (botKey)
483
490
  analyzerArgs.push('--bot-key', botKey);
484
491
  const result = spawnSync(process.execPath, [analyzer, ...analyzerArgs], { stdio: 'inherit' });
@@ -0,0 +1,3 @@
1
+ #!/usr/bin/env node
2
+ export {};
3
+ //# sourceMappingURL=pnl.d.ts.map
@@ -0,0 +1,40 @@
1
+ #!/usr/bin/env node
2
+ 'use strict';
3
+ /**
4
+ * Usage:
5
+ * dexbot pnl <bot|account|1.2.x> [--month N] [--pair BASE/QUOTE] [--report <file>]
6
+ *
7
+ * Thin entry for the PnL analyzer (analysis/trade_profitability.ts) in HTML
8
+ * mode. The reference is resolved against local bot profiles first, then the
9
+ * chain; the account's fills for the requested window are analyzed and written
10
+ * as a self-contained HTML report. Terminal tables remain available by running
11
+ * the analyzer directly (node dist/analysis/trade_profitability.js); --json /
12
+ * --csv exports pass straight through.
13
+ */
14
+ import { pathToFileURL } from 'node:url';
15
+ import { getErrorMessage } from '../modules/utils/errors.js';
16
+ import { run } from '../analysis/trade_profitability.js';
17
+ const invoked = process.argv[1] && import.meta.url === pathToFileURL(process.argv[1]).href;
18
+ if (invoked) {
19
+ const args = process.argv.slice(2);
20
+ // HTML is this command's primary output, but only once an account/target is
21
+ // present: with no positional argument the analyzer should print its usage
22
+ // instead of treating the injected flag as the account. Leave --help/-h and
23
+ // explicit --html/--report untouched so their own handling wins.
24
+ // Append (never prepend) the injected flag: the analyzer treats argv[0] as
25
+ // the account/target positional, so a leading flag would be read as the
26
+ // account name (`dexbot pnl bbot9` would become `--html bbot9`).
27
+ const hasTarget = args.some(a => !a.startsWith('-'));
28
+ const ownsOutput = args.includes('--html') || args.includes('--report') || args.includes('--help') || args.includes('-h');
29
+ if (hasTarget && !ownsOutput)
30
+ args.push('--html');
31
+ run(args)
32
+ .then(() => process.exit(0))
33
+ .catch((err) => {
34
+ console.error(`[pnl] Error: ${getErrorMessage(err)}`);
35
+ if (process.env.DEBUG)
36
+ console.error(err);
37
+ process.exit(1);
38
+ });
39
+ }
40
+ //# sourceMappingURL=pnl.js.map
@@ -176,6 +176,14 @@ const TESTS = [
176
176
  expectFail: false,
177
177
  externalizeNodeBuiltins: true,
178
178
  },
179
+ {
180
+ // The canonical AMA-slope estimator; guards the browser-safe surface now
181
+ // that this module imports modules/constants.ts.
182
+ label: 'market_adapter/core/strategies/dynamic_weight_series.ts (browser-safe)',
183
+ entry: 'market_adapter/core/strategies/dynamic_weight_series.ts',
184
+ expectFail: false,
185
+ externalizeNodeBuiltins: true,
186
+ },
179
187
  {
180
188
  label: 'modules/bitshares-native/serial/serializer.ts (browser-safe)',
181
189
  entry: 'modules/bitshares-native/serial/serializer.ts',
package/dist/unlock.js CHANGED
@@ -977,6 +977,40 @@ async function handleControl({ cmd, target }) {
977
977
  }
978
978
  }
979
979
  }
980
+ // Worker drain: SIGTERM to the wrapper usually tears the
981
+ // supervisor tree down with it, but a dexbot worker can
982
+ // outlive the parent briefly — or keep running when the kill
983
+ // was swallowed. A `dexbot start` immediately after `stop`
984
+ // would then spawn a SECOND worker over the still-live orders
985
+ // (duplicate trades). Wait for every dexbot worker to actually
986
+ // die before returning.
987
+ if (monolithicExited) {
988
+ const workerPaths = candidateRuntimeScriptPaths(['dexbot']);
989
+ const drainDeadlineMs = 15000;
990
+ const drainStarted = Date.now();
991
+ let drained = false;
992
+ while (Date.now() - drainStarted < drainDeadlineMs) {
993
+ const aliveWorkers = [];
994
+ try {
995
+ for (const procEntry of fs.readdirSync('/proc')) {
996
+ const wpid = Number(procEntry);
997
+ if (!Number.isInteger(wpid) || wpid <= 0)
998
+ continue;
999
+ if (pidMatchesScriptCandidates(wpid, workerPaths))
1000
+ aliveWorkers.push(wpid);
1001
+ }
1002
+ }
1003
+ catch (_) { /* /proc scan is best-effort */ }
1004
+ if (aliveWorkers.length === 0) {
1005
+ drained = true;
1006
+ break;
1007
+ }
1008
+ await new Promise((res) => setTimeout(res, 250));
1009
+ }
1010
+ if (!drained) {
1011
+ console.warn(`dexbot stop: worker process(es) still alive after ${drainDeadlineMs}ms — not waiting longer (state kept; a start may report the running bot).`);
1012
+ }
1013
+ }
980
1014
  }
981
1015
  catch (err) {
982
1016
  if (err.code !== 'ESRCH')
@@ -1,7 +1,7 @@
1
1
  # DEXBot vs DEXBot2 — Detailed Comparison Report
2
2
 
3
3
  > **Date:** 2026-09-02 *(metrics refreshed against local source trees)*
4
- > **Scope:** Full architectural, functional, and operational comparison between the original [DEXBot](https://github.com/Codaone/DEXBot) (Python, v1.0.0) and DEXBot2 (TypeScript, v1.6.9).
4
+ > **Scope:** Full architectural, functional, and operational comparison between the original [DEXBot](https://github.com/Codaone/DEXBot) (Python, v1.0.0) and DEXBot2 (TypeScript, v1.6.11).
5
5
  > **Audience:** Developers, contributors, and operators evaluating or migrating between the two projects.
6
6
 
7
7
  ---
@@ -36,7 +36,7 @@
36
36
 
37
37
  | Attribute | DEXBot (original) | DEXBot2 |
38
38
  |---|---|---|
39
- | **Release Track** | 1.0.0 | v1.6.9 |
39
+ | **Release Track** | 1.0.0 | v1.6.11 |
40
40
  | **Language** | Python 3.6+ | TypeScript 5.x |
41
41
  | **Status** | Released 1.0.0, unmaintained | Active development |
42
42
  | **Last Repo Activity** | May 23, 2020 | 2026-09-02 |
@@ -776,7 +776,7 @@ Where:
776
776
 
777
777
  | Metric | DEXBot | DEXBot2 |
778
778
  |---|---|---|
779
- | **Release Track** | 1.0.0 | v1.6.9 |
779
+ | **Release Track** | 1.0.0 | v1.6.11 |
780
780
  | **Active Since** | ~2018 | December 2025 |
781
781
  | **Last Commit** | May 23, 2020 | 2026-09-02 |
782
782
  | **Total Commits** | 2281 | 2,125 (v1.4.25) |
package/docs/EVOLUTION.md CHANGED
@@ -2,14 +2,14 @@
2
2
 
3
3
  ## Executive Summary
4
4
 
5
- DEXBot2 is a sophisticated decentralized exchange trading bot for the BitShares blockchain. This report documents the complete evolution of the project from its inception in December 2025 through the current 1.6.9 release.
5
+ DEXBot2 is a sophisticated decentralized exchange trading bot for the BitShares blockchain. This report documents the complete evolution of the project from its inception in December 2025 through the current 1.6.11 release.
6
6
 
7
7
  ### Key Milestones
8
8
  - **Project Inception**: December 2, 2025
9
- - **Growth Phase**: 2,306 commits over ~9 active months
9
+ - **Growth Phase**: 2,322 commits over ~9 active months
10
10
  - **Code Maturity**: Evolution from basic utilities to a ~100,000+ LoC intelligent TypeScript system
11
- - **Stability**: Progression from manual testing to a suite of 305 automated test files
12
- - **Releases**: 141 version entries in the changelog (v0.1.0 to v1.6.9)
11
+ - **Stability**: Progression from manual testing to a suite of 307 automated test files
12
+ - **Releases**: 143 version entries in the changelog (v0.1.0 to v1.6.11)
13
13
 
14
14
  > **Post-1.0.0 "why":** the thematic story behind the hardening releases — root cause, recurring
15
15
  > bug families, and lessons — lives in
@@ -143,13 +143,13 @@ Evolved from a basic README to a comprehensive framework (50+ docs entries, 80%+
143
143
 
144
144
  ## Post-1.0.0 Status
145
145
 
146
- **Completed**: browser-safe core; credit/MPA runtime; storage-adapter I/O centralization; self-healing recovery; Kibana PnL analytics; credit-only mode; Docker support; npm package. For the grid order engine arc specifically (COW pipeline, orphan/self-trade/fill-guard hardening, invariants) see [ORDER_ENGINE_POST_1.0_RETROSPECTIVE.md](ORDER_ENGINE_POST_1.0_RETROSPECTIVE.md) §R4.
146
+ **Completed**: browser-safe core; credit/MPA runtime; storage-adapter I/O centralization; self-healing recovery; Kibana PnL analytics — terminal analyzer plus the self-contained HTML report behind `dexbot pnl` (`analysis/pnl_report.ts`), backed by a per-account month-shard fill cache (`analysis/fills_cache.ts`); credit-only mode; Docker support; npm package. For the grid order engine arc specifically (COW pipeline, orphan/self-trade/fill-guard hardening, invariants) see [ORDER_ENGINE_POST_1.0_RETROSPECTIVE.md](ORDER_ENGINE_POST_1.0_RETROSPECTIVE.md) §R4.
147
147
 
148
148
  **Planned**: backtesting engine (historical candle replay via exchange abstraction); injectable interfaces at call boundaries; SQLite persistence + Zod validation at the blockchain boundary; Telegram bot (**not yet implemented**) — owner-gated monitoring (`/status`, `/orders`, `/grid`, `/balance`) and opt-in+confirm gated control (`/start`, `/stop`, `/pause`); DEXBot is the only writer, private keys never reach the module (`TELEGRAM` block + `DEXBOT_TELEGRAM_TOKEN` env).
149
149
 
150
150
  ## Version History
151
151
 
152
- Compact, era-level view; commit counts are `git rev-list --count <tag>..<tag>` over the current history (2026-09-30), so the column sums to 2,200 — the 106 commits before the `v0.1.0` tag are not attributed to an era (2,200 + 106 = 2,306). Per-release detail lives in [CHANGELOG.md](../CHANGELOG.md); the thematic post-1.0.0 story in [ORDER_ENGINE_POST_1.0_RETROSPECTIVE.md](ORDER_ENGINE_POST_1.0_RETROSPECTIVE.md).
152
+ Compact, era-level view; commit counts are `git rev-list --count <tag>..<tag>` over the current history (2026-10-02), so the column sums to 2,215 — the 107 commits up to and including the `v0.1.0` tag are not attributed to an era (2,215 + 107 = 2,322). Per-release detail lives in [CHANGELOG.md](../CHANGELOG.md); the thematic post-1.0.0 story in [ORDER_ENGINE_POST_1.0_RETROSPECTIVE.md](ORDER_ENGINE_POST_1.0_RETROSPECTIVE.md).
153
153
 
154
154
  | Era | Commits | Theme |
155
155
  |-----|--------:|-------|
@@ -165,13 +165,15 @@ Compact, era-level view; commit counts are `git rev-list --count <tag>..<tag>` o
165
165
  | v1.6.4 → v1.6.5 | 16 | Editor-managed whitelist flags, centralized bot defaults/settings, log-symmetric range tilt, AMA gridPrice normalization, Pool/Health cues, AMA-slope Δ knob, dynamic-weight CLI, update self-heal, RMS log tagging |
166
166
  | v1.6.5 → v1.6.6 | 13 | Stale-cancellation guard hardening, editor/CLI realignment, poolRef aliases + startPrice priority, legacy SMA/MACD/RSI analyzer archived, run-relative candle-cache migration dropped, dist-freshness exclude fix |
167
167
  | v1.6.6 → v1.6.7 | 11 | Session/fill-channel recovery, clean-process ecosystem regen, onboarding redirect and key-manager link fixes, LAST-FILL-GUARD pivot persistence |
168
- | v1.6.7 → v1.6.8 | 12 | Correction-drain budget + broadcast-deferral bounds, PM2 log capture + rotation, passive version notice, genesis-ladder refusal, reserve window exclusion, legacy tolerance-matcher removal, npm-tarball trim, TV grid-reset replay, bounded Kibana tail refresh, 1.4x range-threshold widening |
168
+ | v1.6.7 → v1.6.8 | 14 | Correction-drain budget + broadcast-deferral bounds, PM2 log capture + rotation, passive version notice, genesis-ladder refusal, reserve window exclusion, legacy tolerance-matcher removal, npm-tarball trim, TV grid-reset replay, bounded Kibana tail refresh, 1.4x range-threshold widening |
169
169
  | v1.6.8 → v1.6.9 | 6 | Market-adapter cycle-CPU cuts, candle-boundary off-hour idle, spread-correction spread-tightening guard |
170
+ | v1.6.9 → v1.6.10 | 7 | Huber-robust AMA slope, asset-pair uppercase canonicalization, TradingView indicator ownership (auto opt-in, span bounds) and chart-view preservation |
171
+ | v1.6.10 → v1.6.11 | 6 | AMA-slope 3-bar persistence gate + 16h Huber lookback, EMA-smoothing removal, PnL HTML report + month-shard fill cache, five order-engine/lifecycle safety fixes |
170
172
 
171
173
  ---
172
174
 
173
175
  **Report Originally Generated**: February 19, 2026
174
- **Last Updated**: September 30, 2026
175
- **Total Commits**: 2,306
176
- **Date Range**: December 2, 2025 – September 30, 2026
176
+ **Last Updated**: October 2, 2026
177
+ **Total Commits**: 2,322
178
+ **Date Range**: December 2, 2025 – October 2, 2026
177
179
  **Repository**: DEXBot2 (BitShares DEX Trading Bot)
@@ -801,4 +801,4 @@ To prevent "Time-of-Check to Time-of-Use" errors:
801
801
  **TOCTOU protection in `processFillAccounting`.** `_buildBtsDeferredRefundAdjustment` reads `btsFeeState` from `mgr.orders` while the order lock is held — the lock is acquired before accounting runs, and the POST-RESET and BOOTSTRAP tracked-fill accounting paths follow the same locking pattern.
802
802
 
803
803
  ---
804
- *Technical Reference for DEXBot2 v1.6.9 release*
804
+ *Technical Reference for DEXBot2 v1.6.11 release*