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
@@ -15,7 +15,7 @@
15
15
  * Time/Performance (ms, %): 1-2 decimals - readable metrics
16
16
  *
17
17
  * ===============================================================================
18
- * TABLE OF CONTENTS (14 exported functions)
18
+ * TABLE OF CONTENTS (15 exported functions)
19
19
  * ===============================================================================
20
20
  *
21
21
  * SECTION 1: ASSET FORMATTING (4 functions)
@@ -24,22 +24,24 @@
24
24
  * 3. formatAmountByPrecision(value, precision) - Format using chain precision
25
25
  * 4. formatSizeByOrderType(value, orderType, assets) - Format order size by BUY/SELL asset precision
26
26
  *
27
- * SECTION 2: PRICE FORMATTING (3 functions)
28
- * 6. formatPrice(value) - Format to 8 decimals (maximum precision)
29
- * 7. formatPrice6(value) - Format to 6 decimals
30
- * 8. formatPrice4(value) - Format to 4 decimals (simplified display)
27
+ * SECTION 2: PRICE & FUNDS FORMATTING (5 functions)
28
+ * 5. formatPrice(value) - Format to 8 decimals (maximum precision)
29
+ * 6. formatPrice6(value) - Format to 6 decimals
30
+ * 7. formatPrice4(value) - Format to 4 decimals (simplified display)
31
+ * 8. formatCurrency(value, digits) - Grouped thousands with SI micro-suffixes
32
+ * 9. formatFundsValue(value) - Compact K/M, 4 significant figures (keeps trailing zeros)
31
33
  *
32
- * SECTION 3: PERCENTAGE FORMATTING (3 functions)
33
- * 9. formatPercent2(value) - Format to 2 decimals (spread %, ratios)
34
- * 10. formatPercent(value, decimals) - Format with custom decimal places
34
+ * SECTION 3: PERCENTAGE FORMATTING (2 functions)
35
+ * 10. formatPercent2(value) - Format to 2 decimals (spread %, ratios)
36
+ * 11. formatPercent(value, decimals) - Format with custom decimal places
35
37
  *
36
- * SECTION 4: RATIO/METRIC FORMATTING (3 functions)
37
- * 11. formatMetric2(value) - Format to 2 decimals (timing, performance)
38
+ * SECTION 4: RATIO/METRIC FORMATTING (1 function)
39
+ * 12. formatMetric2(value) - Format to 2 decimals (timing, performance)
38
40
  *
39
- * SECTION 5: HELPER UTILITIES (4 functions)
40
- * 12. isValidNumber(value) - Check if value is defined and finite
41
- * 13. toFiniteNumber(value, defaultValue) - Convert to finite number with fallback
42
- * 14. safeFormat(value, decimals, fallback) - Safely format with fallback
41
+ * SECTION 5: HELPER UTILITIES (3 functions)
42
+ * 13. isValidNumber(value) - Check if value is defined and finite
43
+ * 14. toFiniteNumber(value, defaultValue) - Convert to finite number with fallback
44
+ * 15. safeFormat(value, decimals, fallback) - Safely format with fallback
43
45
  *
44
46
  * ===============================================================================
45
47
  */
@@ -106,6 +108,24 @@ declare function formatPrice4(value: number): string;
106
108
  * @returns {string} Formatted value with suffix if small
107
109
  */
108
110
  declare function formatCurrency(value: number, digits?: number): string;
111
+ /**
112
+ * Format a value with compact K/M notation and exactly 4 significant figures
113
+ * for values that have more than 4. Unlike `formatCurrency`, this caps the
114
+ * significant digits of large magnitudes (e.g. a volume of 19,423,608.6 ->
115
+ * "19.42M") instead of keeping every integer digit, and it KEEPS significant
116
+ * trailing zeros rather than trimming them (1009.794 -> "1.010K", not "1.01K").
117
+ * Examples:
118
+ * 194395 -> "194.4K"
119
+ * 1009.794 -> "1.010K"
120
+ * 10000 -> "10.00K"
121
+ * 1000 -> "1.000K"
122
+ * 332.33 -> "332.3"
123
+ * 10.389 -> "10.39"
124
+ * 1500000 -> "1.500M"
125
+ * @param {number} value
126
+ * @returns {string}
127
+ */
128
+ declare function formatFundsValue(value: number): string;
109
129
  /**
110
130
  * Format percentages to 2 decimal places
111
131
  * Used for: spread %, ratios, simple percentages
@@ -145,5 +165,5 @@ declare function toFiniteNumber(value: any, defaultValue: number | null): number
145
165
  * @returns {string} Formatted value or fallback string
146
166
  */
147
167
  declare function safeFormat(value: any, decimals: number, fallback?: string): string;
