dexbot 1.7.1 → 1.7.3

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 (66) hide show
  1. package/CHANGELOG.md +52 -0
  2. package/claw/package.json +1 -1
  3. package/claw/runtimes/openclaw-plugin/openclaw.plugin.json +1 -1
  4. package/claw/runtimes/openclaw-plugin/package.json +1 -1
  5. package/dist/analysis/grid_correction_check.d.ts +60 -1
  6. package/dist/analysis/grid_correction_check.js +268 -18
  7. package/dist/analysis/pivot_timeline.d.ts +78 -0
  8. package/dist/analysis/pivot_timeline.js +360 -0
  9. package/dist/market_adapter/utils/file_lock.js +16 -4
  10. package/dist/modules/account_bots.d.ts +7 -0
  11. package/dist/modules/account_bots.js +7 -5
  12. package/dist/modules/bot_defaults.js +6 -1
  13. package/dist/modules/constants.d.ts +14 -0
  14. package/dist/modules/constants.js +82 -2
  15. package/dist/modules/dexbot_class.d.ts +39 -0
  16. package/dist/modules/dexbot_class.js +86 -1
  17. package/dist/modules/dexbot_cow_runtime.d.ts +31 -1
  18. package/dist/modules/dexbot_cow_runtime.js +299 -75
  19. package/dist/modules/dexbot_maintenance_runtime.d.ts +32 -2
  20. package/dist/modules/dexbot_maintenance_runtime.js +196 -16
  21. package/dist/modules/dexbot_state_recovery.js +15 -1
  22. package/dist/modules/launcher/instance_lock.d.ts +27 -0
  23. package/dist/modules/launcher/instance_lock.js +131 -0
  24. package/dist/modules/node_flap_score.d.ts +6 -6
  25. package/dist/modules/node_flap_score.js +6 -6
  26. package/dist/modules/order/accounting.d.ts +9 -4
  27. package/dist/modules/order/accounting.js +89 -26
  28. package/dist/modules/order/async_lock.d.ts +7 -1
  29. package/dist/modules/order/async_lock.js +7 -1
  30. package/dist/modules/order/export.js +25 -18
  31. package/dist/modules/order/fill_ledger.d.ts +99 -0
  32. package/dist/modules/order/fill_ledger.js +103 -0
  33. package/dist/modules/order/grid.d.ts +94 -18
  34. package/dist/modules/order/grid.js +247 -75
  35. package/dist/modules/order/grid_reconcile_internal.js +16 -4
  36. package/dist/modules/order/index.d.ts +29 -6
  37. package/dist/modules/order/index.js +5 -5
  38. package/dist/modules/order/lifecycle.js +3 -3
  39. package/dist/modules/order/manager.d.ts +36 -24
  40. package/dist/modules/order/manager.js +159 -39
  41. package/dist/modules/order/placement_lock.d.ts +30 -0
  42. package/dist/modules/order/placement_lock.js +48 -0
  43. package/dist/modules/order/sync_engine.d.ts +66 -118
  44. package/dist/modules/order/sync_engine.js +118 -162
  45. package/dist/modules/order/utils/math.d.ts +7 -3
  46. package/dist/modules/order/utils/math.js +7 -3
  47. package/dist/modules/order/utils/order.d.ts +79 -42
  48. package/dist/modules/order/utils/order.js +183 -86
  49. package/dist/modules/order/utils/system.d.ts +192 -8
  50. package/dist/modules/order/utils/system.js +534 -34
  51. package/dist/modules/paths.d.ts +1 -0
  52. package/dist/modules/paths.js +1 -0
  53. package/dist/modules/timing_policy.js +4 -2
  54. package/dist/modules/types.d.ts +49 -27
  55. package/dist/pm2.js +126 -0
  56. package/dist/unlock.js +26 -1
  57. package/docs/COW_INVARIANTS.md +5 -1
  58. package/docs/DEXBOT_COMPARISON.md +5 -5
  59. package/docs/EVOLUTION.md +10 -8
  60. package/docs/FUND_MOVEMENT_AND_ACCOUNTING.md +1 -1
  61. package/docs/GRID_RECONCILE.md +3 -3
  62. package/docs/ORDER_ENGINE_POST_1.0_RETROSPECTIVE.md +192 -31
  63. package/docs/README.md +1 -1
  64. package/docs/architecture.md +26 -8
  65. package/modules/README.md +4 -0
  66. package/package.json +4 -3
