dexbot 1.6.9 → 1.6.11
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +34 -0
- package/README.md +1 -0
- package/analysis/README.md +50 -12
- package/analysis/bot_fitting/README.md +12 -0
- package/analysis/tradingview/README.md +15 -10
- package/analysis/trend_detection/DYNAMIC_WEIGHT_RESEARCH.md +10 -36
- package/analysis/trend_detection/README.md +31 -0
- package/claw/modules/chain_queries.ts +9 -4
- package/claw/modules/claw_bridge.ts +9 -9
- 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/ama_fitting/optimizer_high_resolution.js +2 -1
- package/dist/analysis/analyze_dynamic_weight.js +0 -3
- package/dist/analysis/bot_fitting/backtest_ama_sweep.js +52 -8
- package/dist/analysis/bot_fitting/backtest_bot_fitting.js +68 -10
- 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 +17 -17
- 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.d.ts +0 -3
- package/dist/analysis/tradingview/analyze_tradingview.js +6 -19
- 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 +12 -1
- package/dist/analysis/tradingview/grid_reset_sim.js +60 -11
- package/dist/analysis/tradingview/tradingview_uplot_chart_generator.js +180 -33
- 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 +29 -110
- 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 +19 -11
- 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/ama_slope_model.d.ts +2 -2
- package/dist/market_adapter/core/strategies/ama_slope_model.js +12 -10
- package/dist/market_adapter/core/strategies/dynamic_weight_series.d.ts +41 -14
- package/dist/market_adapter/core/strategies/dynamic_weight_series.js +138 -30
- 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/lp_chart_strategy_loader.js +2 -1
- package/dist/market_adapter/market_adapter.d.ts +0 -1
- package/dist/market_adapter/market_adapter.js +2 -27
- package/dist/market_adapter/utils/chain.d.ts +1 -1
- package/dist/market_adapter/utils/chain.js +8 -6
- package/dist/modules/account_bots.js +5 -4
- package/dist/modules/bitshares-native/resolvers.js +5 -0
- package/dist/modules/bot_settings.js +13 -1
- package/dist/modules/chain_orders.js +2 -1
- package/dist/modules/constants.d.ts +9 -1
- package/dist/modules/constants.js +55 -9
- package/dist/modules/credential_policy.js +4 -1
- package/dist/modules/credit_runtime.js +5 -1
- 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/order/utils/system.js +11 -1
- package/dist/modules/paths.d.ts +2 -0
- package/dist/modules/paths.js +2 -0
- package/dist/modules/utils/asset_symbols.d.ts +59 -0
- package/dist/modules/utils/asset_symbols.js +128 -0
- package/dist/modules/utils/time_range.d.ts +15 -0
- package/dist/modules/utils/time_range.js +18 -0
- package/dist/scripts/analyze-credit.js +10 -7
- package/dist/scripts/analyze-orders.js +1 -44
- package/dist/scripts/chart_command.js +15 -8
- package/dist/scripts/pnl.d.ts +3 -0
- package/dist/scripts/pnl.js +40 -0
- package/dist/scripts/verify-browser-bundle.js +8 -0
- package/dist/unlock.js +34 -0
- package/docs/DEXBOT_COMPARISON.md +3 -3
- package/docs/EVOLUTION.md +12 -10
- package/docs/FUND_MOVEMENT_AND_ACCOUNTING.md +1 -1
- package/docs/GRID_RECALCULATION.md +33 -17
- package/docs/README.md +2 -2
- package/docs/WORKFLOW.md +1 -0
- package/market_adapter/README.md +6 -28
- package/package.json +1 -1
- package/scripts/README.md +14 -0
package/dist/dexbot.js
CHANGED
|
@@ -95,15 +95,19 @@ const fundRegistry = require('./modules/fund_registry');
|
|
|
95
95
|
*/
|
|
96
96
|
const _collateralAssetIdCache = new Map();
|
|
97
97
|
async function _resolveCollateralAssetId(ref) {
|
|
98
|
-
|
|
99
|
-
|
|
98
|
+
// The collateral ref is free-text input from the fund-registration flow
|
|
99
|
+
// ("tokena" resolves on the chain without error). Canonicalize before the
|
|
100
|
+
// lookup AND before the cache key, so one asset never occupies two slots.
|
|
101
|
+
const key = normalizeAssetRef(ref);
|
|
102
|
+
if (_collateralAssetIdCache.has(key))
|
|
103
|
+
return _collateralAssetIdCache.get(key) ?? null;
|
|
100
104
|
let result = null;
|
|
101
105
|
try {
|
|
102
|
-
if (
|
|
103
|
-
result =
|
|
106
|
+
if (key.startsWith('1.3.')) {
|
|
107
|
+
result = key;
|
|
104
108
|
}
|
|
105
|
-
else if (
|
|
106
|
-
const res = await BitShares.db.lookup_asset_symbols([
|
|
109
|
+
else if (key) {
|
|
110
|
+
const res = await BitShares.db.lookup_asset_symbols([key]);
|
|
107
111
|
if (res && res[0] && res[0].id)
|
|
108
112
|
result = String(res[0].id);
|
|
109
113
|
}
|
|
@@ -111,7 +115,7 @@ async function _resolveCollateralAssetId(ref) {
|
|
|
111
115
|
catch (_err) {
|
|
112
116
|
result = null;
|
|
113
117
|
}
|
|
114
|
-
_collateralAssetIdCache.set(
|
|
118
|
+
_collateralAssetIdCache.set(key, result);
|
|
115
119
|
return result;
|
|
116
120
|
}
|
|
117
121
|
const { setupGracefulShutdown, registerCleanup, unregisterCleanup } = require('./modules/graceful_shutdown');
|
|
@@ -123,6 +127,7 @@ const credentialPolicy = require('./modules/credential_policy');
|
|
|
123
127
|
const { Config } = require('./modules/config');
|
|
124
128
|
const { getErrorMessage } = require('./modules/utils/errors');
|
|
125
129
|
const { isSameBotName } = require('./modules/utils/sanitize_key');
|
|
130
|
+
const { normalizeAssetRef } = require('./modules/utils/asset_symbols');
|
|
126
131
|
// Setup graceful shutdown handlers
|
|
127
132
|
// Setup graceful shutdown handlers
|
|
128
133
|
setupGracefulShutdown();
|
|
@@ -138,7 +143,7 @@ if (typeof credentialPolicy.checkPolicyFileSecurity === 'function')
|
|
|
138
143
|
// Primary CLI driver that manages tracked bots and helper utilities such as key/bot editors.
|
|
139
144
|
const PROFILES_BOTS_FILE = PATHS.PROFILES.BOTS_JSON;
|
|
140
145
|
const PROFILES_DIR = PATHS.PROFILES_DIR;
|
|
141
|
-
const CLI_COMMANDS = ['start', 'test', 'reset', 'default', 'disable', 'enable', 'drystart', 'key', 'bot', 'pm2', 'update', 'export', 'order', 'credit', 'tv', 'dw', 'clear', 'clear-orders', 'clear-market-adapter', 'clear-all', 'status', 'unlock', 'delete', 'stop', 'restart', 'reload', 'help'];
|
|
146
|
+
const CLI_COMMANDS = ['start', 'test', 'reset', 'default', 'disable', 'enable', 'drystart', 'key', 'bot', 'pm2', 'update', 'export', 'order', 'credit', 'tv', 'dw', 'pnl', 'clear', 'clear-orders', 'clear-market-adapter', 'clear-all', 'status', 'unlock', 'delete', 'stop', 'restart', 'reload', 'help'];
|
|
142
147
|
const COMMAND_ALIASES = { orders: 'order', keys: 'key', bots: 'bot', stat: 'status', stats: 'status', start: 'unlock', defaults: 'default', stp: 'stop', stopall: 'stop', restartall: 'restart', reloadall: 'reload' };
|
|
143
148
|
const CLI_HELP_FLAGS = ['-h', '--help'];
|
|
144
149
|
const CLI_EXAMPLES_FLAG = '--cli-examples';
|
|
@@ -157,6 +162,7 @@ const CLI_EXAMPLES = [
|
|
|
157
162
|
{ title: 'Analyze persisted order grids', command: 'dexbot order', notes: 'Runs the order analyzer across the orders directory (<profiles>/orders) and prints spread/increment/funds/distribution metrics. Add a bot key to render only that bot, and --export for an HTML report.' },
|
|
158
163
|
{ title: 'Show live credit/MPA positions', command: 'dexbot credit', notes: 'Queries get_margin_positions + get_credit_deals_by_borrower per preferredAccount and prints debt/collateral sums plus one Curr. CR line per whitelisted pair (active CR, else borrow-now CR vs funds avail. on the offer) and one Avar. CR line per bot. CR covers only pairs whitelisted in bots.json and listed on the current credit offer. Add a bot key to render only that bot.' },
|
|
159
164
|
{ title: 'TradingView chart for a bot, pool, or pair', command: 'dexbot tv <bot|pool-id|AssetA/AssetB> --month 3', notes: 'Fetches 1h candles for N months (default 3, pool-first with orderbook fallback; --feed charts MPA price-feed history) and writes an auto-named HTML chart.' },
|
|
165
|
+
{ title: 'PnL report for a bot or blockchain account', command: 'dexbot pnl <bot|account|1.2.x> --month 3 [--pair BASE/QUOTE]', notes: 'Resolves a local bot profile first, then the chain account, analyzes its fills for the requested window and writes a self-contained HTML PnL report.' },
|
|
160
166
|
{ title: 'Clear all bot log files', command: 'dexbot clear', notes: 'Runs scripts/clear-logs.sh to remove *.log, rotated *.log.N and *.jsonl* from the logs directory (<profiles>/logs), including the credential audit trail daemon-audit.jsonl and its rotated siblings (named in the preview). Offline only: the scripts warn when a live runtime is detected, but a running bot keeps writing to unlinked files and the space is not freed until it restarts; dexbot clear-orders / clear-market-adapter / clear-all are undone within seconds (grid state is re-persisted, the adapter rewrites its state file and lock). Stop first with dexbot stop / dexbot pm2 stop all.' },
|
|
161
167
|
{ title: 'Reset settings to defaults', command: 'dexbot default', notes: 'Runs scripts/reset-settings.sh to delete general.settings.json, market_profiles.json, and market_adapter_settings.json.' }
|
|
162
168
|
];
|
|
@@ -215,6 +221,7 @@ function printCLIUsage() {
|
|
|
215
221
|
['credit [<bot>]', 'Live summed MPA + borrowed-credit positions per asset per bot.'],
|
|
216
222
|
['tv <target>', 'TradingView chart: 1h candles for <bot|pool-id|AssetA/AssetB> over --month N (default 3).'],
|
|
217
223
|
['dw <target>', 'Dynamic-weight research chart: same targets/flags as tv (see analysis/).'],
|
|
224
|
+
['pnl <account>', 'PnL HTML report for a bot/account over --month N, optional --pair BASE/QUOTE filter.'],
|
|
218
225
|
]],
|
|
219
226
|
['Files', [
|
|
220
227
|
['clear', 'Delete <profiles>/logs/*.log, *.log.N and *.jsonl* (audit trail included). Stop the runtime first.'],
|
|
@@ -254,7 +261,7 @@ if (cliArgs.some(arg => CLI_HELP_FLAGS.includes(arg))) {
|
|
|
254
261
|
// so the script prints its usage. Only scripts with offline help handling
|
|
255
262
|
// belong here — forwarding to a script without it could misinterpret the
|
|
256
263
|
// flag as input (e.g. a bot-name filter triggering live work).
|
|
257
|
-
const HELP_OWNING_COMMANDS = new Set(['credit', 'tv', 'dw']);
|
|
264
|
+
const HELP_OWNING_COMMANDS = new Set(['credit', 'tv', 'dw', 'pnl']);
|
|
258
265
|
const requestedCommand = COMMAND_ALIASES[cliArgs[0]] ?? cliArgs[0];
|
|
259
266
|
if (!HELP_OWNING_COMMANDS.has(requestedCommand)) {
|
|
260
267
|
printCLIUsage();
|
|
@@ -589,7 +596,7 @@ async function runBotInstances(botEntries, { forceDryRun = false, sourceName = '
|
|
|
589
596
|
const collateralRef = item.collateralAsset;
|
|
590
597
|
if (!collateralRef)
|
|
591
598
|
continue;
|
|
592
|
-
const collateralAssetId = _collateralAssetIdCache.get(collateralRef) ?? null;
|
|
599
|
+
const collateralAssetId = _collateralAssetIdCache.get(normalizeAssetRef(collateralRef)) ?? null;
|
|
593
600
|
if (!collateralAssetId) {
|
|
594
601
|
console.error(` ERROR: unable to resolve collateral asset '${collateralRef}' for credit bot ${botName}. Credit bot will run WITHOUT proportional allocation. Check chain connectivity and asset configuration.`);
|
|
595
602
|
continue;
|
|
@@ -1003,7 +1010,8 @@ async function handleCLICommands() {
|
|
|
1003
1010
|
return true;
|
|
1004
1011
|
}
|
|
1005
1012
|
case 'tv':
|
|
1006
|
-
case 'dw':
|
|
1013
|
+
case 'dw':
|
|
1014
|
+
case 'pnl': {
|
|
1007
1015
|
const { spawnSync } = require('child_process');
|
|
1008
1016
|
const scriptArgs = buildRuntimeScriptArgs({
|
|
1009
1017
|
codeRoot: __dirname,
|
|
@@ -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 };
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { computeAverageAmaSlopePct, computeAmaSlopeClipThreshold, createAmaSlopeClipTracker } from './dynamic_weight_series.js';
|
|
1
|
+
import { computeAverageAmaSlopePct, computeHuberWindowSlopePct, computeAmaSlopeClipThreshold, createAmaSlopeClipTracker } from './dynamic_weight_series.js';
|
|
2
2
|
/**
|
|
3
3
|
* Compute AMA slope and volatility offsets from the AMA series.
|
|
4
4
|
*
|
|
@@ -31,5 +31,5 @@ declare function computeAmaSlopeWeights(amaValues: any, weightVariance: any, opt
|
|
|
31
31
|
trend: string;
|
|
32
32
|
isReady: boolean;
|
|
33
33
|
};
|
|
34
|
-
export { computeAmaSlopeWeights, computeAverageAmaSlopePct, computeAmaSlopeClipThreshold, createAmaSlopeClipTracker, };
|
|
34
|
+
export { computeAmaSlopeWeights, computeAverageAmaSlopePct, computeHuberWindowSlopePct, computeAmaSlopeClipThreshold, createAmaSlopeClipTracker, };
|
|
35
35
|
//# sourceMappingURL=ama_slope_model.d.ts.map
|
|
@@ -6,7 +6,7 @@ import { normalizeMaxVolatilityOffset, normalizeVolatilityThreshold, } from '../
|
|
|
6
6
|
import { computeVolatilityShift } from './volatility_shift.js';
|
|
7
7
|
// Canonical AMA slope % lives in dynamic_weight_series.ts (self-contained so the
|
|
8
8
|
// chart generators can embed its exact source); re-exported here for compat.
|
|
9
|
-
import { computeAverageAmaSlopePct, computeAmaSlopeClipThreshold, createAmaSlopeClipTracker, } from './dynamic_weight_series.js';
|
|
9
|
+
import { computeAverageAmaSlopePct, computeHuberWindowSlopePct, computeAmaSlopeClipThreshold, createAmaSlopeClipTracker, } from './dynamic_weight_series.js';
|
|
10
10
|
const _DEFAULT_AMA_KEY = MARKET_ADAPTER.DEFAULT_AMA_KEY;
|
|
11
11
|
const DEFAULT_ER_PERIOD = MARKET_ADAPTER.AMAS[_DEFAULT_AMA_KEY].erPeriod;
|
|
12
12
|
/**
|
|
@@ -74,14 +74,16 @@ function computeAmaSlopeWeights(amaValues, weightVariance, opts = {}) {
|
|
|
74
74
|
return notReady;
|
|
75
75
|
}
|
|
76
76
|
const N = amaValues.length;
|
|
77
|
-
|
|
78
|
-
|
|
79
|
-
|
|
80
|
-
|
|
81
|
-
|
|
82
|
-
//
|
|
83
|
-
// lookback
|
|
84
|
-
|
|
77
|
+
// 2. Slope percent per bar over the lookback window, as a Huber-robust
|
|
78
|
+
// linear regression of ln(AMA) (canonical: computeHuberWindowSlopePct). The
|
|
79
|
+
// two-point endpoint difference is kept in dynamic_weight_series as the
|
|
80
|
+
// reference definition, but it gives the window-edge bar full weight: a
|
|
81
|
+
// single-bar impulse moves it 7x-70x the reset gate while the robust fit
|
|
82
|
+
// bounds that influence without the lag of a rank-based estimator.
|
|
83
|
+
// lookback stays a smoothing/lag knob rather than adding gain in sustained
|
|
84
|
+
// trends. The estimator validates every bar in the window (both ends
|
|
85
|
+
// strictly positive), so it subsumes the old two-endpoint guard here.
|
|
86
|
+
const slopePct = computeHuberWindowSlopePct(amaValues, N - 1, lookbackBars);
|
|
85
87
|
if (!Number.isFinite(slopePct)) {
|
|
86
88
|
return notReady;
|
|
87
89
|
}
|
|
@@ -130,5 +132,5 @@ function computeAmaSlopeWeights(amaValues, weightVariance, opts = {}) {
|
|
|
130
132
|
// computeAmaSlopeClipThreshold and createAmaSlopeClipTracker live in
|
|
131
133
|
// dynamic_weight_series.ts (self-contained so the chart generators can embed
|
|
132
134
|
// their exact source); re-exported here so Node callers keep this import path.
|
|
133
|
-
export { computeAmaSlopeWeights, computeAverageAmaSlopePct, computeAmaSlopeClipThreshold, createAmaSlopeClipTracker, };
|
|
135
|
+
export { computeAmaSlopeWeights, computeAverageAmaSlopePct, computeHuberWindowSlopePct, computeAmaSlopeClipThreshold, createAmaSlopeClipTracker, };
|
|
134
136
|
//# sourceMappingURL=ama_slope_model.js.map
|
|
@@ -1,20 +1,47 @@
|
|
|
1
|
+
declare function computeAverageAmaSlopePct(current: any, past: any, lookbackBars: any): number | null;
|
|
1
2
|
/**
|
|
2
|
-
*
|
|
3
|
-
*
|
|
4
|
-
*
|
|
3
|
+
* Per-bar AMA trend in %/bar over `lookbackBars`, fitted as a Huber-robust
|
|
4
|
+
* linear regression of ln(AMA) against bar index (uniform weights, no kernel).
|
|
5
|
+
*
|
|
6
|
+
* This is the canonical slope used by the live adapter (dynamic weight series,
|
|
7
|
+
* AMA slope model, both clip paths), the grid-reset replay and the research
|
|
8
|
+
* charts, which embed this exact source via `embedFunctionSources`. One
|
|
9
|
+
* definition, one set of numbers — do not re-implement it per caller. Selected
|
|
10
|
+
* experimentally on a real 1h pool: it is the smoothest robust option measured
|
|
11
|
+
* (second-difference energy ~25x lower than the median's, max |dSlope|
|
|
12
|
+
* comparable to the two-point endpoint), because its influence function is
|
|
13
|
+
* continuous and bounded rather than an order statistic.
|
|
14
|
+
*
|
|
15
|
+
* The fit is local linear over `lookbackBars` intervals (bars+1 points, the same
|
|
16
|
+
* 16h span the endpoint uses), so a window-wide regime change tilts the line
|
|
17
|
+
* continuously instead of waiting for a majority, and a lone off-trend spike is
|
|
18
|
+
* bounded rather than given full endpoint weight. Output is the log-return per
|
|
19
|
+
* bar x 100. That differs from the arithmetic per-bar return by ~beta^2/2,
|
|
20
|
+
* which is negligible at the sub-0.1 %/bar magnitudes the defaults use (order
|
|
21
|
+
* 1e-9 at 0.1 %/bar) but grows quadratically with the reading — ln(1.06)*100 =
|
|
22
|
+
* 5.83, ~3% below a 6%/bar arithmetic rate. A pre-existing user override of
|
|
23
|
+
* maxSlopePct / neutralZonePct was tuned against the arithmetic reading, so a
|
|
24
|
+
* saturated override now clamps a hair tighter than before.
|
|
5
25
|
*
|
|
6
|
-
*
|
|
7
|
-
*
|
|
8
|
-
*
|
|
9
|
-
*
|
|
26
|
+
* Persistence note: `slopePct` is a different quantity from any pre-Huber
|
|
27
|
+
* reading (log-return regression vs the old median/endpoint). The first cycle
|
|
28
|
+
* after deploying compares a Huber reading against the still-persisted old
|
|
29
|
+
* baseline (botState.gridRangeScalingAmaSlope); the two magnitudes agree
|
|
30
|
+
* closely, so that delta sits below the reset gate on ~98% of bars (p50
|
|
31
|
+
* 0.00043, p90 0.00277 %/bar) — roughly one whitelisted bot in fifty costs one
|
|
32
|
+
* extra recenter, once. No version marker is persisted to suppress it.
|
|
10
33
|
*
|
|
11
|
-
*
|
|
12
|
-
*
|
|
13
|
-
*
|
|
14
|
-
*
|
|
15
|
-
*
|
|
34
|
+
* Parameters come from MARKET_ADAPTER.DYNAMIC_WEIGHT_AMA_HUBER (aliased as
|
|
35
|
+
* AMA_SLOPE_HUBER; injected into generated charts). `hub` is overridable only so
|
|
36
|
+
* tests can prove the values are threaded through — production never passes it.
|
|
37
|
+
*
|
|
38
|
+
* @param amaValues Full AMA series (index-addressable).
|
|
39
|
+
* @param index Bar to measure at (evaluated at the window edge).
|
|
40
|
+
* @param lookbackBars Window length in bars (fixed at 16 for every estimator).
|
|
41
|
+
* @param hub Parameter block; defaults to the centralized constant.
|
|
42
|
+
* @returns %/bar, or null when the window is unusable.
|
|
16
43
|
*/
|
|
17
|
-
declare function
|
|
44
|
+
declare function computeHuberWindowSlopePct(amaValues: any, index: number, lookbackBars: any, hub?: any): number | null;
|
|
18
45
|
declare function echoLatchSeries(appliedSeries: any[], preGainSeries: any[], confirmBars: any): {
|
|
19
46
|
echoedAppliedSeries: any[];
|
|
20
47
|
echoedPreGainSeries: any[];
|
|
@@ -74,5 +101,5 @@ declare function computeAmaSlopeClipThreshold(amaValues: any, erPeriod: number,
|
|
|
74
101
|
declare function createAmaSlopeClipTracker(erPeriod: number, lookbackBars: number, clipPercentile: number): {
|
|
75
102
|
push(value: number): number;
|
|
76
103
|
};
|
|
77
|
-
export { computeDynamicWeightSeries, computeAverageAmaSlopePct, echoLatchSeries, roundToN, computeAmaSlopeClipThreshold, createAmaSlopeClipTracker, percentileFromSorted, };
|
|
104
|
+
export { computeDynamicWeightSeries, computeAverageAmaSlopePct, computeHuberWindowSlopePct, echoLatchSeries, roundToN, computeAmaSlopeClipThreshold, createAmaSlopeClipTracker, percentileFromSorted, };
|
|
78
105
|
//# sourceMappingURL=dynamic_weight_series.d.ts.map
|