148
- export { formatAmount8, formatAmount, formatAmountByPrecision, formatSizeByOrderType, formatPrice, formatPrice6, formatPrice4, formatCurrency, formatPercent2, formatPercent, formatMetric2, isValidNumber, toFiniteNumber, safeFormat };
168
+ export { formatAmount8, formatAmount, formatAmountByPrecision, formatSizeByOrderType, formatPrice, formatPrice6, formatPrice4, formatCurrency, formatFundsValue, formatPercent2, formatPercent, formatMetric2, isValidNumber, toFiniteNumber, safeFormat };
149
169
  //# sourceMappingURL=format.d.ts.map
@@ -15,7 +15,7 @@
15
15
  * Time/Performance (ms, %): 1-2 decimals - readable metrics
16
16
  *
17
17
  * ===============================================================================
18
- * TABLE OF CONTENTS (14 exported functions)
18
+ * TABLE OF CONTENTS (15 exported functions)
19
19
  * ===============================================================================
20
20
  *
21
21
  * SECTION 1: ASSET FORMATTING (4 functions)
@@ -24,22 +24,24 @@
24
24
  * 3. formatAmountByPrecision(value, precision) - Format using chain precision
25
25
  * 4. formatSizeByOrderType(value, orderType, assets) - Format order size by BUY/SELL asset precision
26
26
  *
27
- * SECTION 2: PRICE FORMATTING (3 functions)
28
- * 6. formatPrice(value) - Format to 8 decimals (maximum precision)
29
- * 7. formatPrice6(value) - Format to 6 decimals
30
- * 8. formatPrice4(value) - Format to 4 decimals (simplified display)
27
+ * SECTION 2: PRICE & FUNDS FORMATTING (5 functions)
28
+ * 5. formatPrice(value) - Format to 8 decimals (maximum precision)
29
+ * 6. formatPrice6(value) - Format to 6 decimals
30
+ * 7. formatPrice4(value) - Format to 4 decimals (simplified display)
31
+ * 8. formatCurrency(value, digits) - Grouped thousands with SI micro-suffixes
32
+ * 9. formatFundsValue(value) - Compact K/M, 4 significant figures (keeps trailing zeros)
31
33
  *
32
- * SECTION 3: PERCENTAGE FORMATTING (3 functions)
33
- * 9. formatPercent2(value) - Format to 2 decimals (spread %, ratios)
34
- * 10. formatPercent(value, decimals) - Format with custom decimal places
34
+ * SECTION 3: PERCENTAGE FORMATTING (2 functions)
35
+ * 10. formatPercent2(value) - Format to 2 decimals (spread %, ratios)
36
+ * 11. formatPercent(value, decimals) - Format with custom decimal places
35
37
  *
36
- * SECTION 4: RATIO/METRIC FORMATTING (3 functions)
37
- * 11. formatMetric2(value) - Format to 2 decimals (timing, performance)
38
+ * SECTION 4: RATIO/METRIC FORMATTING (1 function)
39
+ * 12. formatMetric2(value) - Format to 2 decimals (timing, performance)
38
40
  *
39
- * SECTION 5: HELPER UTILITIES (4 functions)
40
- * 12. isValidNumber(value) - Check if value is defined and finite
41
- * 13. toFiniteNumber(value, defaultValue) - Convert to finite number with fallback
42
- * 14. safeFormat(value, decimals, fallback) - Safely format with fallback
41
+ * SECTION 5: HELPER UTILITIES (3 functions)
42
+ * 13. isValidNumber(value) - Check if value is defined and finite
43
+ * 14. toFiniteNumber(value, defaultValue) - Convert to finite number with fallback
44
+ * 15. safeFormat(value, decimals, fallback) - Safely format with fallback
43
45
  *
44
46
  * ===============================================================================
45
47
  */
@@ -98,7 +100,7 @@ function formatSizeByOrderType(value, orderType, assets) {
98
100
  return formatAmountByPrecision(value, precision);
99
101
  }
100
102
  // ===============================================================================
101
- // SECTION 2: PRICE FORMATTING
103
+ // SECTION 2: PRICE & FUNDS FORMATTING
102
104
  // ===============================================================================