@@ -31,16 +31,16 @@
31
31
  *
32
32
  * SUBSYSTEM MODULES:
33
33
  * 1. manager.ts - OrderManager class (order lifecycle, fund tracking)
34
- * 2. grid.ts - Grid class (grid creation, synchronization, health)
34
+ * 2. grid.ts - Grid engine (grid creation, synchronization, health)
35
35
  * 3. utils/math.ts, utils/order.ts, utils/system.ts - Helper functions by concern
36
- * 4. format.ts - Numeric formatting (17 functions for consistent display)
36
+ * 4. format.ts - Numeric formatting (18 functions for consistent display)
37
37
  * 5. accounting.ts - Accountant class (fund calculations and reconciliation)
38
38
  * 6. logger.ts - Logger class (structured, color-coded output)
39
39
  * 7. async_lock.ts - AsyncLock class (race condition prevention)
40
40
  * 8. working_grid.ts - WorkingGrid class (copy-on-write grid state)
41
41
  * 9. export.ts - Trade history extraction and CSV export
42
42
  * 10. grid_reconcile.ts - Grid reconciliation against chain (startup + maintenance)
43
- * 11. strategy.ts - Strategy configuration and parsing
43
+ * 11. strategy.ts - StrategyEngine class (boundary-crawl rebalancing, target grid)
44
44
  * 12. sync_engine.ts - Real-time blockchain synchronization
45
45
  *
46
46
  * ===============================================================================
@@ -108,10 +108,32 @@ declare const utils: {
108
108
  pivot: number | null;
109
109
  threshold?: number | null;
110
110
  };
111
+ isRefusedLevelRefillBlocked(manager: import("../types.js").OrderManagerLike | null | undefined, price: unknown, type: unknown): {
112
+ blocked: boolean;
113
+ level: number | null;
114
+ };
115
+ evaluateLastFillGuard(manager: import("../types.js").OrderManagerLike | null | undefined, price: number, type: unknown, pivotPrice: number | null, pivotType: string | null): {
116
+ blocked: boolean;
117
+ pivot: number | null;
118
+ threshold?: number | null;
119
+ bandExempt?: boolean;
120
+ refusedLevel?: boolean;
121
+ };
122
+ isLastFillBandSellExempt(manager: import("../types.js").OrderManagerLike | null | undefined, price: unknown): boolean;
111
123
  isLastFillPlacementBlocked(manager: import("../types.js").OrderManagerLike | null | undefined, price: unknown, type: unknown): {
112
124
  blocked: boolean;
113
125
  pivot: number | null;
114
- reason?: "direction" | "same-level";
126
+ reason?: "direction" | "same-level" | "refused-level";
127
+ };
128
+ readFillPipelineState(source: unknown): system.FillPipelineState;
129
+ resolveGridUpdateBlockers(source: unknown, options?: {
130
+ now?: number;
131
+ }): system.GridUpdateBlocker[];
132
+ noteGridUpdateBlockers(source: unknown, blockers: system.GridUpdateBlocker[] | null | undefined, options?: {
133
+ limit?: number;
134
+ }): {
135
+ cycles: number;
136
+ escalate: boolean;
115
137
  };
