@reefclaw/openclaw-plugin 0.1.48 → 0.1.49
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/bridge/bridge.js +22 -16
- package/bridge/gateway/heartbeat-cron.d.ts +64 -0
- package/bridge/gateway/heartbeat-cron.js +150 -1
- package/bridge/provider.d.ts +12 -0
- package/bridge/providers/gateway.d.ts +21 -0
- package/bridge/providers/gateway.js +104 -7
- package/bridge/utils/skill-version.d.ts +6 -0
- package/bridge/utils/skill-version.js +10 -0
- package/index.js +4 -0
- package/openclaw.plugin.json +1 -1
- package/package.json +1 -1
- package/release-integrity.json +5 -0
- package/release-notes.json +2 -1
- package/signals/stop-rules.d.ts +13 -0
- package/signals/stop-rules.js +35 -6
- package/signals/strategy-adapter.js +25 -6
- package/skills/reefclaw/SKILL.md +1 -1
- package/tools/assessment-validation.d.ts +10 -2
- package/tools/assessment-validation.js +19 -5
- package/tools/create-order.d.ts +4 -0
- package/tools/create-order.js +15 -0
- package/tools/intel-cache.d.ts +14 -0
- package/tools/intel-cache.js +59 -0
package/bridge/bridge.js
CHANGED
|
@@ -15,7 +15,7 @@ import { logger, formatError } from './logger.js';
|
|
|
15
15
|
import { noteWebappResponse, webappEdgeTracker, webappHeaders } from './utils/webapp-edge.js';
|
|
16
16
|
import { resolveWebappBaseUrl } from './utils/base-url.js';
|
|
17
17
|
import { Connector } from './connector.js';
|
|
18
|
-
import { readLocalSkillVersion, readAgentVisibleSkillVersions, validateSkillContent, compareSemver } from './utils/skill-version.js';
|
|
18
|
+
import { readLocalSkillVersion, readAgentVisibleSkillVersions, validateSkillContent, compareSemver, isBootstrapSkillVersion } from './utils/skill-version.js';
|
|
19
19
|
import { invalidateSkillsSnapshot } from './utils/skills-snapshot-invalidation.js';
|
|
20
20
|
import { verifySkillSignature, signatureRequired, readLastAppliedSignedAtMs, recordAppliedSignedAt, } from './utils/skill-signing.js';
|
|
21
21
|
import { isTradingMode, validateModeTransition, redactTokens } from '@reefclaw/shared';
|
|
@@ -66,15 +66,6 @@ const BOOTSTRAP_SKILL_HEAL_INTERVAL_MS = 10 * 60_000; // 10 min
|
|
|
66
66
|
/** How often the bridge drains edge-deny transitions into agent_state events
|
|
67
67
|
* (skill.webapp_edge_denied / _recovered audit rows via the relay). */
|
|
68
68
|
const WEBAPP_EDGE_EMIT_INTERVAL_MS = 60_000;
|
|
69
|
-
/** True while the agent is still on the thin bootstrap SKILL.md and has NOT yet
|
|
70
|
-
* received the full trading instructions. The bootstrap ships 0.0.x; the full
|
|
71
|
-
* trading SKILL.md is 2.x — treat anything below 1.0.0 (or an unknown version)
|
|
72
|
-
* as bootstrap so we keep pulling until the real skill lands. */
|
|
73
|
-
function isBootstrapSkillVersion(version) {
|
|
74
|
-
if (!version)
|
|
75
|
-
return true;
|
|
76
|
-
return compareSemver('1.0.0', version) > 0; // '1.0.0' > version ⟺ version < 1.0.0
|
|
77
|
-
}
|
|
78
69
|
/** The single-agent layout every box used before multi-agent attach. */
|
|
79
70
|
export function defaultBridgePaths() {
|
|
80
71
|
return {
|
|
@@ -1298,13 +1289,28 @@ export class Bridge {
|
|
|
1298
1289
|
else if (invalidation.outcome !== 'no-sessions-file') {
|
|
1299
1290
|
logger.info(TAG, invalidation.message);
|
|
1300
1291
|
}
|
|
1301
|
-
// 4. Send chat message to agent to trigger immediate re-read
|
|
1302
|
-
|
|
1303
|
-
|
|
1304
|
-
|
|
1292
|
+
// 4. Send chat message to agent to trigger immediate re-read — except
|
|
1293
|
+
// while this install's FIRST market check is pending (the heartbeat
|
|
1294
|
+
// job was just created and runFirstHeartbeat is waiting for these
|
|
1295
|
+
// instructions): that check reads them itself, and the notice would
|
|
1296
|
+
// be a second agent turn at the same moment on a new box. The
|
|
1297
|
+
// provider holds the notice and sends it only if the first check
|
|
1298
|
+
// ends without starting, so every other path (existing job, a slow
|
|
1299
|
+
// or blocked pull past the wait, a restart) still gets it.
|
|
1300
|
+
const sendNotice = async () => {
|
|
1301
|
+
try {
|
|
1302
|
+
await this.provider.handleChat(`Your trading instructions (SKILL.md) have been updated to v${version}. ` +
|
|
1303
|
+
`Check for any open positions with fetch_positions() and fetch_open_orders(), then re-read SKILL.md to confirm you've processed the changes.`);
|
|
1304
|
+
}
|
|
1305
|
+
catch (chatErr) {
|
|
1306
|
+
logger.warn(TAG, `Chat notification failed (non-fatal): ${chatErr instanceof Error ? chatErr.message : String(chatErr)}`);
|
|
1307
|
+
}
|
|
1308
|
+
};
|
|
1309
|
+
if (this.provider.deferToFirstMarketCheck?.(() => { void sendNotice(); }) === true) {
|
|
1310
|
+
logger.info(TAG, `SKILL.md v${version} applied while the first market check is pending — chat notice held (sent only if that check does not start)`);
|
|
1305
1311
|
}
|
|
1306
|
-
|
|
1307
|
-
|
|
1312
|
+
else {
|
|
1313
|
+
await sendNotice();
|
|
1308
1314
|
}
|
|
1309
1315
|
// 5. Update local version tracker + advance the replay clock. The clock
|
|
1310
1316
|
// advances ONLY on a VERIFIED signature: recording an unverified
|
|
@@ -24,6 +24,17 @@ export declare function hasConfiguredChannels(cfg: unknown): boolean | undefined
|
|
|
24
24
|
* delivery `announce` can only fail at run time, so switch it to `none`.
|
|
25
25
|
* Runs on every bridge start (cheap: one cron.list), independent of the
|
|
26
26
|
* once-per-install marker, because the job predates this fix on every box.
|
|
27
|
+
*
|
|
28
|
+
* ★ `cron.update` needs operator.admin, which the long-lived session holds
|
|
29
|
+
* only when the process started with the heartbeat ensure owed, so on a box
|
|
30
|
+
* with a marker this patch is refused and nothing changes. That is
|
|
31
|
+
* DELIBERATE (2026-09-29 review): the "no channel" signal
|
|
32
|
+
* (hasConfiguredChannels) reads only the top-level openclaw.json and
|
|
33
|
+
* misreads an env-only Telegram token, `$include`d channels and a moved
|
|
34
|
+
* config dir as "none". Widening the repair (an admin side-session was
|
|
35
|
+
* tried) would silently switch off heartbeat summaries that work today. A
|
|
36
|
+
* wider repair must key off the job's own recorded delivery failure, never
|
|
37
|
+
* this guess.
|
|
27
38
|
*/
|
|
28
39
|
export declare function reconcileHeartbeatDelivery(opts: {
|
|
29
40
|
rpc: CronRpcClient;
|
|
@@ -65,6 +76,16 @@ export declare function pickHeartbeatJob<T extends {
|
|
|
65
76
|
name?: unknown;
|
|
66
77
|
payload?: unknown;
|
|
67
78
|
}>(jobs: readonly T[]): T | undefined;
|
|
79
|
+
/**
|
|
80
|
+
* Is the once-per-install ensure still owed on this box? True with no marker,
|
|
81
|
+
* and with a marker from the old rule that adopted a job that is not
|
|
82
|
+
* ReefClaw's (re-checked once). ensureHeartbeatCron runs exactly when this is
|
|
83
|
+
* true, and the bridge requests operator.admin exactly when this is true:
|
|
84
|
+
* both read this one function so they cannot drift. (They did: the re-check
|
|
85
|
+
* ran on a read/write-only session, so its cron.add failed on the scope and
|
|
86
|
+
* the adopted box kept getting no ReefClaw beat.)
|
|
87
|
+
*/
|
|
88
|
+
export declare function heartbeatEnsureOwed(markerPath: string): boolean;
|
|
68
89
|
export type EnsureHeartbeatOutcome = 'already_ensured' | 'found_existing' | 'created' | 'failed';
|
|
69
90
|
/**
|
|
70
91
|
* Ensure a heartbeat cron exists. Non-fatal by contract: every failure path
|
|
@@ -96,3 +117,46 @@ export declare function ensureHeartbeatCron(opts: {
|
|
|
96
117
|
* `none` (announce can only fail); true/undefined → announce as before. */
|
|
97
118
|
channelsConfigured?: boolean;
|
|
98
119
|
}): Promise<EnsureHeartbeatOutcome>;
|
|
120
|
+
/** How long a fresh install waits for the full trading instructions before
|
|
121
|
+
* starting its first market check. Past this, the first check is left to the
|
|
122
|
+
* regular schedule (one interval later), exactly as before. */
|
|
123
|
+
export declare const FIRST_BEAT_MAX_WAIT_MS = 120000;
|
|
124
|
+
export type FirstBeatOutcome = 'started' | 'not_ready' | 'not_found' | 'not_run' | 'inactive' | 'unknown' | 'failed';
|
|
125
|
+
/**
|
|
126
|
+
* Start the FIRST market check right away on a fresh install instead of one
|
|
127
|
+
* full interval (15 min) after connecting.
|
|
128
|
+
*
|
|
129
|
+
* Why (2026-09-29): a new user connected, saw "You're connected", and then
|
|
130
|
+
* nothing happened for 15 minutes — the job's first run is scheduled one
|
|
131
|
+
* interval after creation. Call this ONLY when ensureHeartbeatCron returned
|
|
132
|
+
* 'created' (a brand-new job, once per install): it must never add beats to
|
|
133
|
+
* an existing agent.
|
|
134
|
+
*
|
|
135
|
+
* Rules:
|
|
136
|
+
* • Waits (≤ FIRST_BEAT_MAX_WAIT_MS) until the full trading SKILL.md is what
|
|
137
|
+
* the agent reads. A beat on the bootstrap instructions would be a wasted
|
|
138
|
+
* run; if they never arrive, the first check stays on the schedule (old
|
|
139
|
+
* behaviour).
|
|
140
|
+
* • `cron.run` needs operator.admin, which the bridge's session holds only
|
|
141
|
+
* when the process started with the ensure owed; call this with the client
|
|
142
|
+
* that created the job.
|
|
143
|
+
* • ONE cron.run call, never retried: a timeout or a dropped socket may
|
|
144
|
+
* still have started the run, and a second call would start a second beat.
|
|
145
|
+
* • Never throws; every failure leaves the regular schedule untouched.
|
|
146
|
+
*/
|
|
147
|
+
export declare function runFirstHeartbeat(opts: {
|
|
148
|
+
rpc: CronRpcClient;
|
|
149
|
+
log: (msg: string) => void;
|
|
150
|
+
agentId?: string;
|
|
151
|
+
agentIsDefault?: boolean;
|
|
152
|
+
/** True once the full trading SKILL.md (not the bootstrap) is what the agent reads. */
|
|
153
|
+
instructionsReady: () => boolean;
|
|
154
|
+
/** False once the connection this was started on is gone (provider stopped
|
|
155
|
+
* or client replaced). Checked while waiting and before each call.
|
|
156
|
+
* Absent = always active. */
|
|
157
|
+
isActive?: () => boolean;
|
|
158
|
+
maxWaitMs?: number;
|
|
159
|
+
pollMs?: number;
|
|
160
|
+
/** Injectable for tests. */
|
|
161
|
+
sleep?: (ms: number) => Promise<void>;
|
|
162
|
+
}): Promise<FirstBeatOutcome>;
|
|
@@ -93,6 +93,17 @@ export function hasConfiguredChannels(cfg) {
|
|
|
93
93
|
* delivery `announce` can only fail at run time, so switch it to `none`.
|
|
94
94
|
* Runs on every bridge start (cheap: one cron.list), independent of the
|
|
95
95
|
* once-per-install marker, because the job predates this fix on every box.
|
|
96
|
+
*
|
|
97
|
+
* ★ `cron.update` needs operator.admin, which the long-lived session holds
|
|
98
|
+
* only when the process started with the heartbeat ensure owed, so on a box
|
|
99
|
+
* with a marker this patch is refused and nothing changes. That is
|
|
100
|
+
* DELIBERATE (2026-09-29 review): the "no channel" signal
|
|
101
|
+
* (hasConfiguredChannels) reads only the top-level openclaw.json and
|
|
102
|
+
* misreads an env-only Telegram token, `$include`d channels and a moved
|
|
103
|
+
* config dir as "none". Widening the repair (an admin side-session was
|
|
104
|
+
* tried) would silently switch off heartbeat summaries that work today. A
|
|
105
|
+
* wider repair must key off the job's own recorded delivery failure, never
|
|
106
|
+
* this guess.
|
|
96
107
|
*/
|
|
97
108
|
export async function reconcileHeartbeatDelivery(opts) {
|
|
98
109
|
if (opts.channelsConfigured !== false)
|
|
@@ -180,6 +191,18 @@ function markerAdoptedForeignJob(markerPath) {
|
|
|
180
191
|
return false;
|
|
181
192
|
}
|
|
182
193
|
}
|
|
194
|
+
/**
|
|
195
|
+
* Is the once-per-install ensure still owed on this box? True with no marker,
|
|
196
|
+
* and with a marker from the old rule that adopted a job that is not
|
|
197
|
+
* ReefClaw's (re-checked once). ensureHeartbeatCron runs exactly when this is
|
|
198
|
+
* true, and the bridge requests operator.admin exactly when this is true:
|
|
199
|
+
* both read this one function so they cannot drift. (They did: the re-check
|
|
200
|
+
* ran on a read/write-only session, so its cron.add failed on the scope and
|
|
201
|
+
* the adopted box kept getting no ReefClaw beat.)
|
|
202
|
+
*/
|
|
203
|
+
export function heartbeatEnsureOwed(markerPath) {
|
|
204
|
+
return !existsSync(markerPath) || markerAdoptedForeignJob(markerPath);
|
|
205
|
+
}
|
|
183
206
|
/**
|
|
184
207
|
* Ensure a heartbeat cron exists. Non-fatal by contract: every failure path
|
|
185
208
|
* returns 'failed' rather than throwing, and only success writes the marker so
|
|
@@ -209,7 +232,7 @@ export async function ensureHeartbeatCron(opts) {
|
|
|
209
232
|
const agentId = opts.agentId?.trim().toLowerCase() || undefined;
|
|
210
233
|
const agentIsDefault = opts.agentIsDefault ?? true;
|
|
211
234
|
try {
|
|
212
|
-
if (
|
|
235
|
+
if (!heartbeatEnsureOwed(markerPath))
|
|
213
236
|
return 'already_ensured';
|
|
214
237
|
// includeDisabled: a job the user disabled still means "exists" — re-adding
|
|
215
238
|
// a duplicate next to a deliberately-disabled one is worse than doing nothing.
|
|
@@ -275,6 +298,21 @@ export async function ensureHeartbeatCron(opts) {
|
|
|
275
298
|
`A heartbeat without it would run on the default agent, not '${agentId}'. Upgrade OpenClaw, or create the job yourself with the agent set.`);
|
|
276
299
|
return 'failed';
|
|
277
300
|
}
|
|
301
|
+
// The failed call may still have created the job (a timeout, a dropped
|
|
302
|
+
// socket). Look again before the retry so it can never add a second job
|
|
303
|
+
// beside it. No usable list = no retry: the next connect lists again and
|
|
304
|
+
// either finds the job or creates it.
|
|
305
|
+
const relist = (await rpc.sendRpc('cron.list', { includeDisabled: true }));
|
|
306
|
+
if (!Array.isArray(relist?.jobs)) {
|
|
307
|
+
log('Heartbeat cron: skipped (the add failed and cron.list returned no job list to check it against)');
|
|
308
|
+
return 'failed';
|
|
309
|
+
}
|
|
310
|
+
const landed = relist.jobs.find((j) => isReefclawHeartbeatJob(j) && cronJobBelongsToAgent(j, agentId, agentIsDefault));
|
|
311
|
+
if (landed) {
|
|
312
|
+
writeMarker(markerPath, { ensuredAt: new Date().toISOString(), created: HEARTBEAT_CRON_NAME, delivery: 'announce' });
|
|
313
|
+
log(`Heartbeat cron: created (${String(landed.name)}; the add reported an error but the job exists)`);
|
|
314
|
+
return 'created';
|
|
315
|
+
}
|
|
278
316
|
log(`Heartbeat cron: announce delivery rejected (${addErr instanceof Error ? addErr.message.split('\n')[0] : String(addErr)}) — retrying without delivery`);
|
|
279
317
|
try {
|
|
280
318
|
await rpc.sendRpc('cron.add', { ...baseJob, delivery: { mode: 'none' } });
|
|
@@ -301,3 +339,114 @@ function writeMarker(markerPath, data) {
|
|
|
301
339
|
mkdirSync(dirname(markerPath), { recursive: true });
|
|
302
340
|
writeFileSync(markerPath, JSON.stringify(data, null, 2) + '\n', 'utf-8');
|
|
303
341
|
}
|
|
342
|
+
/** How long a fresh install waits for the full trading instructions before
|
|
343
|
+
* starting its first market check. Past this, the first check is left to the
|
|
344
|
+
* regular schedule (one interval later), exactly as before. */
|
|
345
|
+
export const FIRST_BEAT_MAX_WAIT_MS = 120_000;
|
|
346
|
+
const FIRST_BEAT_POLL_MS = 5_000;
|
|
347
|
+
/**
|
|
348
|
+
* Start the FIRST market check right away on a fresh install instead of one
|
|
349
|
+
* full interval (15 min) after connecting.
|
|
350
|
+
*
|
|
351
|
+
* Why (2026-09-29): a new user connected, saw "You're connected", and then
|
|
352
|
+
* nothing happened for 15 minutes — the job's first run is scheduled one
|
|
353
|
+
* interval after creation. Call this ONLY when ensureHeartbeatCron returned
|
|
354
|
+
* 'created' (a brand-new job, once per install): it must never add beats to
|
|
355
|
+
* an existing agent.
|
|
356
|
+
*
|
|
357
|
+
* Rules:
|
|
358
|
+
* • Waits (≤ FIRST_BEAT_MAX_WAIT_MS) until the full trading SKILL.md is what
|
|
359
|
+
* the agent reads. A beat on the bootstrap instructions would be a wasted
|
|
360
|
+
* run; if they never arrive, the first check stays on the schedule (old
|
|
361
|
+
* behaviour).
|
|
362
|
+
* • `cron.run` needs operator.admin, which the bridge's session holds only
|
|
363
|
+
* when the process started with the ensure owed; call this with the client
|
|
364
|
+
* that created the job.
|
|
365
|
+
* • ONE cron.run call, never retried: a timeout or a dropped socket may
|
|
366
|
+
* still have started the run, and a second call would start a second beat.
|
|
367
|
+
* • Never throws; every failure leaves the regular schedule untouched.
|
|
368
|
+
*/
|
|
369
|
+
export async function runFirstHeartbeat(opts) {
|
|
370
|
+
const maxWaitMs = opts.maxWaitMs ?? FIRST_BEAT_MAX_WAIT_MS;
|
|
371
|
+
const pollMs = Math.max(1, opts.pollMs ?? FIRST_BEAT_POLL_MS);
|
|
372
|
+
const sleep = opts.sleep ??
|
|
373
|
+
((ms) => new Promise((resolve) => {
|
|
374
|
+
const t = setTimeout(resolve, ms);
|
|
375
|
+
t.unref?.();
|
|
376
|
+
}));
|
|
377
|
+
const ready = () => {
|
|
378
|
+
try {
|
|
379
|
+
return opts.instructionsReady();
|
|
380
|
+
}
|
|
381
|
+
catch {
|
|
382
|
+
return false;
|
|
383
|
+
}
|
|
384
|
+
};
|
|
385
|
+
const active = () => {
|
|
386
|
+
if (!opts.isActive)
|
|
387
|
+
return true;
|
|
388
|
+
try {
|
|
389
|
+
return opts.isActive();
|
|
390
|
+
}
|
|
391
|
+
catch {
|
|
392
|
+
return false;
|
|
393
|
+
}
|
|
394
|
+
};
|
|
395
|
+
const inactive = () => {
|
|
396
|
+
opts.log('Heartbeat cron: first market check not started (the gateway connection it was started on is gone) — it runs on the regular schedule');
|
|
397
|
+
return 'inactive';
|
|
398
|
+
};
|
|
399
|
+
const agentId = opts.agentId?.trim().toLowerCase() || undefined;
|
|
400
|
+
const agentIsDefault = opts.agentIsDefault ?? true;
|
|
401
|
+
try {
|
|
402
|
+
let waited = 0;
|
|
403
|
+
while (!ready() && waited < maxWaitMs) {
|
|
404
|
+
if (!active())
|
|
405
|
+
return inactive();
|
|
406
|
+
await sleep(pollMs);
|
|
407
|
+
waited += pollMs;
|
|
408
|
+
}
|
|
409
|
+
if (!ready()) {
|
|
410
|
+
opts.log('Heartbeat cron: first market check left to the regular schedule (the full trading instructions have not arrived yet)');
|
|
411
|
+
return 'not_ready';
|
|
412
|
+
}
|
|
413
|
+
if (!active())
|
|
414
|
+
return inactive();
|
|
415
|
+
const listResp = (await opts.rpc.sendRpc('cron.list', { includeDisabled: true }));
|
|
416
|
+
const jobs = Array.isArray(listResp?.jobs) ? listResp.jobs : [];
|
|
417
|
+
const job = jobs.find((j) => j?.name === HEARTBEAT_CRON_NAME && cronJobBelongsToAgent(j, agentId, agentIsDefault));
|
|
418
|
+
if (!job || typeof job.id !== 'string' || job.enabled === false) {
|
|
419
|
+
opts.log('Heartbeat cron: first market check not started (the new job is missing or disabled)');
|
|
420
|
+
return 'not_found';
|
|
421
|
+
}
|
|
422
|
+
if (!active())
|
|
423
|
+
return inactive();
|
|
424
|
+
let runResp;
|
|
425
|
+
try {
|
|
426
|
+
runResp = (await opts.rpc.sendRpc('cron.run', { id: job.id }));
|
|
427
|
+
}
|
|
428
|
+
catch (err) {
|
|
429
|
+
// Sent, but no answer we can trust: a timeout or a dropped socket may
|
|
430
|
+
// still have started the run. Report it as unknown (never retried).
|
|
431
|
+
opts.log(`Heartbeat cron: could not confirm the first market check started (${err instanceof Error ? err.message.split('\n')[0] : String(err)}) — if it did not, it runs on the regular schedule`);
|
|
432
|
+
return 'unknown';
|
|
433
|
+
}
|
|
434
|
+
// OpenClaw answers a run it did not start with ran:false + a reason
|
|
435
|
+
// instead of an error ('already-running' = a run is under way anyway).
|
|
436
|
+
if (runResp && typeof runResp === 'object' && (runResp.ran === false || runResp.ok === false)) {
|
|
437
|
+
const reason = typeof runResp.reason === 'string' && runResp.reason ? runResp.reason : 'no reason given';
|
|
438
|
+
if (reason === 'already-running') {
|
|
439
|
+
opts.log('Heartbeat cron: first market check already running');
|
|
440
|
+
return 'started';
|
|
441
|
+
}
|
|
442
|
+
opts.log(`Heartbeat cron: first market check not started now (${reason}) — it runs on the regular schedule`);
|
|
443
|
+
return 'not_run';
|
|
444
|
+
}
|
|
445
|
+
opts.log('Heartbeat cron: first market check started now (the next ones follow on the regular schedule)');
|
|
446
|
+
return 'started';
|
|
447
|
+
}
|
|
448
|
+
catch (err) {
|
|
449
|
+
opts.log(`Heartbeat cron: could not start the first market check now (${err instanceof Error ? err.message.split('\n')[0] : String(err)}) — it runs on the regular schedule`);
|
|
450
|
+
return 'failed';
|
|
451
|
+
}
|
|
452
|
+
}
|
package/bridge/provider.d.ts
CHANGED
|
@@ -152,6 +152,18 @@ export interface OpenClawProvider {
|
|
|
152
152
|
received: boolean;
|
|
153
153
|
error?: string;
|
|
154
154
|
}>;
|
|
155
|
+
/**
|
|
156
|
+
* Hold the bridge's "instructions updated" chat notice while this install's
|
|
157
|
+
* FIRST market check is pending (the heartbeat job was just created and the
|
|
158
|
+
* early run has not started or given up yet): that check reads the new
|
|
159
|
+
* instructions itself, and the notice would be a second agent turn at the
|
|
160
|
+
* same moment. Returns true when the notice was taken (the provider calls
|
|
161
|
+
* `send` if the first check ends without starting, on the next connect if
|
|
162
|
+
* the socket is down at that moment; the latest call wins), false when
|
|
163
|
+
* nothing is pending and the caller should send it now. Absent = never
|
|
164
|
+
* pending.
|
|
165
|
+
*/
|
|
166
|
+
deferToFirstMarketCheck?(send: () => void): boolean;
|
|
155
167
|
/** Close a specific position by symbol (non-emergency, single-symbol close) */
|
|
156
168
|
closePosition(symbol: string): Promise<{
|
|
157
169
|
closed: boolean;
|
|
@@ -54,6 +54,13 @@ export declare class GatewayProvider implements OpenClawProvider {
|
|
|
54
54
|
private agentNameReadAtMs;
|
|
55
55
|
/** One-shot latch for the boot-time heartbeat-cron ensure (re-armed on failure). */
|
|
56
56
|
private heartbeatCronEnsureStarted;
|
|
57
|
+
/** Whether this install's FIRST market check may still run early:
|
|
58
|
+
* 'maybe' while the ensure is in flight, 'pending' from 'created' until
|
|
59
|
+
* runFirstHeartbeat settles, 'none' otherwise (deferToFirstMarketCheck). */
|
|
60
|
+
private firstBeatState;
|
|
61
|
+
/** The bridge's "instructions updated" notice, held while a first check is
|
|
62
|
+
* possible; sent only if that check does not start. Latest wins. */
|
|
63
|
+
private deferredSkillNotice;
|
|
57
64
|
/** Live heartbeat cadence (seconds), read from the OpenClaw cron store; cached 60s. */
|
|
58
65
|
private heartbeatSeconds?;
|
|
59
66
|
private heartbeatReadAtMs;
|
|
@@ -230,6 +237,20 @@ export declare class GatewayProvider implements OpenClawProvider {
|
|
|
230
237
|
received: boolean;
|
|
231
238
|
error?: string;
|
|
232
239
|
}>;
|
|
240
|
+
/** See OpenClawProvider.deferToFirstMarketCheck. Held while this install's
|
|
241
|
+
* first market check may still run early, or while an earlier held notice
|
|
242
|
+
* waits for the socket to come back; the latest notice wins. */
|
|
243
|
+
deferToFirstMarketCheck(send: () => void): boolean;
|
|
244
|
+
/** The first market check is settled: send a held notice ('send') or drop
|
|
245
|
+
* it ('drop': the check started, or may have, and reads the new
|
|
246
|
+
* instructions itself). A stopped provider sends nothing. If the socket is
|
|
247
|
+
* down right now (the settle may be BECAUSE it dropped), the notice stays
|
|
248
|
+
* held and goes out on the next connect (flushHeldSkillNotice) instead of
|
|
249
|
+
* being lost. */
|
|
250
|
+
private settleFirstBeat;
|
|
251
|
+
/** Send a held notice once nothing is pending any more (settle, or the next
|
|
252
|
+
* connect after a settle that found the socket down). */
|
|
253
|
+
private flushHeldSkillNotice;
|
|
233
254
|
closePosition(symbol: string): Promise<{
|
|
234
255
|
closed: boolean;
|
|
235
256
|
symbol: string;
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
// GatewayProvider — real OpenClaw gateway integration.
|
|
2
2
|
// Connects to the OpenClaw gateway via HTTP and WebSocket,
|
|
3
3
|
// streams live trading data, and emits ProviderEvents.
|
|
4
|
-
import {
|
|
4
|
+
import { readFileSync, writeFileSync, mkdirSync, unlinkSync } from 'fs';
|
|
5
5
|
import { join } from 'path';
|
|
6
6
|
import { homedir } from 'os';
|
|
7
7
|
import { logger, formatError } from '../logger.js';
|
|
@@ -16,7 +16,8 @@ import { GatewayWsClient } from '../gateway/gateway-ws-client.js';
|
|
|
16
16
|
import { discoverTools } from '../gateway/tool-discovery.js';
|
|
17
17
|
import { EventParser, mapCcxtBalance, mapCcxtOrder, extractLiquidationFields, extractBracketField, extractPlannedLevels, } from '../gateway/event-parser.js';
|
|
18
18
|
import { Poller } from '../gateway/poller.js';
|
|
19
|
-
import {
|
|
19
|
+
import { readLocalSkillVersion, readAgentVisibleSkillVersions, isBootstrapSkillVersion } from '../utils/skill-version.js';
|
|
20
|
+
import { ensureHeartbeatCron, hasConfiguredChannels, heartbeatEnsureOwed, pickHeartbeatJob, reconcileHeartbeatDelivery, runFirstHeartbeat, } from '../gateway/heartbeat-cron.js';
|
|
20
21
|
import { readOpenClawConfigFile } from '../gateway/gateway-config.js';
|
|
21
22
|
import { parseIdentityName } from '../utils/identity-name.js';
|
|
22
23
|
import { assessDrawdownPlausibility, computeEquity as _computeEquity, computePositionNotional as _computePositionNotional, computeRiskMetrics as _computeRiskMetrics, DEFAULT_RISK_LIMITS, DRAWDOWN_ZONE_THRESHOLDS, TENANT_LIMIT_BOUNDS, boundedNum, validateDrawdownLadder, } from './risk-calculator.js';
|
|
@@ -186,6 +187,13 @@ export class GatewayProvider {
|
|
|
186
187
|
agentNameReadAtMs = 0;
|
|
187
188
|
/** One-shot latch for the boot-time heartbeat-cron ensure (re-armed on failure). */
|
|
188
189
|
heartbeatCronEnsureStarted = false;
|
|
190
|
+
/** Whether this install's FIRST market check may still run early:
|
|
191
|
+
* 'maybe' while the ensure is in flight, 'pending' from 'created' until
|
|
192
|
+
* runFirstHeartbeat settles, 'none' otherwise (deferToFirstMarketCheck). */
|
|
193
|
+
firstBeatState = 'none';
|
|
194
|
+
/** The bridge's "instructions updated" notice, held while a first check is
|
|
195
|
+
* possible; sent only if that check does not start. Latest wins. */
|
|
196
|
+
deferredSkillNotice = null;
|
|
189
197
|
/** Live heartbeat cadence (seconds), read from the OpenClaw cron store; cached 60s. */
|
|
190
198
|
heartbeatSeconds;
|
|
191
199
|
heartbeatReadAtMs = 0;
|
|
@@ -702,6 +710,47 @@ export class GatewayProvider {
|
|
|
702
710
|
return { received: false, error: reason };
|
|
703
711
|
}
|
|
704
712
|
}
|
|
713
|
+
/** See OpenClawProvider.deferToFirstMarketCheck. Held while this install's
|
|
714
|
+
* first market check may still run early, or while an earlier held notice
|
|
715
|
+
* waits for the socket to come back; the latest notice wins. */
|
|
716
|
+
deferToFirstMarketCheck(send) {
|
|
717
|
+
if (this.firstBeatState === 'none' && !this.deferredSkillNotice)
|
|
718
|
+
return false;
|
|
719
|
+
this.deferredSkillNotice = send;
|
|
720
|
+
return true;
|
|
721
|
+
}
|
|
722
|
+
/** The first market check is settled: send a held notice ('send') or drop
|
|
723
|
+
* it ('drop': the check started, or may have, and reads the new
|
|
724
|
+
* instructions itself). A stopped provider sends nothing. If the socket is
|
|
725
|
+
* down right now (the settle may be BECAUSE it dropped), the notice stays
|
|
726
|
+
* held and goes out on the next connect (flushHeldSkillNotice) instead of
|
|
727
|
+
* being lost. */
|
|
728
|
+
settleFirstBeat(action) {
|
|
729
|
+
this.firstBeatState = 'none';
|
|
730
|
+
if (!this.deferredSkillNotice)
|
|
731
|
+
return;
|
|
732
|
+
if (action === 'drop' || !this.started) {
|
|
733
|
+
this.deferredSkillNotice = null;
|
|
734
|
+
return;
|
|
735
|
+
}
|
|
736
|
+
if (this.wsClient?.getState() !== 'connected') {
|
|
737
|
+
logger.info(TAG, 'Held "instructions updated" chat notice kept for the next gateway connect (the socket is down)');
|
|
738
|
+
return;
|
|
739
|
+
}
|
|
740
|
+
this.flushHeldSkillNotice();
|
|
741
|
+
}
|
|
742
|
+
/** Send a held notice once nothing is pending any more (settle, or the next
|
|
743
|
+
* connect after a settle that found the socket down). */
|
|
744
|
+
flushHeldSkillNotice() {
|
|
745
|
+
if (this.firstBeatState !== 'none' || !this.started)
|
|
746
|
+
return;
|
|
747
|
+
const send = this.deferredSkillNotice;
|
|
748
|
+
this.deferredSkillNotice = null;
|
|
749
|
+
if (!send)
|
|
750
|
+
return;
|
|
751
|
+
logger.info(TAG, 'Sending the held "instructions updated" chat notice (the first market check did not start early)');
|
|
752
|
+
send();
|
|
753
|
+
}
|
|
705
754
|
async closePosition(symbol) {
|
|
706
755
|
const tool = this.toolMap.close_position;
|
|
707
756
|
if (!tool || !this.http) {
|
|
@@ -1112,12 +1161,16 @@ export class GatewayProvider {
|
|
|
1112
1161
|
// Step 3: Create WS client and connect FIRST to obtain device token.
|
|
1113
1162
|
// OpenClaw's REST API requires a device token from the WS handshake,
|
|
1114
1163
|
// not the raw gateway auth token. Tool discovery must wait for this.
|
|
1115
|
-
// Least privilege: operator.admin (cron
|
|
1116
|
-
//
|
|
1117
|
-
//
|
|
1164
|
+
// Least privilege: operator.admin (cron.add / cron.run) is requested only
|
|
1165
|
+
// when this process starts with the once-per-install heartbeat ensure
|
|
1166
|
+
// still owed: no marker yet, or an old-rule marker that adopted a job that
|
|
1167
|
+
// is not ReefClaw's (heartbeatEnsureOwed — the same check the ensure
|
|
1168
|
+
// itself runs on, so the re-check always has the scope it needs). This
|
|
1169
|
+
// client keeps the scope across reconnects until the bridge restarts;
|
|
1170
|
+
// every later process runs on operator.read/write alone.
|
|
1118
1171
|
this.wsClient = new GatewayWsClient({
|
|
1119
1172
|
...this.config,
|
|
1120
|
-
requestAdminScope:
|
|
1173
|
+
requestAdminScope: heartbeatEnsureOwed(join(this.workspaceDir(), 'heartbeat-cron-ensured.json')),
|
|
1121
1174
|
});
|
|
1122
1175
|
this.wireWsEvents();
|
|
1123
1176
|
// Wait for WS handshake to complete (or fail)
|
|
@@ -1459,9 +1512,14 @@ export class GatewayProvider {
|
|
|
1459
1512
|
// A box with no chat channel gets delivery `none`: announce can only
|
|
1460
1513
|
// fail there and would record every beat as an error (2026-09-27).
|
|
1461
1514
|
const channelsConfigured = hasConfiguredChannels(readOpenClawConfigFile());
|
|
1515
|
+
const markerPath = join(this.workspaceDir(), 'heartbeat-cron-ensured.json');
|
|
1516
|
+
// A first market check is possible only while the ensure is owed; hold
|
|
1517
|
+
// the bridge's update notice from now until it is known either way.
|
|
1518
|
+
if (heartbeatEnsureOwed(markerPath))
|
|
1519
|
+
this.firstBeatState = 'maybe';
|
|
1462
1520
|
void ensureHeartbeatCron({
|
|
1463
1521
|
rpc: ws,
|
|
1464
|
-
markerPath
|
|
1522
|
+
markerPath,
|
|
1465
1523
|
log: (msg) => logger.info(TAG, msg),
|
|
1466
1524
|
// Scoped to the agent we serve: on a shared gateway the business
|
|
1467
1525
|
// agent's own heartbeat must not suppress the trading agent's, and
|
|
@@ -1473,8 +1531,45 @@ export class GatewayProvider {
|
|
|
1473
1531
|
// A transient failure retries on the next (re)connect, not just next boot.
|
|
1474
1532
|
if (outcome === 'failed') {
|
|
1475
1533
|
this.heartbeatCronEnsureStarted = false;
|
|
1534
|
+
this.settleFirstBeat('send');
|
|
1476
1535
|
return;
|
|
1477
1536
|
}
|
|
1537
|
+
// The job did not exist until now (a fresh install, or a box whose
|
|
1538
|
+
// old marker adopted a job that was not ReefClaw's, so it never had
|
|
1539
|
+
// a ReefClaw beat): run the first market check as soon as the full
|
|
1540
|
+
// instructions are in place instead of one interval later. Same
|
|
1541
|
+
// client — cron.run needs the admin scope this session was opened
|
|
1542
|
+
// with. Never on an existing job ('found_existing' /
|
|
1543
|
+
// 'already_ensured'): that would add beats to a running agent.
|
|
1544
|
+
if (outcome === 'created') {
|
|
1545
|
+
this.firstBeatState = 'pending';
|
|
1546
|
+
void runFirstHeartbeat({
|
|
1547
|
+
rpc: ws,
|
|
1548
|
+
log: (msg) => logger.info(TAG, msg),
|
|
1549
|
+
agentId: this.agentId(),
|
|
1550
|
+
agentIsDefault: this.config.agentIsDefault ?? true,
|
|
1551
|
+
// The tracker copy AND every copy the agent can load: a bootstrap
|
|
1552
|
+
// copy left in an extension or workspace skills dir would make
|
|
1553
|
+
// the first beat a wasted run.
|
|
1554
|
+
instructionsReady: () => {
|
|
1555
|
+
const dir = this.workspaceDir();
|
|
1556
|
+
if (isBootstrapSkillVersion(readLocalSkillVersion(dir)))
|
|
1557
|
+
return false;
|
|
1558
|
+
return readAgentVisibleSkillVersions(dir).every((v) => !isBootstrapSkillVersion(v));
|
|
1559
|
+
},
|
|
1560
|
+
isActive: () => this.started && this.wsClient === ws,
|
|
1561
|
+
})
|
|
1562
|
+
.catch(() => 'failed')
|
|
1563
|
+
// Started, or may have started ('unknown': cron.run was sent
|
|
1564
|
+
// but its answer was lost): the check reads the new
|
|
1565
|
+
// instructions, so a held notice is dropped. Gone ('inactive'):
|
|
1566
|
+
// nothing to tell. Otherwise the held notice goes out, as it
|
|
1567
|
+
// always did.
|
|
1568
|
+
.then((first) => this.settleFirstBeat(first === 'started' || first === 'unknown' || first === 'inactive' ? 'drop' : 'send'));
|
|
1569
|
+
}
|
|
1570
|
+
else {
|
|
1571
|
+
this.settleFirstBeat('send');
|
|
1572
|
+
}
|
|
1478
1573
|
// Existing jobs predate the rule above — repair them in place.
|
|
1479
1574
|
void reconcileHeartbeatDelivery({
|
|
1480
1575
|
rpc: ws,
|
|
@@ -1486,6 +1581,8 @@ export class GatewayProvider {
|
|
|
1486
1581
|
});
|
|
1487
1582
|
}
|
|
1488
1583
|
}
|
|
1584
|
+
// A notice whose first-check settle found the socket down goes out now.
|
|
1585
|
+
this.flushHeldSkillNotice();
|
|
1489
1586
|
// Start periodic agent state emission (every 5s)
|
|
1490
1587
|
if (!this.agentStateInterval) {
|
|
1491
1588
|
this.agentStateInterval = setInterval(() => {
|
|
@@ -29,3 +29,9 @@ export declare function validateSkillContent(content: string): {
|
|
|
29
29
|
version: string | null;
|
|
30
30
|
error?: string;
|
|
31
31
|
};
|
|
32
|
+
/** True while the agent is still on the thin bootstrap SKILL.md and has NOT yet
|
|
33
|
+
* received the full trading instructions. The bootstrap ships 0.0.x; the full
|
|
34
|
+
* trading SKILL.md is 2.x — treat anything below 1.0.0 (or an unknown version)
|
|
35
|
+
* as bootstrap. Shared by the bridge (pull/heal) and the gateway provider
|
|
36
|
+
* (first heartbeat after a fresh install). */
|
|
37
|
+
export declare function isBootstrapSkillVersion(version: string | null | undefined): boolean;
|
|
@@ -128,3 +128,13 @@ export function validateSkillContent(content) {
|
|
|
128
128
|
}
|
|
129
129
|
return { valid: true, version };
|
|
130
130
|
}
|
|
131
|
+
/** True while the agent is still on the thin bootstrap SKILL.md and has NOT yet
|
|
132
|
+
* received the full trading instructions. The bootstrap ships 0.0.x; the full
|
|
133
|
+
* trading SKILL.md is 2.x — treat anything below 1.0.0 (or an unknown version)
|
|
134
|
+
* as bootstrap. Shared by the bridge (pull/heal) and the gateway provider
|
|
135
|
+
* (first heartbeat after a fresh install). */
|
|
136
|
+
export function isBootstrapSkillVersion(version) {
|
|
137
|
+
if (!version)
|
|
138
|
+
return true;
|
|
139
|
+
return compareSemver('1.0.0', version) > 0; // '1.0.0' > version ⟺ version < 1.0.0
|
|
140
|
+
}
|
package/index.js
CHANGED
|
@@ -116,6 +116,7 @@ import { toggleStrategyTool } from './tools/toggle-strategy.js';
|
|
|
116
116
|
import { getPatternScanTool } from './tools/get-pattern-scan.js';
|
|
117
117
|
import { scanPairsTool } from './tools/scan-pairs.js';
|
|
118
118
|
import { getSetupDetailTool } from './tools/get-setup-detail.js';
|
|
119
|
+
import { readAtr14FromFacts } from './tools/intel-cache.js';
|
|
119
120
|
import { queryTradesTool } from './tools/query-trades.js';
|
|
120
121
|
import { getAgentProfileTool } from './tools/get-agent-profile.js';
|
|
121
122
|
import { getCvdTool } from './tools/get-cvd.js';
|
|
@@ -2368,6 +2369,9 @@ const paperTradingPlugin = {
|
|
|
2368
2369
|
approvalMode: resolveApprovalMode(),
|
|
2369
2370
|
wave9AdmissionGuard,
|
|
2370
2371
|
wave9ActivationCheck: () => wave9ActivationClient.getActivation(),
|
|
2372
|
+
// 0.3×ATR term of the stop-distance floor, from the cached intel
|
|
2373
|
+
// fact (fail-open → 30 bps only). See assessment-validation.ts.
|
|
2374
|
+
readAtr14: (symbol) => readAtr14FromFacts(symbol, intelApiDeps),
|
|
2371
2375
|
refreshPaperState: reloadState,
|
|
2372
2376
|
wave9TradingModeCheck: () => runtime.mode,
|
|
2373
2377
|
wave9VenueCheck: () => venue,
|
package/openclaw.plugin.json
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"id": "reefclaw-paper-trading",
|
|
3
3
|
"name": "ReefClaw Trading",
|
|
4
|
-
"version": "0.1.
|
|
4
|
+
"version": "0.1.49",
|
|
5
5
|
"description": "Supervised trading plugin for the ReefClaw dashboard. It runs on YOUR machine and starts in PAPER mode with no API keys. It cannot trade real funds until you supply exchange credentials and step PAPER→MICRO_LIVE→LIVE yourself from the dashboard — the agent cannot make that change (the tool is refused without operator provenance). Exchange keys stay local, are used only to sign requests to the exchange, and are never transmitted to ReefClaw (asserted by a test in this package). Trading telemetry — positions, fills, decision journal — is sent to ReefClaw to render the dashboard. Every live position carries exchange-native protective stops. Remote updates to the agent's trading instructions are applied only after an Ed25519 signature is verified against a public key pinned in this build. It runs on gateway startup and supervises a local connector process; the package README lists every path it writes and everything it sends. It never changes the gateway's auth settings.",
|
|
6
6
|
"author": "ReefClaw",
|
|
7
7
|
"activation": {
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@reefclaw/openclaw-plugin",
|
|
3
|
-
"version": "0.1.
|
|
3
|
+
"version": "0.1.49",
|
|
4
4
|
"description": "ReefClaw supervised trading plugin for OpenClaw. Runs entirely on YOUR machine and starts in PAPER mode — it cannot trade real funds until you supply exchange credentials and walk the PAPER→MICRO_LIVE→LIVE ladder yourself from the ReefClaw dashboard (the agent cannot make that change; it is refused without operator provenance). Your exchange API keys stay on your machine to sign requests to the exchange and are NEVER sent to ReefClaw — a test in the package asserts this. What does reach ReefClaw is trading telemetry for the dashboard (positions, fills, decision journal). Live trading always carries exchange-native protective stops. Trading instructions can be updated remotely, and every update must carry a valid Ed25519 signature verified against a key pinned in this build before it is applied. Install from ClawHub on OpenClaw 2026.8.1+ (Control UI Plugins > Discover, or /plugins install clawhub:@reefclaw/openclaw-plugin then the same with --accept-capabilities after reviewing the listed capabilities), or with the ReefClaw connect installer (@reefclaw/connect on npm, pinned to the exact release named in the bundled skill). It runs on gateway startup, supervises a local connector process, and writes only under ~/.reefclaw and OpenClaw's own skill, config and cron locations; the README lists every path it writes and everything it sends. It never changes the gateway's auth settings.",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"main": "index.js",
|
package/release-integrity.json
CHANGED
|
@@ -38,5 +38,10 @@
|
|
|
38
38
|
"index.js": "47477ea63083abeb07c3088481acd723c0366a9170f6069a67a055362f61a878",
|
|
39
39
|
"tools/create-order.js": "3bf10b657b97fb67fa6a893822929d61ee164d169f6bedf5ec978263b3fb6847",
|
|
40
40
|
"risk/pre-trade-check.js": "5074ac12687d554f9c0a0aee611202aba9ecb4536e4632f8a5c76a5614ae0aad"
|
|
41
|
+
},
|
|
42
|
+
"0.1.48": {
|
|
43
|
+
"index.js": "7ee02a477ed7a508cc0e628f011eb5055e9dc6ad65a383f4830ac4a881c77832",
|
|
44
|
+
"tools/create-order.js": "3bf10b657b97fb67fa6a893822929d61ee164d169f6bedf5ec978263b3fb6847",
|
|
45
|
+
"risk/pre-trade-check.js": "5074ac12687d554f9c0a0aee611202aba9ecb4536e4632f8a5c76a5614ae0aad"
|
|
41
46
|
}
|
|
42
47
|
}
|
package/release-notes.json
CHANGED
|
@@ -18,5 +18,6 @@
|
|
|
18
18
|
"0.1.44": "Heartbeats on a box without a chat channel (no Telegram etc.) are no longer recorded as errors: the heartbeat job is created without a chat delivery, existing jobs are repaired automatically, and a failed announcement no longer counts as a failed heartbeat. get_regime, get_crypto_metrics and get_market_intel now work when called without arguments (they default to your trading symbol / the overview category), which removes the rejected calls seen on OpenClaw 2026.9.",
|
|
19
19
|
"0.1.45": "Every market-data and analysis tool now works when called without a symbol (it uses your configured trading symbol), so agents on OpenClaw 2026.9 no longer waste calls on rejected arguments. Trading actions still require an explicit symbol. The heartbeat prompt no longer sends the agent looking for a checklist file that is not installed.",
|
|
20
20
|
"0.1.47": "Security release (independent audit, 2026-09-27). The heartbeat recorder no longer uploads the output of file and shell tools and scrubs anything key-shaped from what it does record. Dashboard-only settings (trading mode, exchange credentials, the stop requirement) now require a secret the plugin hands to its own connector at start - nothing the agent can read or repeat; plugin and connector must be updated together, which this update does. While trading is live a new entry without a protective stop is refused whatever the settings say, and a stop can no longer be moved wider on a losing position. Risk limits fetched from the server are clamped to hardcoded bounds. The installer pins its runtime dependencies to exact, integrity-checked versions and no longer widens the OpenClaw sandbox allow-list. Market-intel text is fenced against prompt injection in more places, the connector refuses relay hosts outside ReefClaw's, and uploads that hit a rate limit are retried instead of dropped.",
|
|
21
|
-
"0.1.48": "Two changes. The heartbeat checklist (HEARTBEAT.md) now arrives with your trading instructions, signed, and is placed beside SKILL.md, so the agent reads it instead of failing every beat looking for a file that was never installed. And if ReefClaw's own edge protection ever blocks your host's address (an automatic DDoS mitigation, seen once on 2026-09-28), the plugin and connector now recognise it, back off instead of retrying into it, keep trading with the safety floor intact, and report it to the dashboard over the relay so you see a banner and support is paged; the log names the real cause instead of 'connect the account first' or 'Pro subscription required'. Periodic checks are spread out so several agents behind one address no longer call in lockstep. RC_WEBAPP_EDGE_GATE=off disables the back-off only."
|
|
21
|
+
"0.1.48": "Two changes. The heartbeat checklist (HEARTBEAT.md) now arrives with your trading instructions, signed, and is placed beside SKILL.md, so the agent reads it instead of failing every beat looking for a file that was never installed. And if ReefClaw's own edge protection ever blocks your host's address (an automatic DDoS mitigation, seen once on 2026-09-28), the plugin and connector now recognise it, back off instead of retrying into it, keep trading with the safety floor intact, and report it to the dashboard over the relay so you see a banner and support is paged; the log names the real cause instead of 'connect the account first' or 'Pro subscription required'. Periodic checks are spread out so several agents behind one address no longer call in lockstep. RC_WEBAPP_EDGE_GATE=off disables the back-off only.",
|
|
22
|
+
"0.1.49": "Fixes for new and stuck agents. On a fresh install the first market check now starts as soon as the full trading instructions arrive, instead of 15 minutes after connecting. An agent whose ReefClaw heartbeat was never created, because an older version mistook one of your own scheduled jobs for it, now gets the heartbeat with this update and runs its first check straight away. The heartbeat job can no longer be created twice when the gateway answers slowly. New installs from the dashboard's paste message start on the exchange you picked there. New entries now need a stop at least 0.3 x ATR away, the rule the order checks always described (only the 30 bps minimum was enforced before); when ATR is unavailable the 30 bps minimum applies as before. The local signal evaluator (off by default) applies the same minimum stop distance as the server."
|
|
22
23
|
}
|
package/signals/stop-rules.d.ts
CHANGED
|
@@ -1,3 +1,16 @@
|
|
|
1
1
|
import type { MarketContext, Direction } from './types.js';
|
|
2
2
|
import type { StopRuleConfig, ConditionContext } from './conditions/types.js';
|
|
3
|
+
/** Discipline floor for a protective stop, mirrored from the plugin's
|
|
4
|
+
* create_order gate (`validateProtectiveGeometry`): the stop must sit at
|
|
5
|
+
* least max(0.3 × ATR, 30 bps of price) from entry. Applied at SIGNAL time
|
|
6
|
+
* by the strategy adapter and again at FILL time by the backtest engine, so
|
|
7
|
+
* a stop that no exchange order could carry never becomes a signal or a
|
|
8
|
+
* simulated trade (2026-09-28: the swing_atr rule with swingCount 1 was
|
|
9
|
+
* landing stops at or above price after a breakdown; the unsigned risk then
|
|
10
|
+
* produced wrong-side targets and, in the backtester, near-zero-risk trades
|
|
11
|
+
* sized to tens of millions of notional — see
|
|
12
|
+
* memory/project_ardi_report10_backtest_geometry_sep28.md). */
|
|
13
|
+
export declare const MIN_STOP_DISTANCE_BPS = 30;
|
|
14
|
+
export declare const MIN_STOP_ATR_FRACTION = 0.3;
|
|
15
|
+
export declare function stopDistanceFloor(price: number, atr14: number): number;
|
|
3
16
|
export declare function computeStop(rule: StopRuleConfig, ctx: MarketContext, direction: Direction, condCtx: ConditionContext): number;
|
package/signals/stop-rules.js
CHANGED
|
@@ -7,6 +7,22 @@
|
|
|
7
7
|
// @reefclaw/shared runtime code across the deploy boundary.
|
|
8
8
|
// Stop level calculation for declarative strategies.
|
|
9
9
|
import { findSwingPoints } from '../shared/indicators.js';
|
|
10
|
+
/** Discipline floor for a protective stop, mirrored from the plugin's
|
|
11
|
+
* create_order gate (`validateProtectiveGeometry`): the stop must sit at
|
|
12
|
+
* least max(0.3 × ATR, 30 bps of price) from entry. Applied at SIGNAL time
|
|
13
|
+
* by the strategy adapter and again at FILL time by the backtest engine, so
|
|
14
|
+
* a stop that no exchange order could carry never becomes a signal or a
|
|
15
|
+
* simulated trade (2026-09-28: the swing_atr rule with swingCount 1 was
|
|
16
|
+
* landing stops at or above price after a breakdown; the unsigned risk then
|
|
17
|
+
* produced wrong-side targets and, in the backtester, near-zero-risk trades
|
|
18
|
+
* sized to tens of millions of notional — see
|
|
19
|
+
* memory/project_ardi_report10_backtest_geometry_sep28.md). */
|
|
20
|
+
export const MIN_STOP_DISTANCE_BPS = 30;
|
|
21
|
+
export const MIN_STOP_ATR_FRACTION = 0.3;
|
|
22
|
+
export function stopDistanceFloor(price, atr14) {
|
|
23
|
+
const atrFloor = Number.isFinite(atr14) && atr14 > 0 ? atr14 * MIN_STOP_ATR_FRACTION : 0;
|
|
24
|
+
return Math.max(atrFloor, price * (MIN_STOP_DISTANCE_BPS / 10_000));
|
|
25
|
+
}
|
|
10
26
|
export function computeStop(rule, ctx, direction, condCtx) {
|
|
11
27
|
switch (rule.type) {
|
|
12
28
|
case 'swing_atr': {
|
|
@@ -14,15 +30,28 @@ export function computeStop(rule, ctx, direction, condCtx) {
|
|
|
14
30
|
const atrFraction = (rule.params.atrFraction ?? 0.3) * ctx.atr14;
|
|
15
31
|
const fallbackAtrMult = rule.params.fallbackAtrMultiple ?? 2;
|
|
16
32
|
const swings = findSwingPoints(ctx.ohlcv1h.slice(-48), 3);
|
|
33
|
+
// A confirmed swing is always ≥3 bars old. When price has since broken
|
|
34
|
+
// THROUGH it (a breakdown below the last swing low on a long, a breakout
|
|
35
|
+
// above the last swing high on a short), or sits so close that the
|
|
36
|
+
// derived stop is inside the discipline floor, the structural level is
|
|
37
|
+
// not a usable stop — treat both exactly like "no swing" and fall back
|
|
38
|
+
// to the ATR stop. Falling back only on the wrong-side case would leave
|
|
39
|
+
// a dead band (a shallow breakdown yields no signal while a deeper one
|
|
40
|
+
// re-arms on the fallback); the floor check makes the rule continuous.
|
|
41
|
+
const floor = stopDistanceFloor(ctx.currentPrice, ctx.atr14);
|
|
17
42
|
if (direction === 'LONG') {
|
|
18
|
-
|
|
19
|
-
|
|
20
|
-
|
|
43
|
+
const fallback = ctx.currentPrice - ctx.atr14 * fallbackAtrMult;
|
|
44
|
+
if (swings.lows.length === 0)
|
|
45
|
+
return fallback;
|
|
46
|
+
const level = Math.min(...swings.lows.slice(-swingCount)) - atrFraction;
|
|
47
|
+
return ctx.currentPrice - level >= floor ? level : fallback;
|
|
21
48
|
}
|
|
22
49
|
else {
|
|
23
|
-
|
|
24
|
-
|
|
25
|
-
|
|
50
|
+
const fallback = ctx.currentPrice + ctx.atr14 * fallbackAtrMult;
|
|
51
|
+
if (swings.highs.length === 0)
|
|
52
|
+
return fallback;
|
|
53
|
+
const level = Math.max(...swings.highs.slice(-swingCount)) + atrFraction;
|
|
54
|
+
return level - ctx.currentPrice >= floor ? level : fallback;
|
|
26
55
|
}
|
|
27
56
|
}
|
|
28
57
|
case 'recent_extreme_atr': {
|
|
@@ -8,7 +8,7 @@
|
|
|
8
8
|
import { evaluateConditions } from './conditions/registry.js';
|
|
9
9
|
import { resolveDirection } from './direction-rules.js';
|
|
10
10
|
import { computeEntry } from './entry-rules.js';
|
|
11
|
-
import { computeStop } from './stop-rules.js';
|
|
11
|
+
import { computeStop, stopDistanceFloor } from './stop-rules.js';
|
|
12
12
|
import { computeATR } from '../shared/indicators.js';
|
|
13
13
|
/**
|
|
14
14
|
* Higher-timeframe tick gating state, keyed by
|
|
@@ -192,18 +192,37 @@ export function adaptStrategy(config, gateNamespace) {
|
|
|
192
192
|
}
|
|
193
193
|
const allMet = finalConditions.every(c => c.met);
|
|
194
194
|
let trade;
|
|
195
|
+
let geometryRejection;
|
|
195
196
|
if (allMet && direction) {
|
|
196
197
|
const entryZone = computeEntry(config.entryRule, ectx, direction, condCtx);
|
|
197
198
|
const stopLevel = computeStop(config.stopRule, ectx, direction, condCtx);
|
|
199
|
+
// SIGNED risk: negative means the stop is on the wrong side of the
|
|
200
|
+
// signal price. Before 2026-09-28 this was used unsigned — a stop
|
|
201
|
+
// above a long's price produced targets BELOW it and the backtester
|
|
202
|
+
// took |risk|, so a 2-cent stop became a $17M-notional "trade".
|
|
198
203
|
const risk = direction === 'LONG'
|
|
199
204
|
? ectx.currentPrice - stopLevel
|
|
200
205
|
: stopLevel - ectx.currentPrice;
|
|
201
|
-
const
|
|
202
|
-
|
|
203
|
-
|
|
204
|
-
|
|
206
|
+
const floor = stopDistanceFloor(ectx.currentPrice, ectx.atr14);
|
|
207
|
+
// `!(risk >= floor)` also catches NaN (a NaN stop must never emit).
|
|
208
|
+
if (!(risk >= floor)) {
|
|
209
|
+
geometryRejection = {
|
|
210
|
+
reason: !Number.isFinite(risk) ? 'invalid' : risk <= 0 ? 'wrong_side' : 'below_floor',
|
|
211
|
+
stopLevel,
|
|
212
|
+
risk,
|
|
213
|
+
floor,
|
|
214
|
+
};
|
|
215
|
+
}
|
|
216
|
+
else {
|
|
217
|
+
const targets = config.targetRMultiples.map(rm => direction === 'LONG'
|
|
218
|
+
? ectx.currentPrice + risk * rm
|
|
219
|
+
: ectx.currentPrice - risk * rm);
|
|
220
|
+
trade = { entryZone, stopLevel, targets };
|
|
221
|
+
}
|
|
205
222
|
}
|
|
206
|
-
return
|
|
223
|
+
return geometryRejection
|
|
224
|
+
? { direction, conditions: finalConditions, trade, geometryRejection }
|
|
225
|
+
: { direction, conditions: finalConditions, trade };
|
|
207
226
|
},
|
|
208
227
|
};
|
|
209
228
|
}
|
package/skills/reefclaw/SKILL.md
CHANGED
|
@@ -101,7 +101,7 @@ When a user gives you this message (or just a bare `Here's my ReefClaw token: rc
|
|
|
101
101
|
If the ReefClaw trading tools are not present yet, the **user** installs them by running this once, in a terminal on the machine running OpenClaw (inside the container, if OpenClaw runs in Docker):
|
|
102
102
|
|
|
103
103
|
```
|
|
104
|
-
npx --yes @reefclaw/connect@0.1.
|
|
104
|
+
npx --yes @reefclaw/connect@0.1.62
|
|
105
105
|
```
|
|
106
106
|
|
|
107
107
|
That is the whole install. It places the plugin, sets up the connector, restarts the gateway where it can, and prints what it changed. If its closing lines say **GATEWAY NOT RESTARTED**, the plugin is on disk but not running yet: restarting is the user's step (in Docker, `docker restart <container>` from the host; otherwise restarting OpenClaw). Tell the user exactly that and stop — do not restart, signal or kill any process, do not run docker or service commands, and do not edit the gateway config, even if you could. The plugin reports its own version to ReefClaw after the restart; never post readiness, version or health reports yourself. The version is pinned on purpose: the line names the exact connector release this plugin was published with, so what runs on the machine is reviewable and never "whatever the registry serves today". It needs no ReefClaw token — the connection is the separate paste step above, and the connector picks it up on its own.
|
|
@@ -1,8 +1,14 @@
|
|
|
1
1
|
import type { RealizationRule } from '../simulator/types.js';
|
|
2
2
|
/** Minimum pre-entry stop distance in basis points (the SKILL v2.10.0
|
|
3
|
-
* discipline floor's fixed component
|
|
4
|
-
*
|
|
3
|
+
* discipline floor's fixed component). ★ 2026-09-29: the 0.3×ATR component
|
|
4
|
+
* used to exist ONLY in the error text — no code path enforced it (a
|
|
5
|
+
* customer read the compiled module and said so). It is now applied here
|
|
6
|
+
* whenever the caller can supply `atr14` (create_order reads it from the
|
|
7
|
+
* cached intel fact; absent → the fixed 30 bps floor alone, fail-open). */
|
|
5
8
|
export declare const MIN_STOP_DISTANCE_BPS = 30;
|
|
9
|
+
/** Re-exported from the synced signal-side floor so the two can never drift
|
|
10
|
+
* (plugin/src/signals/stop-rules.ts is generated from shared/). */
|
|
11
|
+
export { MIN_STOP_ATR_FRACTION } from '../signals/stop-rules.js';
|
|
6
12
|
export interface ProtectiveGeometryArgs {
|
|
7
13
|
side: 'buy' | 'sell';
|
|
8
14
|
/** Reference entry price: the limit price, or last trade for market orders. */
|
|
@@ -10,6 +16,8 @@ export interface ProtectiveGeometryArgs {
|
|
|
10
16
|
stopPrice?: number;
|
|
11
17
|
invalidationPrice?: number;
|
|
12
18
|
targetPrice?: number;
|
|
19
|
+
/** ATR(14) in price units when known; enables the 0.3×ATR floor term. */
|
|
20
|
+
atr14?: number;
|
|
13
21
|
}
|
|
14
22
|
/** Validate stop / invalidation / target geometry against the entry side.
|
|
15
23
|
*
|
|
@@ -13,11 +13,18 @@
|
|
|
13
13
|
// live mode.
|
|
14
14
|
// Tested in: assessment-validation.test.ts.
|
|
15
15
|
import { normalizeBracketSymbol } from '../live/bracket-ledger.js';
|
|
16
|
+
import { stopDistanceFloor, MIN_STOP_ATR_FRACTION } from '../signals/stop-rules.js';
|
|
16
17
|
// ---- protective geometry (create_order, issue #200) ----
|
|
17
18
|
/** Minimum pre-entry stop distance in basis points (the SKILL v2.10.0
|
|
18
|
-
* discipline floor's fixed component
|
|
19
|
-
*
|
|
19
|
+
* discipline floor's fixed component). ★ 2026-09-29: the 0.3×ATR component
|
|
20
|
+
* used to exist ONLY in the error text — no code path enforced it (a
|
|
21
|
+
* customer read the compiled module and said so). It is now applied here
|
|
22
|
+
* whenever the caller can supply `atr14` (create_order reads it from the
|
|
23
|
+
* cached intel fact; absent → the fixed 30 bps floor alone, fail-open). */
|
|
20
24
|
export const MIN_STOP_DISTANCE_BPS = 30;
|
|
25
|
+
/** Re-exported from the synced signal-side floor so the two can never drift
|
|
26
|
+
* (plugin/src/signals/stop-rules.ts is generated from shared/). */
|
|
27
|
+
export { MIN_STOP_ATR_FRACTION } from '../signals/stop-rules.js';
|
|
21
28
|
/** Validate stop / invalidation / target geometry against the entry side.
|
|
22
29
|
*
|
|
23
30
|
* Before this existed the wrong-side check ran ONLY on the wave9 path
|
|
@@ -41,10 +48,17 @@ export function validateProtectiveGeometry(args) {
|
|
|
41
48
|
`protective stop must be ${side === 'buy' ? 'below' : 'above'} entry. A wrong-side stop is ` +
|
|
42
49
|
`instantly "breached" and the stop-watcher closes the position seconds after entry.`);
|
|
43
50
|
}
|
|
44
|
-
const
|
|
45
|
-
|
|
51
|
+
const distance = Math.abs(refPrice - stop);
|
|
52
|
+
const distanceBps = (distance / refPrice) * 10_000;
|
|
53
|
+
const atr = typeof args.atr14 === 'number' && Number.isFinite(args.atr14) && args.atr14 > 0 ? args.atr14 : null;
|
|
54
|
+
// stopDistanceFloor = max(0.3×ATR, 30 bps of price); with no ATR it is the bps term alone.
|
|
55
|
+
const floor = stopDistanceFloor(refPrice, atr ?? 0);
|
|
56
|
+
if (distance < floor) {
|
|
57
|
+
const atrNote = atr !== null
|
|
58
|
+
? `0.3×ATR = ${(atr * MIN_STOP_ATR_FRACTION / refPrice * 10_000).toFixed(1)}bps (ATR ${atr.toPrecision(4)}) and `
|
|
59
|
+
: '';
|
|
46
60
|
return (`stopPrice ${stop} is only ${distanceBps.toFixed(1)}bps from entry ${refPrice} — below the ` +
|
|
47
|
-
|
|
61
|
+
`discipline floor of max(${atrNote}${MIN_STOP_DISTANCE_BPS}bps). Place the stop at a structural level ` +
|
|
48
62
|
`(≥ max(0.3×ATR, ${MIN_STOP_DISTANCE_BPS}bps) from entry).`);
|
|
49
63
|
}
|
|
50
64
|
}
|
package/tools/create-order.d.ts
CHANGED
|
@@ -77,6 +77,10 @@ export declare function createOrderTool(args: {
|
|
|
77
77
|
available: boolean;
|
|
78
78
|
active: boolean;
|
|
79
79
|
}>;
|
|
80
|
+
/** ATR(14) for the symbol (price units) for the protective-geometry
|
|
81
|
+
* floor's 0.3×ATR term. Optional and FAIL-OPEN: null/throw/slow (>2 s)
|
|
82
|
+
* → the fixed 30 bps floor alone, exactly the pre-2026-09-29 behaviour. */
|
|
83
|
+
readAtr14?: (symbol: string) => Promise<number | null>;
|
|
80
84
|
refreshPaperState?: () => void;
|
|
81
85
|
wave9TradingModeCheck?: () => string;
|
|
82
86
|
wave9VenueCheck?: () => string;
|
package/tools/create-order.js
CHANGED
|
@@ -1006,12 +1006,27 @@ export async function createOrderTool(args, deps) {
|
|
|
1006
1006
|
// by the stop-watcher seconds later (7 sub-5-minute kills on the 2026-07 HL
|
|
1007
1007
|
// soak — one spawned the −$117.86 journal fabrication of issue #199).
|
|
1008
1008
|
if (!wave9Claimed) {
|
|
1009
|
+
// ATR term of the floor (2026-09-29). Bounded so a slow intel read can
|
|
1010
|
+
// never delay an order by more than 2 s; any failure = no ATR = 30 bps only.
|
|
1011
|
+
let atr14;
|
|
1012
|
+
if (deps.readAtr14 && args.stopPrice !== undefined) {
|
|
1013
|
+
// Promise.resolve().then(...) also converts a SYNCHRONOUS throw from the
|
|
1014
|
+
// dep into a rejection — the outer catch would otherwise refuse the
|
|
1015
|
+
// entry (fail-closed) against this gate's fail-open contract.
|
|
1016
|
+
const reader = deps.readAtr14;
|
|
1017
|
+
const read = Promise.resolve().then(() => reader(args.symbol)).catch(() => null);
|
|
1018
|
+
const timeout = new Promise(resolve => { const t = setTimeout(() => resolve(null), 2_000); t.unref?.(); });
|
|
1019
|
+
const v = await Promise.race([read, timeout]);
|
|
1020
|
+
if (typeof v === 'number' && Number.isFinite(v) && v > 0)
|
|
1021
|
+
atr14 = v;
|
|
1022
|
+
}
|
|
1009
1023
|
const geometryError = validateProtectiveGeometry({
|
|
1010
1024
|
side: side,
|
|
1011
1025
|
refPrice: orderPrice,
|
|
1012
1026
|
stopPrice: args.stopPrice,
|
|
1013
1027
|
invalidationPrice: args.invalidation_price,
|
|
1014
1028
|
targetPrice: args.target_price,
|
|
1029
|
+
atr14,
|
|
1015
1030
|
});
|
|
1016
1031
|
if (geometryError) {
|
|
1017
1032
|
return { error: `create_order rejected (protective geometry): ${geometryError}` };
|
package/tools/intel-cache.d.ts
CHANGED
|
@@ -23,3 +23,17 @@ export declare function getStrategiesCached(deps: IntelApiDeps): Promise<Strateg
|
|
|
23
23
|
export declare const __testing__: {
|
|
24
24
|
resetCaches(): void;
|
|
25
25
|
};
|
|
26
|
+
export declare function _resetAtrLastKnownGoodForTests(): void;
|
|
27
|
+
/** ATR(14) for the symbol (price units), for create_order's stop-distance
|
|
28
|
+
* floor. Venue-aware symbol resolution mirrors get_setup_detail (the raw
|
|
29
|
+
* 'AVAX/USDC' form never hits the HL_ cache key). Order of preference:
|
|
30
|
+
* a fact returned within the budget → its atr14 (and remember it);
|
|
31
|
+
* otherwise the last-known-good value if younger than 30 min; otherwise
|
|
32
|
+
* null — the caller fails open to the fixed 30 bps floor. Never throws. */
|
|
33
|
+
export declare function readAtr14FromFacts(rawSymbol: string, deps: IntelApiDeps, opts?: {
|
|
34
|
+
getFact?: (symbol: string, deps: IntelApiDeps) => Promise<SymbolFact | {
|
|
35
|
+
error: string;
|
|
36
|
+
}>;
|
|
37
|
+
now?: () => number;
|
|
38
|
+
budgetMs?: number;
|
|
39
|
+
}): Promise<number | null>;
|
package/tools/intel-cache.js
CHANGED
|
@@ -146,3 +146,62 @@ export const __testing__ = {
|
|
|
146
146
|
symbolFactCache.clear();
|
|
147
147
|
},
|
|
148
148
|
};
|
|
149
|
+
/** Last-known-good ATR per intel symbol. The fact cache is only 30 s and the
|
|
150
|
+
* LLM's gap between scan_pairs and create_order is usually longer, so most
|
|
151
|
+
* entries would miss it and race a network fetch; ATR(14) on 1h bars barely
|
|
152
|
+
* moves in 30 minutes, so a recent value is a better floor input than none. */
|
|
153
|
+
const atrLastKnownGood = new Map();
|
|
154
|
+
const ATR_LKG_TTL_MS = 30 * 60_000;
|
|
155
|
+
/** Give the fact fetch this long before falling back to the last-known-good
|
|
156
|
+
* value; the fetch keeps running and warms the cache for the next call. */
|
|
157
|
+
const ATR_FETCH_BUDGET_MS = 1_500;
|
|
158
|
+
export function _resetAtrLastKnownGoodForTests() {
|
|
159
|
+
atrLastKnownGood.clear();
|
|
160
|
+
}
|
|
161
|
+
/** ATR(14) for the symbol (price units), for create_order's stop-distance
|
|
162
|
+
* floor. Venue-aware symbol resolution mirrors get_setup_detail (the raw
|
|
163
|
+
* 'AVAX/USDC' form never hits the HL_ cache key). Order of preference:
|
|
164
|
+
* a fact returned within the budget → its atr14 (and remember it);
|
|
165
|
+
* otherwise the last-known-good value if younger than 30 min; otherwise
|
|
166
|
+
* null — the caller fails open to the fixed 30 bps floor. Never throws. */
|
|
167
|
+
export async function readAtr14FromFacts(rawSymbol, deps, opts = {}) {
|
|
168
|
+
const now = opts.now ?? Date.now;
|
|
169
|
+
const budgetMs = opts.budgetMs ?? ATR_FETCH_BUDGET_MS;
|
|
170
|
+
const getFact = opts.getFact ?? getFactBySymbolCached;
|
|
171
|
+
let symbol;
|
|
172
|
+
try {
|
|
173
|
+
symbol = (deps.venue ?? 'binance') === 'hyperliquid'
|
|
174
|
+
? resolveIntelSymbol(deps, rawSymbol)
|
|
175
|
+
: String(rawSymbol ?? '').toUpperCase().replace(/[^A-Z0-9]/g, '');
|
|
176
|
+
}
|
|
177
|
+
catch {
|
|
178
|
+
return null;
|
|
179
|
+
}
|
|
180
|
+
const fromLkg = () => {
|
|
181
|
+
const lkg = atrLastKnownGood.get(symbol);
|
|
182
|
+
return lkg && now() - lkg.at <= ATR_LKG_TTL_MS ? lkg.atr : null;
|
|
183
|
+
};
|
|
184
|
+
try {
|
|
185
|
+
const fetch = Promise.resolve().then(() => getFact(symbol, deps)).then((fact) => {
|
|
186
|
+
if ('error' in fact)
|
|
187
|
+
return null;
|
|
188
|
+
const raw = fact.indicators?.atr14;
|
|
189
|
+
const n = typeof raw === 'number' ? raw : typeof raw === 'string' ? Number(raw) : Number.NaN;
|
|
190
|
+
if (!Number.isFinite(n) || n <= 0)
|
|
191
|
+
return null;
|
|
192
|
+
atrLastKnownGood.set(symbol, { atr: n, at: now() });
|
|
193
|
+
return n;
|
|
194
|
+
}).catch(() => null);
|
|
195
|
+
let timer;
|
|
196
|
+
const budget = new Promise((resolve) => { timer = setTimeout(() => resolve('timeout'), budgetMs); timer.unref?.(); });
|
|
197
|
+
const raced = await Promise.race([fetch, budget]);
|
|
198
|
+
if (timer)
|
|
199
|
+
clearTimeout(timer);
|
|
200
|
+
if (raced === 'timeout')
|
|
201
|
+
return fromLkg();
|
|
202
|
+
return raced ?? fromLkg();
|
|
203
|
+
}
|
|
204
|
+
catch {
|
|
205
|
+
return fromLkg();
|
|
206
|
+
}
|
|
207
|
+
}
|