103
105
  /**
104
106
  * Format prices to 8 decimal places (maximum precision)
@@ -157,6 +159,50 @@ function formatCurrency(value, digits = 4) {
157
159
  ? formatted.replace(/\B(?=(\d{3})+(?!\d))/g, ',')
158
160
  : formatted;
159
161
  }
162
+ /**
163
+ * Format a value with compact K/M notation and exactly 4 significant figures
164
+ * for values that have more than 4. Unlike `formatCurrency`, this caps the
165
+ * significant digits of large magnitudes (e.g. a volume of 19,423,608.6 ->
166
+ * "19.42M") instead of keeping every integer digit, and it KEEPS significant
167
+ * trailing zeros rather than trimming them (1009.794 -> "1.010K", not "1.01K").
168
+ * Examples:
169
+ * 194395 -> "194.4K"
170
+ * 1009.794 -> "1.010K"
171
+ * 10000 -> "10.00K"
172
+ * 1000 -> "1.000K"
173
+ * 332.33 -> "332.3"
174
+ * 10.389 -> "10.39"
175
+ * 1500000 -> "1.500M"
176
+ * @param {number} value
177
+ * @returns {string}
178
+ */
179
+ function formatFundsValue(value) {
180
+ if (!Number.isFinite(value))
181
+ return 'N/A';
182
+ if (value === 0)
183
+ return '0';
184
+ const digits = 4;
185
+ const absValue = Math.abs(value);
186
+ let quotient;
187
+ let suffix = '';
188
+ if (absValue >= 1000000) {
189
+ quotient = value / 1000000;
190
+ suffix = 'M';
191
+ }
192
+ else if (absValue >= 1000) {
193
+ quotient = value / 1000;
194
+ suffix = 'K';
195
+ }
196
+ else {
197
+ quotient = value;
198
+ }
199
+ const absQ = Math.abs(quotient);
200
+ const intDigits = Math.floor(Math.log10(Math.max(absQ, 1e-10))) + 1;
201
+ const formatted = intDigits >= digits
202
+ ? String(Math.round(quotient))
203
+ : quotient.toFixed(digits - intDigits);
204
+ return formatted + suffix;
205
+ }
160
206
  // ===============================================================================
161
207
  // SECTION 3: PERCENTAGE FORMATTING
162
208
  // ===============================================================================