116
138
  hasUnsettledFills(source: unknown): {
117
139
  unsettled: boolean;
@@ -135,6 +157,7 @@ declare const utils: {
135
157
  } | null;
136
158
  setLastFillPivot(manager: import("../types.js").OrderManagerLike, type: string, price: unknown, provenance: "fill" | "book", atMs?: number): boolean;
137
159
  resetLastFillPivot(manager: import("../types.js").OrderManagerLike, reason?: string): boolean;
160
+ expireLastFillGuardReferences(manager: import("../types.js").OrderManagerLike, reason?: string): void;
138
161
  restoreLastFillPivot(manager: import("../types.js").OrderManagerLike, persisted: unknown, options?: {
139
162
  now?: number;
140
163
  }): boolean;
@@ -213,7 +236,7 @@ declare const utils: {
213
236
  reviveVirtualSlotFromChain: typeof order.reviveVirtualSlotFromChain;
214
237
  attributeUnmatchedFillToGrid: typeof order.attributeUnmatchedFillToGrid;
215
238
  getLivePendingBroadcasts: typeof order.getLivePendingBroadcasts;
216
- buildFillKey: typeof order.buildFillKey;
239
+ buildFillKey: typeof import("./fill_ledger.js").fillKeyOf;
217
240
  correctOrderPriceOnChain: typeof order.correctOrderPriceOnChain;
218
241
  correctAllPriceMismatches: typeof order.correctAllPriceMismatches;
219
242
  _validatePriceCorrectionEntry: typeof order._validatePriceCorrectionEntry;
@@ -274,6 +297,7 @@ declare const utils: {
274
297
  duplicateOrphanLogInfo: typeof order.duplicateOrphanLogInfo;
275
298
  chainOrderUnchangedFromCache: typeof order.chainOrderUnchangedFromCache;
276
299
  detectCrossedBookPlan: typeof order.detectCrossedBookPlan;
300
+ describeMarketCrossingActions: typeof order.describeMarketCrossingActions;
277
301
  collectKnownOnChainOrderIds: typeof order.collectKnownOnChainOrderIds;
278
302
  collectEdgePinnedFillIds: typeof order.collectEdgePinnedFillIds;
279
303
  edgeOrderIdSet: typeof order.edgeOrderIdSet;
@@ -284,7 +308,6 @@ declare const utils: {
284
308
  resolveLiveEdgeAnchorPrice: typeof order.resolveLiveEdgeAnchorPrice;
285
309
  compareEdge: typeof order.compareEdge;
286
310
  collectRefillSlotIds: typeof order.collectRefillSlotIds;
287
- recordOrderPlacement: typeof order.recordOrderPlacement;
288
311
  isFreshlyPlacedOrder: typeof order.isFreshlyPlacedOrder;
289
312
  _filterUnmatchedChainOrders: typeof order._filterUnmatchedChainOrders;
290
313
  getBtsSide: typeof math.getBtsSide;
@@ -31,22 +31,22 @@
31
31
  *
32
32
  * SUBSYSTEM MODULES:
33
33
  * 1. manager.ts - OrderManager class (order lifecycle, fund tracking)
34
- * 2. grid.ts - Grid class (grid creation, synchronization, health)
34
+ * 2. grid.ts - Grid engine (grid creation, synchronization, health)
35
35
  * 3. utils/math.ts, utils/order.ts, utils/system.ts - Helper functions by concern
36
- * 4. format.ts - Numeric formatting (17 functions for consistent display)
36
+ * 4. format.ts - Numeric formatting (18 functions for consistent display)
37
37
  * 5. accounting.ts - Accountant class (fund calculations and reconciliation)
38
38
  * 6. logger.ts - Logger class (structured, color-coded output)
39
39
  * 7. async_lock.ts - AsyncLock class (race condition prevention)
40
40
  * 8. working_grid.ts - WorkingGrid class (copy-on-write grid state)
41
41
  * 9. export.ts - Trade history extraction and CSV export
42
42
  * 10. grid_reconcile.ts - Grid reconciliation against chain (startup + maintenance)
43
- * 11. strategy.ts - Strategy configuration and parsing
43
+ * 11. strategy.ts - StrategyEngine class (boundary-crawl rebalancing, target grid)
44
44
  * 12. sync_engine.ts - Real-time blockchain synchronization
45
45
  *
46
46
  * ===============================================================================
47
47
  */
48
- // Runner may contain I/O and larger logic; require lazily to avoid loading it
49
- // during small unit tests. Expose a lazy accessor instead.
48
+ // The logger is required lazily: it pulls in console/formatting setup that small
49
+ // unit tests do not need, and `logger` is exposed as a lazy getter below.
50
50
  import { createRequire } from 'node:module';
51
51
  const require = createRequire(import.meta.url);
52
52
  import { OrderManager } from './manager.js';
@@ -884,9 +884,9 @@ export class LifecycleRegistry {
884
884
  record.revision += 1;
885
885
  // Dropping a pending entry means the CREATE resolved. If the record
886
886
  // still reads `broadcasting`, nothing was observed afterwards, so the
887
- // slot is a clean intent again. (An ABANDONED entry goes through
888
- // `expirePending`, which leaves `unknown` instead — the two cases must
889
- // not collapse into one.)
887
+ // slot is a clean intent again. (A pending entry that expires in the
888
+ // manager's TTL sweep goes through `_expirePendingBroadcast`, which
889
+ // leaves `unknown` instead — the two cases must not collapse into one.)
890
890
  if (record.phase === 'broadcasting')
891
891
  record.phase = 'intent';
892
892
  if (!record.orderId && !record.slotId)
@@ -9,8 +9,8 @@
9
9
  * ===============================================================================
10
10
  *
11
11
  * SECTION 1: EXTERNAL DEPENDENCIES
12
- * SECTION 2: COW REBALANCE ENGINE
13
- * SECTION 3: ORDER MANAGER CLASS
12
+ * SECTION 2: COW REBALANCE ENGINE - COWRebalanceEngine class (exported)
13
+ * SECTION 3: ORDER MANAGER CLASS - OrderManager class (exported)
14
14
  * ===============================================================================
15
15
  */
16
16
  import { WorkingGrid } from './working_grid.js';
@@ -195,6 +195,7 @@ declare class OrderManager implements OrderManagerLike {
195
195
  _pauseFundRecalc: number;
196
196
  _pauseFundRecalcWatchdog: ReturnType<typeof setTimeout> | null;
197
197
  _fillBatchInFlight: number;
198
+ _gridUpdateBlockedCycles: number;
198
199
  _pauseRecalcLogging: boolean;
199
200
  _pauseRecalcLoggingWatchdog: ReturnType<typeof setTimeout> | null;
200
201
  _throwOnIllegalState: boolean;
@@ -260,6 +261,9 @@ declare class OrderManager implements OrderManagerLike {
260
261
  _lastFilledPrice: number | null;
261
262
  _lastFilledType: string | null;
262
263
  _lastFilledAt: number;
264
+ _lastRefusedFillPrice: number | null;
265
+ _lastRefusedFillType: string | null;
266
+ _lastRefusedFillAt: number;
263
267
  /** Timestamp of the fill reference whose read-time expiry was already logged (one line per expired value). */
264
268
  _lastFillPivotExpiryLoggedAt: number;
265
269
  lastFillPivotSource: 'fill' | 'book' | null;
@@ -365,7 +369,8 @@ declare class OrderManager implements OrderManagerLike {
365
369
  * `isPlacementLeaseCurrent()` before mutating.
366
370
  *
367
371
  * Lock hierarchy: acquire placement BEFORE `_gridLock`; never acquire it
368
- * while holding `_gridLock` (Level 0.5 — see `manageLocks`).
372
+ * while holding `_gridLock` (Level 0.5 — see the constructor's canonical
373
+ * lock-hierarchy block in this file).
369
374
  *
370
375
  * @returns `null` when the region could not be acquired; the caller must
371
376
  * defer/abort its broadcast.
@@ -452,14 +457,6 @@ declare class OrderManager implements OrderManagerLike {
452
457
  * @returns {number} Applied (already-in-snapshot) amount, 0..filledInt
453
458
  */
454
459
  consumeChainSizeAppliedFillAmount(orderId: string, filledInt: number, maxAgeMs?: number): number;
455
- /**
456
- * Boolean compatibility wrapper for {@link consumeChainSizeAppliedFillAmount}.
457
- * @param {string} orderId - Chain order id
458
- * @param {number} filledInt - Base-amount delta in chain integer units
459
- * @param {number} [maxAgeMs] - Marker freshness bound
460
- * @returns {boolean} true when any part of the fill was already applied
461
- */
462
- consumeChainSizeAppliedFill(orderId: string, filledInt: number, maxAgeMs?: number): boolean;
463
460
  /**
464
461
  * Merge persisted pass-1 markers into the in-memory set (recovery reload).
465
462
  * Live markers win on conflict: they may already be partially consumed,
@@ -709,7 +706,7 @@ declare class OrderManager implements OrderManagerLike {
709
706
  */
710
707
  resumeRecalcLogging(): void;
711
708
  /**
712
- * @param {Array<import('./types').Order>} orders
709
+ * @param {Array<import('../types.js').Order>} orders
713
710
  * @param {Object} info
714
711
  * @returns {Promise<any>}
715
712
  */
@@ -826,7 +823,7 @@ declare class OrderManager implements OrderManagerLike {
826
823
  _peekWorkingGrid(): WorkingGrid | null;
827
824
  _syncWorkingGridFromMasterMutation(orderId: string, context: string): void;
828
825
  /**
829
- * @param {Array<import('./types').Order>} updates - Order updates to apply
826
+ * @param {Array<import('../types.js').Order>} updates - Order updates to apply
830
827
  * @param {string} [context] - Update context label
831
828
  * @param {unknown} [options]
832
829
  * @returns {Promise<boolean>}
@@ -883,14 +880,14 @@ declare class OrderManager implements OrderManagerLike {
883
880
  reason: string;
884
881
  }>;
885
882
  /**
886
- * @param {Array<import('./types').Order>} orders - Filled orders
883
+ * @param {Array<import('../types.js').Order>} orders - Filled orders
887
884
  * @param {Set<string>} [excl] - Order IDs to exclude
888
885
  * @param {Object} [options]
889
886
  * @returns {Promise<any>}
890
887
  */
891
888
  processFilledOrders(orders: COWFillLike[], excl: Set<string>, options?: UnknownRecord): Promise<RebalanceResult>;
892
889
  /**
893
- * @returns {Array<import('./types').Order>}
890
+ * @returns {Array<import('../types.js').Order>}
894
891
  */
895
892
  getInitialOrdersToActivate(): ManagedOrder[];
896
893
  /**
@@ -933,19 +930,16 @@ declare class OrderManager implements OrderManagerLike {
933
930
  * Also used when the boundary is (re)anchored outside the fill path (grid
934
931
  * reset / recenter / rejected-snapshot rebuild): those records belong to
935
932
  * the previous generation, and applying their relative deltas onto a fresh
936
- * anchor would double-count movement the anchor already contains.
933
+ * anchor would double-count movement the anchor already contains. That is
934
+ * the explicit allowed-loss path: the grid generation is being discarded
935
+ * (rebuild, rejected snapshot, restart replay), so the relative deltas no
936
+ * longer have a geometry to apply onto.
937
937
  *
938
938
  * Marks the grid dirty so the cleared array reaches disk even on paths
939
939
  * that do not otherwise persist.
940
940
  *
941
941
  * @param {string} reason - Log/debug label for the drop
942
- */
943
- /**
944
- * Drop ALL owed fill-crawl records.
945
- *
946
- * This is the explicit allowed-loss path: the grid generation is being
947
- * discarded (rebuild, rejected snapshot, restart replay), so the relative
948
- * deltas no longer have a geometry to apply onto.
942
+ * @param {string} detail - Extra context appended to the drop log line
949
943
  */
950
944
  _clearPendingFillCrawls(reason?: string, detail?: string): void;
951
945
  /**
@@ -1037,6 +1031,17 @@ declare class OrderManager implements OrderManagerLike {
1037
1031
  * edge. Skipping keeps the reference on the last WINDOW trade, matching
1038
1032
  * the crawl's classification (collectEdgePinnedFillIds is the shared
1039
1033
  * definition).
1034
+ *
1035
+ * IN-BAND FILLS ARE SKIPPED TOO (same rule, completed). A slot the CURRENT
1036
+ * geometry classifies as gap-band holds a stranded residual — an order the
1037
+ * engine has already declared out of place ("placed_order_in_band") — not a
1038
+ * window trade. Live: a sweep crawled the boundary over a resting sell,
1039
+ * that stranded sell then partially filled 11s later, and the fill armed the
1040
+ * pivot at the top of the band the geometry had just derived. Every SELL in
1041
+ * the band was then `<= pivot`, so the counter-orders the sweep owed could
1042
+ * never be placed. The eligibility rule (§9.6 "Only a window trade may
1043
+ * become the pivot") is applied at this single writer: edge-pinned here,
1044
+ * in-band here, off-market distance in setLastFillPivot.
1040
1045
  * @param {Array} fills
1041
1046
  */
1042
1047
  recordLastFilledPrices(fills: COWFillLike[]): void;
@@ -1070,6 +1075,7 @@ declare class OrderManager implements OrderManagerLike {
1070
1075
  partialsMoved: number;
1071
1076
  stall?: import("../types.js").SpreadCorrectionStall;
1072
1077
  transient?: boolean;
1078
+ excessAfter?: number;
1073
1079
  }>;
1074
1080
  /**
1075
1081
  * @param {Function} batchCb - Batch callback
@@ -1121,7 +1127,7 @@ declare class OrderManager implements OrderManagerLike {
1121
1127
  */
1122
1128
  clearStalePipelineOperations(): boolean;
1123
1129
  /**
1124
- * @param {Map<string, import('./types').Order>} targetGrid
1130
+ * @param {Map<string, import('../types.js').Order>} targetGrid
1125
1131
  * @param {number} targetBoundary
1126
1132
  * @returns {Object}
1127
1133
  */
@@ -1193,11 +1199,17 @@ declare class OrderManager implements OrderManagerLike {
1193
1199
  * @param {boolean} [options.skipBroadcastWait] - Set by the COW re-plan path,
1194
1200
  * which runs INSIDE its own startBroadcasting() region and must not wait
1195
1201
  * on the flag it holds itself.
1202
+ * @param {boolean} [options.holdPlanRegion] - Claim the exclusive placement
1203
+ * region before planning and ride it on the result, so the plan→broadcast
1204
+ * window is serialized against other planners. Set by the callers that are
1205
+ * guaranteed to execute the result (fill path, post-recovery rebalance).
1206
+ * Planner-only callers (unit fixtures) leave it off and stay lease-free.
1196
1207
  * @returns {Promise<any>}
1197
1208
  */
1198
1209
  performSafeRebalance(fills?: COWFillLike[], excludeIds?: Set<string>, options?: {
1199
1210
  skipBroadcastWait?: boolean;
1200
1211
  deferIfBroadcasting?: boolean;
1212
+ holdPlanRegion?: boolean;
1201
1213
  [key: string]: unknown;
1202
1214
  }): Promise<RebalanceResult>;
1203
1215
  _applySafeRebalanceCOW(fills?: COWFillLike[], excludeIds?: Set<string>): Promise<RebalanceResult>;