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.
- package/CHANGELOG.md +16 -0
- package/README.md +1 -0
- package/analysis/README.md +49 -11
- package/analysis/bot_fitting/README.md +12 -0
- package/analysis/tradingview/README.md +2 -2
- package/analysis/trend_detection/DYNAMIC_WEIGHT_RESEARCH.md +10 -36
- package/analysis/trend_detection/README.md +31 -0
- package/claw/package.json +1 -1
- package/claw/runtimes/openclaw-plugin/openclaw.plugin.json +1 -1
- package/claw/runtimes/openclaw-plugin/package.json +1 -1
- package/dist/analysis/account_resolver.js +13 -1
- package/dist/analysis/analyze_dynamic_weight.js +0 -3
- package/dist/analysis/bot_fitting/backtest_ama_sweep.js +51 -7
- package/dist/analysis/bot_fitting/backtest_bot_fitting.js +65 -7
- package/dist/analysis/bot_fitting/backtest_lookback_drawdown.d.ts +21 -0
- package/dist/analysis/bot_fitting/backtest_lookback_drawdown.js +315 -0
- package/dist/analysis/bot_key_utils.js +3 -13
- package/dist/analysis/fills_cache.d.ts +64 -0
- package/dist/analysis/fills_cache.js +254 -0
- package/dist/analysis/fills_source.js +5 -2
- package/dist/analysis/pnl_report.d.ts +39 -0
- package/dist/analysis/pnl_report.js +325 -0
- package/dist/analysis/resolve_source.d.ts +0 -1
- package/dist/analysis/trade_profitability.d.ts +11 -2
- package/dist/analysis/trade_profitability.js +187 -61
- package/dist/analysis/tradingview/analyze_tradingview.js +3 -5
- package/dist/analysis/tradingview/grid_reset_config.d.ts +2 -0
- package/dist/analysis/tradingview/grid_reset_config.js +18 -1
- package/dist/analysis/tradingview/grid_reset_sim.d.ts +1 -0
- package/dist/analysis/tradingview/grid_reset_sim.js +38 -2
- package/dist/analysis/tradingview/tradingview_uplot_chart_generator.js +2 -1
- package/dist/analysis/trend_detection/backtest_ama_slope_huber.d.ts +102 -0
- package/dist/analysis/trend_detection/backtest_ama_slope_huber.js +725 -0
- package/dist/analysis/trend_detection/dynamic_weight_chart_generator.js +22 -108
- package/dist/analysis/trend_detection/huber_scale_variants.d.ts +34 -0
- package/dist/analysis/trend_detection/huber_scale_variants.js +176 -0
- package/dist/dexbot.js +6 -3
- package/dist/market_adapter/core/market_adapter_service.d.ts +15 -0
- package/dist/market_adapter/core/market_adapter_service.js +64 -5
- package/dist/market_adapter/core/strategies/ama.d.ts +1 -1
- package/dist/market_adapter/core/strategies/ama.js +5 -28
- package/dist/market_adapter/core/strategies/dynamic_weight_series.d.ts +2 -2
- package/dist/market_adapter/core/strategies/dynamic_weight_series.js +2 -2
- package/dist/market_adapter/inputs/fetch_cex_synthetic_data.js +1 -2
- package/dist/market_adapter/log_format.js +1 -2
- package/dist/market_adapter/market_adapter.d.ts +0 -1
- package/dist/market_adapter/market_adapter.js +2 -27
- package/dist/modules/constants.d.ts +3 -1
- package/dist/modules/constants.js +39 -15
- package/dist/modules/dexbot_maintenance_runtime.js +12 -0
- package/dist/modules/order/accounting.js +25 -0
- package/dist/modules/order/format.d.ts +35 -15
- package/dist/modules/order/format.js +62 -16
- package/dist/modules/order/manager.d.ts +1 -0
- package/dist/modules/order/manager.js +22 -1
- package/dist/modules/order/sync_engine.js +15 -1
- package/dist/modules/order/utils/order.d.ts +21 -1
- package/dist/modules/order/utils/order.js +80 -2
- package/dist/modules/paths.d.ts +2 -0
- package/dist/modules/paths.js +2 -0
- package/dist/modules/utils/time_range.d.ts +15 -0
- package/dist/modules/utils/time_range.js +18 -0
- package/dist/scripts/analyze-orders.js +1 -44
- package/dist/scripts/chart_command.js +3 -4
- package/dist/scripts/pnl.d.ts +3 -0
- package/dist/scripts/pnl.js +40 -0
- package/dist/unlock.js +34 -0
- package/docs/DEXBOT_COMPARISON.md +3 -3
- package/docs/EVOLUTION.md +10 -9
- package/docs/FUND_MOVEMENT_AND_ACCOUNTING.md +1 -1
- package/docs/GRID_RECALCULATION.md +12 -15
- package/docs/README.md +2 -2
- package/docs/WORKFLOW.md +1 -0
- package/market_adapter/README.md +4 -26
- package/package.json +1 -1
- package/scripts/README.md +14 -0
|
@@ -140,6 +140,21 @@ declare class MarketAdapterService {
|
|
|
140
140
|
thresholdCrossed: boolean;
|
|
141
141
|
shouldTrigger: boolean;
|
|
142
142
|
};
|
|
143
|
+
/**
|
|
144
|
+
* Number of consecutive confirming bars the slope-delta trigger requires.
|
|
145
|
+
* Resolves per-bot/market override, else the global enable + value, else 1
|
|
146
|
+
* (legacy fire-on-first-crossing).
|
|
147
|
+
*/
|
|
148
|
+
resolveAmaSlopePersistBars(cfg: any): number;
|
|
149
|
+
/**
|
|
150
|
+
* Advance the slope-delta persistence counter on one actionable cycle and
|
|
151
|
+
* report whether the gate is satisfied. Mutates botState counters (persisted
|
|
152
|
+
* across restarts). Caller clears them on any successful reset.
|
|
153
|
+
*/
|
|
154
|
+
advanceAmaSlopePersistence(details: any, cfg: any, botState: any): {
|
|
155
|
+
shouldTrigger: boolean;
|
|
156
|
+
persistBars: number;
|
|
157
|
+
};
|
|
143
158
|
normalizePersistedBotState(botState: any, lookbackBars: any): any;
|
|
144
159
|
extractPersistedDynamicGridState(snapshot: any, lookbackBars: any): {
|
|
145
160
|
gridCenterPrice: number | null;
|
|
@@ -67,6 +67,11 @@ function normalizePersistedAmaSlopeDiagnostics(data, lookbackBars) {
|
|
|
67
67
|
const thresholdPercent = convertSlopePercentToPerBar(data.amaSlopeThresholdPercent, lookbackBars, mode);
|
|
68
68
|
normalized.amaSlopeDeltaPercent = Number.isFinite(deltaPercent) ? deltaPercent : null;
|
|
69
69
|
normalized.amaSlopeThresholdPercent = Number.isFinite(thresholdPercent) ? thresholdPercent : null;
|
|
70
|
+
// Persistence-gate state carried across restarts (see advanceAmaSlopePersistence).
|
|
71
|
+
const persistCount = Number(data.amaSlopePersistCount);
|
|
72
|
+
normalized.amaSlopePersistCount = Number.isFinite(persistCount) && persistCount > 0 ? Math.floor(persistCount) : 0;
|
|
73
|
+
const persistDir = Number(data.amaSlopePersistDir);
|
|
74
|
+
normalized.amaSlopePersistDir = persistDir === 1 ? 1 : (persistDir === -1 ? -1 : 0);
|
|
70
75
|
return normalized;
|
|
71
76
|
}
|
|
72
77
|
function computeGridPriceOffsetPlan(bot, amaSlope) {
|
|
@@ -661,6 +666,53 @@ class MarketAdapterService {
|
|
|
661
666
|
shouldTrigger: thresholdCrossed,
|
|
662
667
|
};
|
|
663
668
|
}
|
|
669
|
+
/**
|
|
670
|
+
* Number of consecutive confirming bars the slope-delta trigger requires.
|
|
671
|
+
* Resolves per-bot/market override, else the global enable + value, else 1
|
|
672
|
+
* (legacy fire-on-first-crossing).
|
|
673
|
+
*/
|
|
674
|
+
resolveAmaSlopePersistBars(cfg) {
|
|
675
|
+
const explicit = Number(cfg?.amaSlope?.persistBars ?? cfg?.amaSlopePersistBars);
|
|
676
|
+
if (Number.isFinite(explicit) && explicit >= 1)
|
|
677
|
+
return Math.round(explicit);
|
|
678
|
+
const enabled = cfg?.amaSlope?.persistEnabled === true
|
|
679
|
+
|| cfg?.amaSlopePersistEnabled === true
|
|
680
|
+
|| MARKET_ADAPTER.AMA_SLOPE_PERSIST_ENABLED === true;
|
|
681
|
+
if (!enabled)
|
|
682
|
+
return 1;
|
|
683
|
+
const bars = Number(MARKET_ADAPTER.AMA_SLOPE_PERSIST_BARS);
|
|
684
|
+
return Number.isFinite(bars) && bars >= 1 ? Math.round(bars) : 1;
|
|
685
|
+
}
|
|
686
|
+
/**
|
|
687
|
+
* Advance the slope-delta persistence counter on one actionable cycle and
|
|
688
|
+
* report whether the gate is satisfied. Mutates botState counters (persisted
|
|
689
|
+
* across restarts). Caller clears them on any successful reset.
|
|
690
|
+
*/
|
|
691
|
+
advanceAmaSlopePersistence(details, cfg, botState) {
|
|
692
|
+
const persistBars = this.resolveAmaSlopePersistBars(cfg);
|
|
693
|
+
const crossed = !!details?.thresholdCrossed;
|
|
694
|
+
if (persistBars <= 1) {
|
|
695
|
+
botState.amaSlopePersistCount = 0;
|
|
696
|
+
botState.amaSlopePersistDir = 0;
|
|
697
|
+
return { shouldTrigger: crossed, persistBars };
|
|
698
|
+
}
|
|
699
|
+
if (!crossed) {
|
|
700
|
+
botState.amaSlopePersistCount = 0;
|
|
701
|
+
botState.amaSlopePersistDir = 0;
|
|
702
|
+
return { shouldTrigger: false, persistBars };
|
|
703
|
+
}
|
|
704
|
+
const current = Number(details?.currentSlopePct);
|
|
705
|
+
const previous = Number(details?.previousSlopePct);
|
|
706
|
+
const dir = Number.isFinite(current) && Number.isFinite(previous) ? Math.sign(current - previous) : 0;
|
|
707
|
+
const storedDirRaw = Number(botState.amaSlopePersistDir);
|
|
708
|
+
const storedDir = storedDirRaw === 1 ? 1 : (storedDirRaw === -1 ? -1 : 0);
|
|
709
|
+
const storedCountRaw = Number(botState.amaSlopePersistCount);
|
|
710
|
+
const storedCount = Number.isFinite(storedCountRaw) && storedCountRaw > 0 ? Math.floor(storedCountRaw) : 0;
|
|
711
|
+
const count = (dir !== 0 && dir === storedDir) ? storedCount + 1 : 1;
|
|
712
|
+
botState.amaSlopePersistDir = dir;
|
|
713
|
+
botState.amaSlopePersistCount = count;
|
|
714
|
+
return { shouldTrigger: count >= persistBars, persistBars };
|
|
715
|
+
}
|
|
664
716
|
normalizePersistedBotState(botState, lookbackBars) {
|
|
665
717
|
if (!botState || typeof botState !== 'object')
|
|
666
718
|
return {};
|
|
@@ -1109,7 +1161,7 @@ class MarketAdapterService {
|
|
|
1109
1161
|
// Retention targets, derived from the bot's own AMA parameters. Pure and
|
|
1110
1162
|
// local, so they are computed before the off-hour gate below (which
|
|
1111
1163
|
// needs the warmup target) and reused by the full path unchanged.
|
|
1112
|
-
const amaWarmupBars = getAmaWarmupBars(botAma.erPeriod, botAma.slowPeriod, lookbackBars, botAma.fastPeriod
|
|
1164
|
+
const amaWarmupBars = getAmaWarmupBars(botAma.erPeriod, botAma.slowPeriod, lookbackBars, botAma.fastPeriod);
|
|
1113
1165
|
const analysisKeepCount = amaWarmupBars + 1;
|
|
1114
1166
|
// Retain one extra raw candle so the closed-candle analysis window still keeps a
|
|
1115
1167
|
// full warmup/history set when the newest bucket is the current in-progress bar.
|
|
@@ -1989,7 +2041,6 @@ class MarketAdapterService {
|
|
|
1989
2041
|
erPeriod: botAma.erPeriod,
|
|
1990
2042
|
fastPeriod: botAma.fastPeriod,
|
|
1991
2043
|
slowPeriod: botAma.slowPeriod,
|
|
1992
|
-
erSmoothPeriod: botAma.erSmoothPeriod ?? 0,
|
|
1993
2044
|
},
|
|
1994
2045
|
pendingClosedCandle,
|
|
1995
2046
|
});
|
|
@@ -2121,6 +2172,13 @@ class MarketAdapterService {
|
|
|
2121
2172
|
// trigger/snapshot write happened on a stale-but-new cycle.
|
|
2122
2173
|
triggerSuppressedReason = 'stale_candle_data';
|
|
2123
2174
|
}
|
|
2175
|
+
// Slope-delta persistence gate (trigger B). Advances only on actionable
|
|
2176
|
+
// cycles; any successful reset clears it via advanceTriggeredBotState.
|
|
2177
|
+
const amaSlopePersistence = (!staleData && !hasUnresolvedCandleGaps)
|
|
2178
|
+
? this.advanceAmaSlopePersistence(amaSlopeResetDetails, cfg, botState)
|
|
2179
|
+
: { shouldTrigger: false, persistBars: this.resolveAmaSlopePersistBars(cfg) };
|
|
2180
|
+
const amaSlopeShouldTrigger = amaSlopePersistence.shouldTrigger;
|
|
2181
|
+
const amaSlopePersistBars = amaSlopePersistence.persistBars;
|
|
2124
2182
|
const buildDynamicGridOptions = (options = {}) => {
|
|
2125
2183
|
const payload = {
|
|
2126
2184
|
gridCenterPrice: options.gridCenterPrice ?? null, // explicit baseline if provided
|
|
@@ -2179,6 +2237,8 @@ class MarketAdapterService {
|
|
|
2179
2237
|
: botState.amaSlopeDeltaPercent ?? null;
|
|
2180
2238
|
botState.amaSlopeThresholdPercent = amaSlopeThresholdPercent;
|
|
2181
2239
|
botState.amaSlopePercentMode = AMA_SLOPE_PERCENT_MODE_PER_BAR;
|
|
2240
|
+
botState.amaSlopePersistCount = 0;
|
|
2241
|
+
botState.amaSlopePersistDir = 0;
|
|
2182
2242
|
botState.triggerCount = Number(botState.triggerCount || 0) + 1;
|
|
2183
2243
|
if (canApplyDynamicWeights && dynamicWeightsPayload) {
|
|
2184
2244
|
botState.effectiveWeights = dynamicWeightsPayload.effectiveWeights || null;
|
|
@@ -2296,7 +2356,7 @@ class MarketAdapterService {
|
|
|
2296
2356
|
}
|
|
2297
2357
|
}
|
|
2298
2358
|
}
|
|
2299
|
-
if (!triggered && !triggerSuppressedReason && isGridRangeScalingWhitelisted &&
|
|
2359
|
+
if (!triggered && !triggerSuppressedReason && isGridRangeScalingWhitelisted && amaSlopeShouldTrigger) {
|
|
2300
2360
|
const amaSlopePersisted = persistDynamicGridSnapshot(centerPrice);
|
|
2301
2361
|
if (!amaSlopePersisted) {
|
|
2302
2362
|
triggerSuppressedReason = 'ama_slope_persist_failed';
|
|
@@ -2308,6 +2368,7 @@ class MarketAdapterService {
|
|
|
2308
2368
|
reason: 'market_adapter_ama_slope_delta_threshold',
|
|
2309
2369
|
thresholdPercent: amaSlopeThresholdPercent,
|
|
2310
2370
|
deltaPercent: amaSlopeDeltaPercent,
|
|
2371
|
+
amaSlopePersistBars,
|
|
2311
2372
|
previousAmaSlope,
|
|
2312
2373
|
previousGridResetAmaSlope,
|
|
2313
2374
|
amaSlope,
|
|
@@ -2428,7 +2489,6 @@ class MarketAdapterService {
|
|
|
2428
2489
|
erPeriod: botAma.erPeriod,
|
|
2429
2490
|
fastPeriod: botAma.fastPeriod,
|
|
2430
2491
|
slowPeriod: botAma.slowPeriod,
|
|
2431
|
-
erSmoothPeriod: botAma.erSmoothPeriod ?? 0,
|
|
2432
2492
|
},
|
|
2433
2493
|
amaComparison,
|
|
2434
2494
|
lastDeltaPercent: deltaPercent,
|
|
@@ -2517,7 +2577,6 @@ class MarketAdapterService {
|
|
|
2517
2577
|
erPeriod: botAma.erPeriod,
|
|
2518
2578
|
fastPeriod: botAma.fastPeriod,
|
|
2519
2579
|
slowPeriod: botAma.slowPeriod,
|
|
2520
|
-
erSmoothPeriod: botAma.erSmoothPeriod ?? 0,
|
|
2521
2580
|
},
|
|
2522
2581
|
atr,
|
|
2523
2582
|
weightVariance,
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
declare function getAmaWarmupBars(erPeriod: any, slowPeriod: any, lookbackBars: any, fastPeriod: any
|
|
1
|
+
declare function getAmaWarmupBars(erPeriod: any, slowPeriod: any, lookbackBars: any, fastPeriod: any): number;
|
|
2
2
|
declare function calculateAMA(closes: any, params: any): any[];
|
|
3
3
|
export { calculateAMA, getAmaWarmupBars };
|
|
4
4
|
//# sourceMappingURL=ama.d.ts.map
|
|
@@ -5,9 +5,6 @@ import { MARKET_ADAPTER } from '../../../modules/constants.js';
|
|
|
5
5
|
*/
|
|
6
6
|
class AMA {
|
|
7
7
|
erPeriod;
|
|
8
|
-
erSmoothPeriod;
|
|
9
|
-
erSmoothAlpha;
|
|
10
|
-
erSmoothValue;
|
|
11
8
|
fastSC;
|
|
12
9
|
slowSC;
|
|
13
10
|
prevAMA;
|
|
@@ -15,7 +12,7 @@ class AMA {
|
|
|
15
12
|
warmedUp;
|
|
16
13
|
smaSum;
|
|
17
14
|
smaCount;
|
|
18
|
-
constructor(erPeriod, fastPeriod, slowPeriod
|
|
15
|
+
constructor(erPeriod, fastPeriod, slowPeriod) {
|
|
19
16
|
if (!Number.isFinite(erPeriod) || erPeriod <= 0) {
|
|
20
17
|
throw new TypeError(`AMA erPeriod must be a positive finite number, got ${erPeriod}`);
|
|
21
18
|
}
|
|
@@ -26,10 +23,6 @@ class AMA {
|
|
|
26
23
|
throw new TypeError(`AMA slowPeriod must be a positive finite number, got ${slowPeriod}`);
|
|
27
24
|
}
|
|
28
25
|
this.erPeriod = Math.ceil(erPeriod);
|
|
29
|
-
const esPeriod = Number(erSmoothPeriod);
|
|
30
|
-
this.erSmoothPeriod = Number.isFinite(esPeriod) && esPeriod >= 1 ? esPeriod : 0;
|
|
31
|
-
this.erSmoothAlpha = this.erSmoothPeriod > 0 ? 2 / (this.erSmoothPeriod + 1) : 0;
|
|
32
|
-
this.erSmoothValue = null;
|
|
33
26
|
this.fastSC = 2 / (fastPeriod + 1);
|
|
34
27
|
this.slowSC = 2 / (slowPeriod + 1);
|
|
35
28
|
this.prevAMA = null;
|
|
@@ -65,21 +58,13 @@ class AMA {
|
|
|
65
58
|
volatility += Math.abs(this.history[i] - this.history[i - 1]);
|
|
66
59
|
}
|
|
67
60
|
const er = volatility === 0 ? 0 : direction / volatility;
|
|
68
|
-
const
|
|
69
|
-
? (this.erSmoothValue === null
|
|
70
|
-
? er
|
|
71
|
-
: this.erSmoothValue + this.erSmoothAlpha * (er - this.erSmoothValue))
|
|
72
|
-
: er;
|
|
73
|
-
if (this.erSmoothAlpha > 0) {
|
|
74
|
-
this.erSmoothValue = effectiveER;
|
|
75
|
-
}
|
|
76
|
-
const smooth = (effectiveER * (this.fastSC - this.slowSC) + this.slowSC) ** 2;
|
|
61
|
+
const smooth = (er * (this.fastSC - this.slowSC) + this.slowSC) ** 2;
|
|
77
62
|
const ama = this.prevAMA + smooth * (price - this.prevAMA);
|
|
78
63
|
this.prevAMA = ama;
|
|
79
64
|
return ama;
|
|
80
65
|
}
|
|
81
66
|
}
|
|
82
|
-
function getAmaWarmupBars(erPeriod, slowPeriod, lookbackBars, fastPeriod
|
|
67
|
+
function getAmaWarmupBars(erPeriod, slowPeriod, lookbackBars, fastPeriod) {
|
|
83
68
|
if (!Number.isFinite(erPeriod) || erPeriod <= 0) {
|
|
84
69
|
throw new TypeError(`getAmaWarmupBars erPeriod must be a positive finite number, got ${erPeriod}`);
|
|
85
70
|
}
|
|
@@ -92,23 +77,15 @@ function getAmaWarmupBars(erPeriod, slowPeriod, lookbackBars, fastPeriod, erSmoo
|
|
|
92
77
|
if (!Number.isFinite(fastPeriod) || fastPeriod <= 0) {
|
|
93
78
|
throw new TypeError(`getAmaWarmupBars fastPeriod must be a positive finite number, got ${fastPeriod}`);
|
|
94
79
|
}
|
|
95
|
-
if (!Number.isFinite(erSmoothPeriod) || erSmoothPeriod < 0) {
|
|
96
|
-
throw new TypeError(`getAmaWarmupBars erSmoothPeriod must be a non-negative finite number, got ${erSmoothPeriod}`);
|
|
97
|
-
}
|
|
98
80
|
const safeErPeriod = Math.ceil(erPeriod);
|
|
99
81
|
const safeSlowPeriod = Math.ceil(slowPeriod);
|
|
100
82
|
const safeLookbackBars = Math.ceil(lookbackBars);
|
|
101
|
-
const safeErSmoothPeriod = erSmoothPeriod >= 1 ? erSmoothPeriod : 0;
|
|
102
83
|
const fastSC = 2 / (fastPeriod + 1);
|
|
103
84
|
const slowSC = 2 / (safeSlowPeriod + 1);
|
|
104
85
|
const deltaSC = fastSC - slowSC;
|
|
105
86
|
const scAvg = (MARKET_ADAPTER.AMA_CONVERGENCE_ER_AVG * deltaSC + slowSC) ** 2;
|
|
106
87
|
const convergenceBars = Math.ceil(Math.log(MARKET_ADAPTER.AMA_CONVERGENCE_EPSILON) / Math.log(1 - scAvg));
|
|
107
|
-
|
|
108
|
-
? Math.ceil(Math.log(MARKET_ADAPTER.AMA_CONVERGENCE_EPSILON)
|
|
109
|
-
/ Math.log(1 - (2 / (safeErSmoothPeriod + 1))))
|
|
110
|
-
: 0;
|
|
111
|
-
return safeErPeriod + convergenceBars + erSmoothConvergenceBars + safeLookbackBars;
|
|
88
|
+
return safeErPeriod + convergenceBars + safeLookbackBars;
|
|
112
89
|
}
|
|
113
90
|
function calculateAMA(closes, params) {
|
|
114
91
|
if (!params || typeof params !== 'object') {
|
|
@@ -126,7 +103,7 @@ function calculateAMA(closes, params) {
|
|
|
126
103
|
if (!Array.isArray(closes)) {
|
|
127
104
|
throw new TypeError('calculateAMA closes must be an array');
|
|
128
105
|
}
|
|
129
|
-
const indicator = new AMA(params.erPeriod, params.fastPeriod, params.slowPeriod
|
|
106
|
+
const indicator = new AMA(params.erPeriod, params.fastPeriod, params.slowPeriod);
|
|
130
107
|
return closes.map(price => indicator.update(price));
|
|
131
108
|
}
|
|
132
109
|
export { calculateAMA, getAmaWarmupBars };
|
|
@@ -13,7 +13,7 @@ declare function computeAverageAmaSlopePct(current: any, past: any, lookbackBars
|
|
|
13
13
|
* continuous and bounded rather than an order statistic.
|
|
14
14
|
*
|
|
15
15
|
* The fit is local linear over `lookbackBars` intervals (bars+1 points, the same
|
|
16
|
-
*
|
|
16
|
+
* 16h span the endpoint uses), so a window-wide regime change tilts the line
|
|
17
17
|
* continuously instead of waiting for a majority, and a lone off-trend spike is
|
|
18
18
|
* bounded rather than given full endpoint weight. Output is the log-return per
|
|
19
19
|
* bar x 100. That differs from the arithmetic per-bar return by ~beta^2/2,
|
|
@@ -37,7 +37,7 @@ declare function computeAverageAmaSlopePct(current: any, past: any, lookbackBars
|
|
|
37
37
|
*
|
|
38
38
|
* @param amaValues Full AMA series (index-addressable).
|
|
39
39
|
* @param index Bar to measure at (evaluated at the window edge).
|
|
40
|
-
* @param lookbackBars Window length in bars (fixed at
|
|
40
|
+
* @param lookbackBars Window length in bars (fixed at 16 for every estimator).
|
|
41
41
|
* @param hub Parameter block; defaults to the centralized constant.
|
|
42
42
|
* @returns %/bar, or null when the window is unusable.
|
|
43
43
|
*/
|
|
@@ -41,7 +41,7 @@ function computeAverageAmaSlopePct(current, past, lookbackBars) {
|
|
|
41
41
|
* continuous and bounded rather than an order statistic.
|
|
42
42
|
*
|
|
43
43
|
* The fit is local linear over `lookbackBars` intervals (bars+1 points, the same
|
|
44
|
-
*
|
|
44
|
+
* 16h span the endpoint uses), so a window-wide regime change tilts the line
|
|
45
45
|
* continuously instead of waiting for a majority, and a lone off-trend spike is
|
|
46
46
|
* bounded rather than given full endpoint weight. Output is the log-return per
|
|
47
47
|
* bar x 100. That differs from the arithmetic per-bar return by ~beta^2/2,
|
|
@@ -65,7 +65,7 @@ function computeAverageAmaSlopePct(current, past, lookbackBars) {
|
|
|
65
65
|
*
|
|
66
66
|
* @param amaValues Full AMA series (index-addressable).
|
|
67
67
|
* @param index Bar to measure at (evaluated at the window edge).
|
|
68
|
-
* @param lookbackBars Window length in bars (fixed at
|
|
68
|
+
* @param lookbackBars Window length in bars (fixed at 16 for every estimator).
|
|
69
69
|
* @param hub Parameter block; defaults to the centralized constant.
|
|
70
70
|
* @returns %/bar, or null when the window is unusable.
|
|
71
71
|
*/
|
|
@@ -155,7 +155,7 @@ function computeRequiredCandles(amaConfig = null, cfg = null) {
|
|
|
155
155
|
const ama = amaConfig || MARKET_ADAPTER.AMAS[MARKET_ADAPTER.DEFAULT_AMA_KEY] || MARKET_ADAPTER.AMAS.AMA3;
|
|
156
156
|
if (!ama)
|
|
157
157
|
return DEFAULT_BOOTSTRAP_LOOKBACK_HOURS;
|
|
158
|
-
const warmupBars = getAmaWarmupBars(ama.erPeriod, ama.slowPeriod, cfg?.amaSlope?.lookbackBars ?? MARKET_ADAPTER.DYNAMIC_WEIGHT_AMA_LOOKBACK_BARS, ama.fastPeriod
|
|
158
|
+
const warmupBars = getAmaWarmupBars(ama.erPeriod, ama.slowPeriod, cfg?.amaSlope?.lookbackBars ?? MARKET_ADAPTER.DYNAMIC_WEIGHT_AMA_LOOKBACK_BARS, ama.fastPeriod);
|
|
159
159
|
const analysisKeepCount = warmupBars + 1;
|
|
160
160
|
return Math.max(DEFAULT_BOOTSTRAP_LOOKBACK_HOURS, analysisKeepCount);
|
|
161
161
|
}
|
|
@@ -1134,7 +1134,6 @@ async function main() {
|
|
|
1134
1134
|
erPeriod: botAma.erPeriod,
|
|
1135
1135
|
fastPeriod: botAma.fastPeriod,
|
|
1136
1136
|
slowPeriod: botAma.slowPeriod,
|
|
1137
|
-
erSmoothPeriod: botAma.erSmoothPeriod ?? null,
|
|
1138
1137
|
} : null,
|
|
1139
1138
|
bot: botContext ? {
|
|
1140
1139
|
name: botContext.bot.name || null,
|
|
@@ -18,8 +18,7 @@ function formatLogPair(first, second, digits = 2) {
|
|
|
18
18
|
function formatAmaTuple(ama) {
|
|
19
19
|
if (!ama)
|
|
20
20
|
return 'n/a';
|
|
21
|
-
|
|
22
|
-
return `${formatLogNumber(ama.erPeriod, 0)}/${formatLogNumber(ama.fastPeriod, 1)}/${formatLogNumber(ama.slowPeriod, 1)}/es${formatLogNumber(erSmoothPeriod, 0)}`;
|
|
21
|
+
return `${formatLogNumber(ama.erPeriod, 0)}/${formatLogNumber(ama.fastPeriod, 1)}/${formatLogNumber(ama.slowPeriod, 1)}`;
|
|
23
22
|
}
|
|
24
23
|
function formatAsymmetryFactor(value, digits = 1) {
|
|
25
24
|
return Number.isFinite(value) ? `${(Number(value) * 100).toFixed(digits)}%` : 'n/a';
|
|
@@ -20,7 +20,7 @@ import { acquireFileLockSync, releaseFileLockSync } from './utils/file_lock.js';
|
|
|
20
20
|
import { updateDynamicGridSnapshotSync } from './utils/dynamic_grid_snapshot.js';
|
|
21
21
|
import { PATHS, getRecalculateTriggerFile } from '../modules/paths.js';
|
|
22
22
|
import Logger from '../modules/order/logger.js';
|
|
23
|
-
import {
|
|
23
|
+
import { roundTo } from '../modules/order/utils/math.js';
|
|
24
24
|
import { usesAmaGridPrice } from '../modules/dexbot_maintenance_runtime.js';
|
|
25
25
|
import { normalizeAtrPeriod, normalizeMaxVolatilityOffset, normalizeVolatilityThreshold, } from './core/config_normalizers.js';
|
|
26
26
|
import { resetMarketAdapterWhitelistCache, isBotWhitelisted, isBotDynamicWeightWhitelisted, isBotAsymmetricBoundsWhitelisted, } from '../modules/market_adapter_whitelist.js';
|
|
@@ -336,23 +336,6 @@ function findAmaProfileForBot(bot, ctx) {
|
|
|
336
336
|
function getAmaPresetForKey(key, profile) {
|
|
337
337
|
return normalizeAmaPreset(profile?.amas?.[key]) || normalizeAmaPreset(BUILTIN_AMAS[key]) || null;
|
|
338
338
|
}
|
|
339
|
-
function normalizeErSmoothPeriod(raw, fallback = 0) {
|
|
340
|
-
const value = Number(raw);
|
|
341
|
-
if (value === 0)
|
|
342
|
-
return 0;
|
|
343
|
-
if (Number.isFinite(value) && value >= 1)
|
|
344
|
-
return value;
|
|
345
|
-
const fallbackValue = Number(fallback);
|
|
346
|
-
return Number.isFinite(fallbackValue) && fallbackValue >= 1 ? fallbackValue : 0;
|
|
347
|
-
}
|
|
348
|
-
function resolveErSmoothPeriodForBot(bot) {
|
|
349
|
-
const raw = (bot && typeof bot.ama === 'object' && bot.ama !== null) ? bot.ama : {};
|
|
350
|
-
const globalErSmoothPeriod = normalizeErSmoothPeriod(MARKET_ADAPTER.AMA_ER_SMOOTH_FAST_PERIOD, 0);
|
|
351
|
-
if (Object.prototype.hasOwnProperty.call(raw, 'erSmoothPeriod')) {
|
|
352
|
-
return normalizeErSmoothPeriod(raw.erSmoothPeriod, globalErSmoothPeriod);
|
|
353
|
-
}
|
|
354
|
-
return globalErSmoothPeriod;
|
|
355
|
-
}
|
|
356
339
|
function getAmaFromProfilesForBot(bot, ctx, cfg) {
|
|
357
340
|
const selected = resolveAmaPresetForBot(bot, ctx, cfg);
|
|
358
341
|
if (!selected)
|
|
@@ -363,7 +346,6 @@ function getAmaFromProfilesForBot(bot, ctx, cfg) {
|
|
|
363
346
|
erPeriod: selected.erPeriod,
|
|
364
347
|
fastPeriod: selected.fastPeriod,
|
|
365
348
|
slowPeriod: selected.slowPeriod,
|
|
366
|
-
erSmoothPeriod: selected.erSmoothPeriod,
|
|
367
349
|
};
|
|
368
350
|
}
|
|
369
351
|
/**
|
|
@@ -375,7 +357,6 @@ function getAmaFromProfilesForBot(bot, ctx, cfg) {
|
|
|
375
357
|
*/
|
|
376
358
|
function resolveAmaPresetForBot(bot, ctx, cfg) {
|
|
377
359
|
const profile = findAmaProfileForBot(bot, ctx);
|
|
378
|
-
const erSmoothPeriod = resolveErSmoothPeriodForBot(bot);
|
|
379
360
|
if (!profile)
|
|
380
361
|
return null;
|
|
381
362
|
const rawGridPrice = String(bot?.gridPrice || '').trim().toLowerCase();
|
|
@@ -399,7 +380,6 @@ function resolveAmaPresetForBot(bot, ctx, cfg) {
|
|
|
399
380
|
erPeriod: selected.preset.erPeriod,
|
|
400
381
|
fastPeriod: selected.preset.fastPeriod,
|
|
401
382
|
slowPeriod: selected.preset.slowPeriod,
|
|
402
|
-
erSmoothPeriod,
|
|
403
383
|
};
|
|
404
384
|
}
|
|
405
385
|
function pairAmaKey(key, preset) {
|
|
@@ -867,7 +847,6 @@ function computeCandleStaleness(lastCandleTs, maxStaleHours) {
|
|
|
867
847
|
*/
|
|
868
848
|
function resolveAmaForBot(bot, ctx = null, cfg = null) {
|
|
869
849
|
const raw = (bot && typeof bot.ama === 'object' && bot.ama !== null) ? bot.ama : {};
|
|
870
|
-
const erSmoothPeriod = resolveErSmoothPeriodForBot(bot);
|
|
871
850
|
const fromProfiles = getAmaFromProfilesForBot(bot, ctx, cfg);
|
|
872
851
|
if (fromProfiles)
|
|
873
852
|
return fromProfiles;
|
|
@@ -875,7 +854,6 @@ function resolveAmaForBot(bot, ctx = null, cfg = null) {
|
|
|
875
854
|
erPeriod: Number(raw.erPeriod),
|
|
876
855
|
fastPeriod: Number(raw.fastPeriod),
|
|
877
856
|
slowPeriod: Number(raw.slowPeriod),
|
|
878
|
-
erSmoothPeriod,
|
|
879
857
|
enabled: true,
|
|
880
858
|
name: 'custom',
|
|
881
859
|
};
|
|
@@ -941,7 +919,6 @@ function buildAmaRecord(botAma, amaPrice) {
|
|
|
941
919
|
const erPeriod = Number(botAma?.erPeriod);
|
|
942
920
|
const fastPeriod = Number(botAma?.fastPeriod);
|
|
943
921
|
const slowPeriod = Number(botAma?.slowPeriod);
|
|
944
|
-
const erSmoothPeriod = Number(botAma?.erSmoothPeriod);
|
|
945
922
|
if (!Number.isFinite(erPeriod) || !Number.isFinite(fastPeriod) || !Number.isFinite(slowPeriod)) {
|
|
946
923
|
return [];
|
|
947
924
|
}
|
|
@@ -951,7 +928,6 @@ function buildAmaRecord(botAma, amaPrice) {
|
|
|
951
928
|
erPeriod,
|
|
952
929
|
fastPeriod,
|
|
953
930
|
slowPeriod,
|
|
954
|
-
erSmoothPeriod: Number.isFinite(erSmoothPeriod) ? erSmoothPeriod : 0,
|
|
955
931
|
value: Number.isFinite(value) ? value : null,
|
|
956
932
|
ok: Number.isFinite(value),
|
|
957
933
|
}];
|
|
@@ -1402,8 +1378,7 @@ async function runOnce(cfg, state, contextCache) {
|
|
|
1402
1378
|
if (Array.isArray(r.amaComparison) && r.amaComparison.length > 0) {
|
|
1403
1379
|
const parts = r.amaComparison.map((a) => {
|
|
1404
1380
|
const val = Number.isFinite(a.value) ? a.value.toFixed(8) : 'n/a';
|
|
1405
|
-
|
|
1406
|
-
return `${a.name}[${a.erPeriod}/${a.fastPeriod}/${a.slowPeriod}${erSmoothText}]=${val}`;
|
|
1381
|
+
return `${a.name}[${a.erPeriod}/${a.fastPeriod}/${a.slowPeriod}]=${val}`;
|
|
1407
1382
|
});
|
|
1408
1383
|
log(cfg, ` AMA active: ${parts.join(' | ')}`);
|
|
1409
1384
|
}
|
|
@@ -202,6 +202,7 @@ declare let TIMING: {
|
|
|
202
202
|
SYNC_LOCK_TIMEOUT_MS: number;
|
|
203
203
|
SYNC_SUSPECT_EMPTY_READ_LIMIT: number;
|
|
204
204
|
SYNC_EMPTY_READ_CONFIRM_DELAY_MS: number;
|
|
205
|
+
SURPLUS_CANCEL_GRACE_MS: number;
|
|
205
206
|
CONNECTION_TIMEOUT_MS: number;
|
|
206
207
|
DAEMON_STARTUP_TIMEOUT_MS: number;
|
|
207
208
|
RETRY_BACKOFF_CAP_MS: number;
|
|
@@ -410,6 +411,8 @@ declare let MARKET_ADAPTER: {
|
|
|
410
411
|
SCALE_FLOOR: number;
|
|
411
412
|
ZERO_EPSILON: number;
|
|
412
413
|
};
|
|
414
|
+
AMA_SLOPE_PERSIST_ENABLED: boolean;
|
|
415
|
+
AMA_SLOPE_PERSIST_BARS: number;
|
|
413
416
|
DYNAMIC_WEIGHT_ALPHA: number;
|
|
414
417
|
DYNAMIC_WEIGHT_DW: number;
|
|
415
418
|
DYNAMIC_WEIGHT_GAIN: number;
|
|
@@ -492,7 +495,6 @@ declare let MARKET_ADAPTER: {
|
|
|
492
495
|
};
|
|
493
496
|
AMA_CONVERGENCE_ER_AVG: number;
|
|
494
497
|
AMA_CONVERGENCE_EPSILON: number;
|
|
495
|
-
AMA_ER_SMOOTH_FAST_PERIOD: number;
|
|
496
498
|
};
|
|
497
499
|
declare let LOG_LEVEL: string;
|
|
498
500
|
declare let LOGGING_CONFIG: {
|
|
@@ -242,6 +242,14 @@ let TIMING = {
|
|
|
242
242
|
// genuinely empty. A contradicted re-read (non-empty) aborts acceptance
|
|
243
243
|
// and feeds the fresh snapshot to the resync instead.
|
|
244
244
|
SYNC_EMPTY_READ_CONFIRM_DELAY_MS: 2000,
|
|
245
|
+
// Surplus-cancel grace for freshly placed orders. Spread correction and
|
|
246
|
+
// surplus sweeps run on different count snapshots within one cycle, so a
|
|
247
|
+
// fill landing between them makes the second controller cancel what the
|
|
248
|
+
// first just placed (observed: 4 placed, 3 cancelled seconds later).
|
|
249
|
+
// Orders younger than this are skipped by surplus cancellation and
|
|
250
|
+
// re-evaluated next cycle. Time-bounded by design: genuine misplacements
|
|
251
|
+
// are only delayed, never protected forever.
|
|
252
|
+
SURPLUS_CANCEL_GRACE_MS: 15 * 60 * 1000,
|
|
245
253
|
// Connection and initialization timeouts
|
|
246
254
|
CONNECTION_TIMEOUT_MS: 30000, // 30 seconds - BitShares client connection establishment timeout
|
|
247
255
|
DAEMON_STARTUP_TIMEOUT_MS: 60000, // 60 seconds - Private key daemon startup timeout
|
|
@@ -1083,12 +1091,15 @@ let MARKET_ADAPTER = {
|
|
|
1083
1091
|
// DYNAMIC_WEIGHT_AMA_LOOKBACK_BARS: Lookback window for measuring AMA trend.
|
|
1084
1092
|
// Lower values react faster to recent price changes.
|
|
1085
1093
|
// Higher values smooth the signal and require a more sustained move.
|
|
1086
|
-
//
|
|
1087
|
-
//
|
|
1088
|
-
//
|
|
1089
|
-
//
|
|
1094
|
+
// 16 (was 20): the shorter window's slope is ~8% noisier (bar-to-bar wobble
|
|
1095
|
+
// and zero-crossings), which by itself would add slope resets; the
|
|
1096
|
+
// persistence gate (K=3) absorbs that, so resets/day stay matched — 962 vs
|
|
1097
|
+
// 960 on the sample, 0.95/day either way. It buys a cleaner signal where it
|
|
1098
|
+
// matters: AMA group delay 10→8 bars, reversal lag 22→20, and range-tilt
|
|
1099
|
+
// wrong-way 13.7%→12.6%. Measured on the real 1h pools; see
|
|
1100
|
+
// docs/AMA_SLOPE_WINDOW.md.
|
|
1090
1101
|
// nob: lb (Lookback Bars)
|
|
1091
|
-
DYNAMIC_WEIGHT_AMA_LOOKBACK_BARS:
|
|
1102
|
+
DYNAMIC_WEIGHT_AMA_LOOKBACK_BARS: 16,
|
|
1092
1103
|
// DYNAMIC_WEIGHT_AMA_MAX_SLOPE_PCT: Average per-bar trend size that counts as "full strength" for AMA.
|
|
1093
1104
|
// Lower values make the AMA channel reach maximum influence more easily.
|
|
1094
1105
|
// Higher values require a stronger price move before AMA reaches full effect.
|
|
@@ -1113,8 +1124,16 @@ let MARKET_ADAPTER = {
|
|
|
1113
1124
|
// Node callers via the module import, generated HTML via an injected
|
|
1114
1125
|
// `const AMA_SLOPE_HUBER = {...}` literal. Change a value here and every
|
|
1115
1126
|
// slope computation follows; do not re-declare them per caller.
|
|
1116
|
-
// C Huber tuning constant
|
|
1117
|
-
//
|
|
1127
|
+
// C Huber tuning constant. Nominal 1.345 ~= 95% Gaussian
|
|
1128
|
+
// efficiency, but the plug-in 1.4826*MAD scale is biased low
|
|
1129
|
+
// (residual degrees of freedom), so the EFFECTIVE C is
|
|
1130
|
+
// ~1.25 at the 16-bar window — more robust, less efficient
|
|
1131
|
+
// than nominal. The detune grows ~1/(bars-1) at short
|
|
1132
|
+
// windows and vanishes at long ones; deliberately NOT
|
|
1133
|
+
// compensated (the bias points the robust way, and a
|
|
1134
|
+
// sqrt(n/(n-2)) correction is decision-neutral). See
|
|
1135
|
+
// analysis/trend_detection/huber_scale_variants.ts.
|
|
1136
|
+
// ITERATIONS IRLS passes (converges in a few at the ~16-bar window)
|
|
1118
1137
|
// SCALE_FLOOR Floor for the 1.4826*MAD robust scale, in log units
|
|
1119
1138
|
// ZERO_EPSILON Slopes below this (%/bar) snap to exactly 0
|
|
1120
1139
|
// nob: n/a (algorithm-internal)
|
|
@@ -1124,6 +1143,19 @@ let MARKET_ADAPTER = {
|
|
|
1124
1143
|
SCALE_FLOOR: 1e-6,
|
|
1125
1144
|
ZERO_EPSILON: 1e-9,
|
|
1126
1145
|
},
|
|
1146
|
+
// AMA_SLOPE_PERSIST_ENABLED: slope-delta persistence gate (trigger B).
|
|
1147
|
+
// When true, the slope reset requires AMA_SLOPE_PERSIST_BARS consecutive
|
|
1148
|
+
// confirming bars, filtering short-lived excursions. Enabled by default
|
|
1149
|
+
// (was legacy fire-on-first-crossing): measured over the real 1h pools it
|
|
1150
|
+
// cuts resets ~35% and whipsaw ~52%→~17%, leaving lag and range-tilt
|
|
1151
|
+
// unchanged. Per bot/market override via `amaSlope.persistBars` /
|
|
1152
|
+
// `amaSlope.persistEnabled`. See docs/AMA_SLOPE_WINDOW.md.
|
|
1153
|
+
AMA_SLOPE_PERSIST_ENABLED: true,
|
|
1154
|
+
// AMA_SLOPE_PERSIST_BARS: consecutive confirming bars required before the
|
|
1155
|
+
// slope-delta grid reset (trigger B) fires once enabled. 1 = legacy behavior
|
|
1156
|
+
// (no persistence). Filters short-lived slope excursions without adding trend
|
|
1157
|
+
// latency.
|
|
1158
|
+
AMA_SLOPE_PERSIST_BARS: 3,
|
|
1127
1159
|
// DYNAMIC_WEIGHT_ALPHA: Blend between AMA trend and Kalman trend.
|
|
1128
1160
|
// 0 = pure Kalman, 1 = pure AMA.
|
|
1129
1161
|
// Higher values trust AMA more, lower values trust Kalman more.
|
|
@@ -1331,14 +1363,6 @@ let MARKET_ADAPTER = {
|
|
|
1331
1363
|
// AMA_CONVERGENCE_EPSILON: Target fraction of initialization bias remaining
|
|
1332
1364
|
// after convergence. 0.01 = 99 % of the initial bias has decayed.
|
|
1333
1365
|
AMA_CONVERGENCE_EPSILON: 0.01,
|
|
1334
|
-
// AMA_ER_SMOOTH_FAST_PERIOD: Fast-period equivalent for smoothing the raw
|
|
1335
|
-
// Efficiency Ratio via EMA before it enters the SC formula. Raw ER can spike
|
|
1336
|
-
// at regime boundaries (trending ↔ ranging), causing jerky AMA transitions
|
|
1337
|
-
// and false grid re-centering triggers.
|
|
1338
|
-
// 0 = disabled (raw ER used directly, backward compatible).
|
|
1339
|
-
// Enabled alpha = 2 / (AMA_ER_SMOOTH_FAST_PERIOD + 1).
|
|
1340
|
-
// Overridable per bot via bots.json inline `ama.erSmoothPeriod` field.
|
|
1341
|
-
AMA_ER_SMOOTH_FAST_PERIOD: 0,
|
|
1342
1366
|
};
|
|
1343
1367
|
// Logging Level Configuration
|
|
1344
1368
|
// Options:
|
|
@@ -497,6 +497,18 @@ async function checkAndApplyBotConfigChanges(bot, context = 'bots-config poll',
|
|
|
497
497
|
.join('; ');
|
|
498
498
|
bot._log?.(`Applied bots.json changes for '${botName}' live during ${context} (no restart needed): ${summary}. ` +
|
|
499
499
|
`Targeted maintenance will place missing / cancel excess orders.`, 'info');
|
|
500
|
+
// Deliver the promise above instead of waiting for the next fill
|
|
501
|
+
// or the 240-min fetch: run the targeted drift reconciliation
|
|
502
|
+
// right away (same fire-and-forget shape as the poll tick — the
|
|
503
|
+
// callee owns its cooldown and pipeline gates, so a busy pipeline
|
|
504
|
+
// skips and the next maintenance tick retries).
|
|
505
|
+
try {
|
|
506
|
+
const driftRun = maybeRunTargetedDriftReconciliation(bot, `${context} config pickup`);
|
|
507
|
+
driftRun?.catch?.((err) => {
|
|
508
|
+
bot._log?.(`[TARGETED-SYNC] Config-pickup reconciliation failed: ${getErrorMessage(err)}`, 'debug');
|
|
509
|
+
});
|
|
510
|
+
}
|
|
511
|
+
catch { /* never break the poll tick */ }
|
|
500
512
|
}
|
|
501
513
|
if (otherKeys.length > 0) {
|
|
502
514
|
const shown = otherKeys.slice(0, 8).join(', ');
|
|
@@ -389,6 +389,31 @@ class Accountant {
|
|
|
389
389
|
virtualSell += size;
|
|
390
390
|
}
|
|
391
391
|
}
|
|
392
|
+
// Deferred-but-live chain orders: the last sync saw these on chain
|
|
393
|
+
// without a grid slot (out-of-grid, boundary-unknown deferrals).
|
|
394
|
+
// They lock REAL funds — a BUY size is already quote, a SELL size is
|
|
395
|
+
// already base, same conventions as the slot loop above — so they
|
|
396
|
+
// belong in the on-chain committed sums. Without them every invariant
|
|
397
|
+
// check reports drift equal to their value and triggers futile
|
|
398
|
+
// recovery resyncs. Never counted as grid or placeable: only the
|
|
399
|
+
// committed (locked) side. Staleness is bounded by the sync refresh
|
|
400
|
+
// (the list is replaced wholesale each sync); a fill between syncs
|
|
401
|
+
// over-counts until the next refresh, at most one transient recovery.
|
|
402
|
+
try {
|
|
403
|
+
const unmatched = mgr?._lastUnmatchedChainOrders;
|
|
404
|
+
if (Array.isArray(unmatched)) {
|
|
405
|
+
for (const u of unmatched) {
|
|
406
|
+
const uSize = Number(u?.size);
|
|
407
|
+
if (!Number.isFinite(uSize) || uSize <= 0)
|
|
408
|
+
continue;
|
|
409
|
+
if (u?.type === ORDER_TYPES.BUY)
|
|
410
|
+
chainBuy += uSize;
|
|
411
|
+
else if (u?.type === ORDER_TYPES.SELL)
|
|
412
|
+
chainSell += uSize;
|
|
413
|
+
}
|
|
414
|
+
}
|
|
415
|
+
}
|
|
416
|
+
catch { /* committed sums stay grid-only */ }
|
|
392
417
|
// STEP 5: Fetch blockchain free balances and compute totals
|
|
393
418
|
const chainFreeBuy = mgr.accountTotals?.buyFree || 0;
|
|
394
419
|
const chainFreeSell = mgr.accountTotals?.sellFree || 0;
|