@@ -222,5 +268,5 @@ function safeFormat(value, decimals, fallback = 'N/A') {
222
268
  // ===============================================================================
223
269
  // EXPORTS
224
270
  // ===============================================================================
225
- export { formatAmount8, formatAmount, formatAmountByPrecision, formatSizeByOrderType, formatPrice, formatPrice6, formatPrice4, formatCurrency, formatPercent2, formatPercent, formatMetric2, isValidNumber, toFiniteNumber, safeFormat };
271
+ export { formatAmount8, formatAmount, formatAmountByPrecision, formatSizeByOrderType, formatPrice, formatPrice6, formatPrice4, formatCurrency, formatFundsValue, formatPercent2, formatPercent, formatMetric2, isValidNumber, toFiniteNumber, safeFormat };
226
272
  //# sourceMappingURL=format.js.map
@@ -152,6 +152,7 @@ declare class OrderManager {
152
152
  _committedOrderIds: Set<string>;
153
153
  _committedOrderIdsBuiltAt: number;
154
154
  _orderIdAssignedAt: Map<string, number>;
155
+ _placedAt: Map<string, number>;
155
156
  _gapSlots: number;
156
157
  _genesis: any;
157
158
  _missingGenesis: any;
@@ -30,7 +30,7 @@ import { ORDER_TYPES, ORDER_STATES, REBALANCE_STATES, TIMING, LOG_LEVEL, PIPELIN
30
30
  import { seedBotRuntimeConfig } from '../bot_defaults.js';
31
31
  import { getMinOrderSize, computeChainFundTotals, hasValidAccountTotals, resolveConfigValueWithRegistry, isExplicitZeroAllocation, floatToBlockchainInt, validateBoundaryCommit, resolveGapSlots, resolveGapBand, isSlotInRail } from './utils/math.js';
32
32
  import { validateOrder, validateGridForPersistence, validateWorkingGridFunds, checkFundDrift, reconcileGrid, optimizeRebalanceActions, projectTargetToWorkingGrid, buildStateUpdates, buildAbortedResult, buildSuccessResult, evaluateCommit } from './utils/validate.js';
33
- import { resolveSpreadOrderSide, parseSlotIndex, parseChainOrder, geometryTypeForSlotIndex, isOrderOnChain, resolveReserveCount, resolveLiveReserveEdgeAnchorPrice, compareReserveEdge, collectRefillSlotIds } from './utils/order.js';
33
+ import { resolveSpreadOrderSide, parseSlotIndex, parseChainOrder, geometryTypeForSlotIndex, isOrderOnChain, resolveReserveCount, resolveLiveReserveEdgeAnchorPrice, compareReserveEdge, collectRefillSlotIds, recordOrderPlacement } from './utils/order.js';
34
34
  import { getErrorMessage } from '../utils/errors.js';
35
35
  const { toFiniteNumber } = Format;
36
36
  // ===============================================================================
@@ -417,6 +417,7 @@ class OrderManager {
417
417
  _committedOrderIds;
418
418
  _committedOrderIdsBuiltAt;
419
419
  _orderIdAssignedAt;
420
+ _placedAt;
420
421
  _gapSlots;
421
422
  _genesis;
422
423
  _missingGenesis;
@@ -540,6 +541,9 @@ class OrderManager {
540
541
  this._committedOrderIds = new Set();
541
542
  this._committedOrderIdsBuiltAt = 0;
542
543
  this._orderIdAssignedAt = new Map();
544
+ // Fresh-placement timestamps (chainOrderId -> Date.now) for the
545
+ // surplus-cancel grace window. See recordOrderPlacement.
546
+ this._placedAt = new Map();
543
547
  this._gapSlots = 0;
544
548
  // Genesis (price-ladder) state. `_genesis` is established by
545
549
  // loadGrid/initializeGrid; these records are the missing-genesis fault
@@ -1355,6 +1359,23 @@ class OrderManager {
1355
1359
  }
1356
1360
  this._orderIdAssignedAt.set(updatedOrder.orderId, Date.now());
1357
1361
  }
1362
+ // Fresh-placement timestamp for the surplus-cancel grace window: a
1363
+ // slot gaining an orderId it did not have is a new placement (create,
1364
+ // adopt, rotation target), and surplus sweeps must not cancel it
1365
+ // before it has had time to prove itself. Same-id updates do not
1366
+ // refresh the stamp, so grace cannot extend forever. Snapshot/grid
1367
+ // load paths are excluded: reloaded orders are old by definition, and
1368
+ // stamping them would neuter surplus sweeps for 15 minutes after every
1369
+ // restart.
1370
+ try {
1371
+ const prevId = oldOrder?.orderId != null ? String(oldOrder.orderId) : '';
1372
+ const nextId = updatedOrder.orderId != null ? String(updatedOrder.orderId) : '';
1373
+ const isLoadContext = context === 'grid-load' || context === 'grid-init';
1374
+ if (nextId && nextId !== prevId && !isLoadContext) {
1375
+ recordOrderPlacement(this, nextId);
1376
+ }
1377
+ }
1378
+ catch { /* bookkeeping must never break order updates */ }
1358
1379
  const newMap = cloneMap(this.orders);
1359
1380
  newMap.set(id, updatedOrder);
1360
1381
  this.orders = Object.freeze(newMap);
@@ -124,7 +124,7 @@ const { BitShares } = client;
124
124
  import { NATIVE_CLIENT } from '../constants.js';
125
125
  const { toFiniteNumber } = Format;
126
126
  import { blockchainToFloat, floatToBlockchainInt, getAssetFees, getBtsSide, slotIndexForPrice, isChainPriceOutOfGrid, isSlotInRail, priceForSlot, priceSlotEqual } from './utils/math.js';
127
- import { parseChainOrder, applyChainSizeToGridOrder, convertToSpreadPlaceholder, virtualizeOrder, buildFillKey, isOrderPlaced, hasOnChainId, isOrderVirtual, resolveSpreadOrderSide, duplicateOrphanLogInfo, _stampCorrectionProvenance } from './utils/order.js';
127
+ import { parseChainOrder, applyChainSizeToGridOrder, convertToSpreadPlaceholder, virtualizeOrder, buildFillKey, isOrderPlaced, hasOnChainId, isOrderVirtual, resolveSpreadOrderSide, duplicateOrphanLogInfo, _stampCorrectionProvenance, _filterUnmatchedChainOrders } from './utils/order.js';
128
128
  import { parseSlotIndex } from './utils/slot.js';
129
129
  import { resolveProcessedFillPersistenceMode } from './processed_fill_store.js';
130
130
  import { hasGenesisLadder } from './genesis_policy.js';
@@ -442,6 +442,10 @@ async function adoptChainOrderIntoSlot(mgr, slot, chainOrder, chainOrderId, rawC
442
442
  filledOrders.push({ ...bestMatch });
443
443
  updatedOrders.push(spreadOrder);
444
444
  chainOrderIdsOnGrid.add(chainOrderId);
445
+ try {
446
+ _filterUnmatchedChainOrders(mgr, chainOrderId);
447
+ }
448
+ catch { /* counting hygiene only */ }
445
449
  return true; // filled path
446
450
  }
447
451
  }
@@ -458,6 +462,12 @@ async function adoptChainOrderIntoSlot(mgr, slot, chainOrder, chainOrderId, rawC
458
462
  }
459
463
  updatedOrders.push(bestMatch);
460
464
  chainOrderIdsOnGrid.add(chainOrderId);
465
+ // Adopted means matched: drop any deferred-orphan record so fund counting
466
+ // (which adds unmatched locks) never double-counts the slot.
467
+ try {
468
+ _filterUnmatchedChainOrders(mgr, chainOrderId);
469
+ }
470
+ catch { /* counting hygiene only */ }
461
471
  return true;
462
472
  }
463
473
  class SyncEngine {
@@ -2200,6 +2210,10 @@ class SyncEngine {
2200
2210
  mgr.logger?.log?.(`[SYNC] createOrder linkage FAILED: grid order ${gridOrderId} not in master and materializing chain order ${chainOrderId} (${materializeType} @${materializePrice} x${descriptorSize}) was rejected — chain order left untracked`, 'error');
2201
2211
  }
2202
2212
  else {
2213
+ try {
2214
+ _filterUnmatchedChainOrders(mgr, chainOrderId);
2215
+ }
2216
+ catch { /* counting hygiene only */ }
2203
2217
  mgr.logger?.log?.(`[SYNC] createOrder for unknown grid order ${gridOrderId}: materialized ${materializeType} @${materializePrice} x${descriptorSize} (price source: ${priceSource}) -> ${chainOrderId} (master lost the slot mid-broadcast)`, 'warn');
2204
2218
  }
2205
2219
  }
@@ -115,6 +115,26 @@ declare function duplicateOrphanLogInfo(orderId: any): {
115
115
  level: string;
116
116
  suffix: string;
117
117
  };
118
+ declare function _filterUnmatchedChainOrders(manager: any, chainOrderId: string): void;
119
+ /**
120
+ * Record a fresh on-chain placement timestamp for surplus-cancel grace.
121
+ * Called when a slot gains a chain orderId it did not have before (create,
122
+ * adopt, rotation target). Powers isFreshlyPlacedOrder below.
123
+ * @param {any} manager - OrderManager instance (owns `_placedAt`)
124
+ * @param {string} chainOrderId - Chain order id that was just placed
125
+ */
126
+ declare function recordOrderPlacement(manager: any, chainOrderId: string | null | undefined): void;
127
+ /**
128
+ * True when the chain order was placed within the surplus-cancel grace
129
+ * window. Surplus sweeps must skip such orders: a fill landing between two
130
+ * controllers' count snapshots otherwise makes the second cancel what the
131
+ * first just placed (fee bleed + empty levels, no net change).
132
+ * @param {any} manager - OrderManager instance
133
+ * @param {string} chainOrderId - Chain order id to test
134
+ * @param {number} [graceMs] - Override grace window (defaults to TIMING.SURPLUS_CANCEL_GRACE_MS)
135
+ * @returns {boolean} True while the order is still inside its grace window
136
+ */
137
+ declare function isFreshlyPlacedOrder(manager: any, chainOrderId: string | null | undefined, graceMs?: number): boolean;
118
138
  /**
119
139
  * Stamp queue provenance on a correction entry: queued-at timestamp plus
120
140
  * the detector that produced it. Existing provenance (e.g. a fresher
@@ -1139,5 +1159,5 @@ declare function collectKnownOnChainOrderIds(mgr: any, placedResults: any, place
1139
1159
  all: string[];
1140
1160
  };
1141
1161
  export { parseChainOrder, applyChainSizeToGridOrder, buildFillKey, correctOrderPriceOnChain, correctAllPriceMismatches, _validatePriceCorrectionEntry, _stampCorrectionProvenance, findLiveOrderOwnerByChainId, buildCreateOrderArgs, getOrderTypeFromUpdatedFlags, resolveConfiguredPriceBound, virtualizeOrder, convertToSpreadPlaceholder, toRailHolePlaceholder, geometryTypeForSlotIndex, detectGapEvacuationCandidates, updateGapEvacuationStreaks, resolveSpreadOrderSide, chainOrderMatchesSlot, chainOrderMatchesSlotWithTolerance, crossingCandidateChainId, isCrossingCheckCandidate, buildCrossingCheckCandidates, parseSlotIndex, filterOrdersByType, buildOutsideInPairGroups, extractBatchOperationResults, formatUnmatchedChainOrder, isNonBlockingUnmatchedOrder, isStrandedHoldOrder, isOrderOnChain, isOrderVirtual, hasOnChainId, isOrderPlaced, isPhantomOrder, isSlotAvailable, isEmptyGridSlot, isOrderHealthy, checkSizeThreshold, checkSizesBeforeMinimum, calculateIdealBoundary, assignGridRoles, resolveOnChainRetypeType, shouldFlagOutOfSpread, buildIndexes, validateIndexes, ordersEqual, buildDelta, deriveTargetBoundary, isShiftEligibleFill, resolveReserveCount, resolveReserveOrders, selectReserveEdgeSlots, getActiveOrdersTotal, getSideBudget, calculateBudgetedSizes, buildCreateOpFingerprint, isOrderGoneErrorMessage, recordDuplicateOrphanDetection, clearDuplicateOrphanDetection, duplicateOrphanLogInfo, chainOrderUnchangedFromCache, detectCrossedBookPlan, collectKnownOnChainOrderIds, reserveEdgeIdSet, liveWindowIdSet, checkGridPriceInvariant, reportGridPriceInvariant };
1142
- export { resolveReserveEdgeAnchorPrice, resolveLiveReserveEdgeAnchorPrice, compareReserveEdge, collectRefillSlotIds };
1162
+ export { resolveReserveEdgeAnchorPrice, resolveLiveReserveEdgeAnchorPrice, compareReserveEdge, collectRefillSlotIds, recordOrderPlacement, isFreshlyPlacedOrder, _filterUnmatchedChainOrders };
1143
1163
  //# sourceMappingURL=order.d.ts.map
@@ -198,6 +198,59 @@ function _filterUnmatchedChainOrders(manager, chainOrderId) {
198
198
  manager._lastUnmatchedChainOrders = manager._lastUnmatchedChainOrders.filter((u) => (u?.id || u?.orderId || u?.chainOrderId) !== chainOrderId);
199
199
  }
200
200
  }
201
+ /**
202
+ * Record a fresh on-chain placement timestamp for surplus-cancel grace.
203
+ * Called when a slot gains a chain orderId it did not have before (create,
204
+ * adopt, rotation target). Powers isFreshlyPlacedOrder below.
205
+ * @param {any} manager - OrderManager instance (owns `_placedAt`)
206
+ * @param {string} chainOrderId - Chain order id that was just placed
207
+ */
208
+ function recordOrderPlacement(manager, chainOrderId) {
209
+ try {
210
+ if (!manager || chainOrderId == null || String(chainOrderId).length === 0)
211
+ return;
212
+ if (!(manager._placedAt instanceof Map))
213
+ manager._placedAt = new Map();
214
+ manager._placedAt.set(String(chainOrderId), Date.now());
215
+ // Lazy GC: placement timestamps only matter inside the grace window.
216
+ if (manager._placedAt.size > 500) {
217
+ const cutoff = Date.now() - TIMING.SURPLUS_CANCEL_GRACE_MS * 2;
218
+ for (const [id, ts] of manager._placedAt) {
219
+ if (Number(ts) < cutoff)
220
+ manager._placedAt.delete(id);
221
+ }
222
+ }
223
+ }
224
+ catch { /* bookkeeping must never break placement */ }
225
+ }
226
+ /**
227
+ * True when the chain order was placed within the surplus-cancel grace
228
+ * window. Surplus sweeps must skip such orders: a fill landing between two
229
+ * controllers' count snapshots otherwise makes the second cancel what the
230
+ * first just placed (fee bleed + empty levels, no net change).
231
+ * @param {any} manager - OrderManager instance
232
+ * @param {string} chainOrderId - Chain order id to test
233
+ * @param {number} [graceMs] - Override grace window (defaults to TIMING.SURPLUS_CANCEL_GRACE_MS)
234
+ * @returns {boolean} True while the order is still inside its grace window
235
+ */
236
+ function isFreshlyPlacedOrder(manager, chainOrderId, graceMs) {
237
+ try {
238
+ if (chainOrderId == null || String(chainOrderId).length === 0)
239
+ return false;
240
+ const placedAt = manager?._placedAt instanceof Map
241
+ ? manager._placedAt.get(String(chainOrderId))
242
+ : null;
243
+ if (!Number.isFinite(Number(placedAt)))
244
+ return false;
245
+ const grace = Number.isFinite(Number(graceMs)) && Number(graceMs) > 0
246
+ ? Number(graceMs)
247
+ : TIMING.SURPLUS_CANCEL_GRACE_MS;
248
+ return Date.now() - Number(placedAt) < grace;
249
+ }
250
+ catch {
251
+ return false;
252
+ }
253
+ }
201
254
  /**
202
255
  * Remove a single correction entry by its full queue key
203
256
  * (chainOrderId + surplus flag). The queue's upsert key is
@@ -504,6 +557,13 @@ async function correctOrderPriceOnChain(manager, correctionInfo, accountName, pr
504
557
  // Cancel-only entries (e.g., duplicate price level orphans) — cancel without
505
558
  // updating any grid slot. The orphan has no matching grid slot to convert.
506
559
  if (cancelOnly) {
560
+ // Surplus-cancel grace: a fill landing between two controllers' count
561
+ // snapshots must not get a seconds-old placement cancelled. Skip
562
+ // quietly; the entry stays queued and re-evaluates next cycle.
563
+ if (isFreshlyPlacedOrder(manager, chainOrderId)) {
564
+ manager.logger?.log?.(`[CORRECTION] Skipping cancel-only for freshly placed ${chainOrderId} — inside grace window`, 'info');
565
+ return { success: true, skipped: true };
566
+ }
507
567
  let shouldRemove = false;
508
568
  try {
509
569
  const sideLabel = type === ORDER_TYPES.SELL ? 'SELL' : 'BUY';
@@ -531,6 +591,10 @@ async function correctOrderPriceOnChain(manager, correctionInfo, accountName, pr
531
591
  }
532
592
  // Surplus/type-mismatch entries need cancellation, not a price update
533
593
  if (isSurplus) {
594
+ if (isFreshlyPlacedOrder(manager, chainOrderId)) {
595
+ manager.logger?.log?.(`[CORRECTION] Skipping surplus cancel for freshly placed ${chainOrderId} — inside grace window`, 'info');
596
+ return { success: true, skipped: true };
597
+ }
534
598
  let shouldRemove = false;
535
599
  try {
536
600
  const sideLabel = type === ORDER_TYPES.SELL ? 'SELL' : 'BUY';
@@ -926,7 +990,21 @@ async function correctAllPriceMismatches(manager, accountName, privateKey, accou
926
990
  // inter-op delay, fund-safety-critical). Only the SYNC_DELAY_MS-spaced
927
991
  // price-update loop is budgeted; the unselected remainder stays queued
928
992
  // durably and re-drains next cycle.
929
- const cancelEntries = liveEntries.filter((c) => c.cancelOnly === true || c.isSurplus === true);
993
+ //
994
+ // Freshly placed orders are held back from BOTH the batched and the
995
+ // serial cancel paths here: the per-entry grace check inside
996
+ // correctOrderPriceOnChain cannot protect the batch path, which
997
+ // bypasses it. Held-back entries are simply left in
998
+ // ordersNeedingPriceCorrection (never removed) and re-drain next cycle.
999
+ const cancelEntries = liveEntries.filter((c) => {
1000
+ if (!(c.cancelOnly === true || c.isSurplus === true))
1001
+ return false;
1002
+ if (isFreshlyPlacedOrder(manager, c.chainOrderId)) {
1003
+ manager?.logger?.log?.(`[CORRECTION] Deferring cancel of freshly placed ${c.chainOrderId} — inside grace window`, 'info');
1004
+ return false;
1005
+ }
1006
+ return true;
1007
+ });
930
1008
  const updateEntries = liveEntries.filter((c) => !(c.cancelOnly === true || c.isSurplus === true));
931
1009
  const canBatch = cancelEntries.length > 1
932
1010
  && typeof accountOrders?.buildCancelOrderOp === 'function'
@@ -3164,5 +3242,5 @@ function collectKnownOnChainOrderIds(mgr, placedResults, placedContexts, extraCr
3164
3242
  return { masterIds: [...masterIds], createIds: [...createIds], all: [...all] };
3165
3243
  }
3166
3244
  export { parseChainOrder, applyChainSizeToGridOrder, buildFillKey, correctOrderPriceOnChain, correctAllPriceMismatches, _validatePriceCorrectionEntry, _stampCorrectionProvenance, findLiveOrderOwnerByChainId, buildCreateOrderArgs, getOrderTypeFromUpdatedFlags, resolveConfiguredPriceBound, virtualizeOrder, convertToSpreadPlaceholder, toRailHolePlaceholder, geometryTypeForSlotIndex, detectGapEvacuationCandidates, updateGapEvacuationStreaks, resolveSpreadOrderSide, chainOrderMatchesSlot, chainOrderMatchesSlotWithTolerance, crossingCandidateChainId, isCrossingCheckCandidate, buildCrossingCheckCandidates, parseSlotIndex, filterOrdersByType, buildOutsideInPairGroups, extractBatchOperationResults, formatUnmatchedChainOrder, isNonBlockingUnmatchedOrder, isStrandedHoldOrder, isOrderOnChain, isOrderVirtual, hasOnChainId, isOrderPlaced, isPhantomOrder, isSlotAvailable, isEmptyGridSlot, isOrderHealthy, checkSizeThreshold, checkSizesBeforeMinimum, calculateIdealBoundary, assignGridRoles, resolveOnChainRetypeType, shouldFlagOutOfSpread, buildIndexes, validateIndexes, ordersEqual, buildDelta, deriveTargetBoundary, isShiftEligibleFill, resolveReserveCount, resolveReserveOrders, selectReserveEdgeSlots, getActiveOrdersTotal, getSideBudget, calculateBudgetedSizes, buildCreateOpFingerprint, isOrderGoneErrorMessage, recordDuplicateOrphanDetection, clearDuplicateOrphanDetection, duplicateOrphanLogInfo, chainOrderUnchangedFromCache, detectCrossedBookPlan, collectKnownOnChainOrderIds, reserveEdgeIdSet, liveWindowIdSet, checkGridPriceInvariant, reportGridPriceInvariant };
3167
- export { resolveReserveEdgeAnchorPrice, resolveLiveReserveEdgeAnchorPrice, compareReserveEdge, collectRefillSlotIds };
3245
+ export { resolveReserveEdgeAnchorPrice, resolveLiveReserveEdgeAnchorPrice, compareReserveEdge, collectRefillSlotIds, recordOrderPlacement, isFreshlyPlacedOrder, _filterUnmatchedChainOrders };
3168
3246
  //# sourceMappingURL=order.js.map
@@ -76,6 +76,7 @@ declare function resolveAnalysisDirs(profilesDir?: string, projectRoot?: string)
76
76
  DIR: string;
77
77
  CHARTS_DIR: string;
78
78
  RESULTS_DIR: string;
79
+ CACHE_DIR: string;
79
80
  ASSETS_DIR: string;
80
81
  };
81
82
  /**
@@ -147,6 +148,7 @@ declare const PATHS: {
147
148
  DIR: string;
148
149
  CHARTS_DIR: string;
149
150
  RESULTS_DIR: string;
151
+ CACHE_DIR: string;
150
152
  ASSETS_DIR: string;
151
153
  };
152
154
  };
@@ -234,6 +234,8 @@ function resolveAnalysisDirs(profilesDir = PROFILES_DIR, projectRoot = PROJECT_R
234
234
  DIR: outRoot,
235
235
  CHARTS_DIR: path.join(outRoot, 'charts'),
236
236
  RESULTS_DIR: path.join(outRoot, 'results'),
237
+ // Persistent query caches (e.g. analysis/fills_cache month shards).
238
+ CACHE_DIR: path.join(outRoot, 'cache'),
237
239
  // Vendored read-only assets always live with the code (repo checkout
238
240
  // or npm package), never under the relocated output root.
239
241
  ASSETS_DIR: path.join(sourceDir, 'uplot'),
@@ -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
@@ -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
@@ -39,12 +39,12 @@ import { fetchFeedCandlesSequentially } from '../market_adapter/inputs/kibana_fe
39
39
  import { muteChainLogs } from '../modules/utils/chain_logs.js';
40
40
  import { isSameBotName, sanitizeKey } from '../modules/utils/sanitize_key.js';
41
41
  import { slugPart } from '../market_adapter/interval_utils.js';
42
+ import { monthsToHours } from '../modules/utils/time_range.js';
42
43
  const INTERVAL_SECONDS = 3600;
43
44
  const DEFAULT_MONTHS = 3;
44
45
  // Explicit --feed warns when the settlement feed is older than this
45
46
  // (a stale feed draws a flat/misleading chart). Default: 7 days.
46
47
  const FEED_STALE_WARN_AGE_MS = 7 * 24 * 3600 * 1000;
47
- const HOURS_PER_MONTH = 730;
48
48
  const CHUNK_MONTHS = 1;
49
49
  const RENDERERS = {
50
50
  tv: {
@@ -320,7 +320,7 @@ async function run(cmd) {
320
320
  process.exit(1);
321
321
  process.exit(0);
322
322
  }
323
- const lookbackHours = Math.max(1, Math.round(months * HOURS_PER_MONTH));
323
+ const lookbackHours = monthsToHours(months);
324
324
  const bucketMs = INTERVAL_SECONDS * 1000;
325
325
  const endMs = Math.floor(Date.now() / bucketMs) * bucketMs;
326
326
  const startMs = endMs - lookbackHours * 3600 * 1000;
@@ -485,8 +485,7 @@ async function run(cmd) {
485
485
  // Both renderers resolve bot-scoped config themselves from the SAME
486
486
  // --bot-key (AMA config via resolveAmaConfig; tv additionally grid
487
487
  // bounds + order overlay). Explicit --ama-*-period forwarding was
488
- // dropped on purpose: it duplicated that resolution and forwarded only
489
- // 3 of 4 fields (silently losing erSmoothPeriod).
488
+ // dropped on purpose: it duplicated that resolution.
490
489
  if (botKey)
491
490
  analyzerArgs.push('--bot-key', botKey);
492
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