@reefclaw/openclaw-plugin 0.1.30 → 0.1.34
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.d.ts +20 -1
- package/bridge/bridge.js +22 -8
- package/bridge/gateway/agent-scope.d.ts +47 -6
- package/bridge/gateway/agent-scope.js +89 -11
- package/bridge/gateway/gateway-config.d.ts +20 -0
- package/bridge/gateway/gateway-config.js +43 -5
- package/bridge/gateway/heartbeat-cron.d.ts +17 -0
- package/bridge/gateway/heartbeat-cron.js +42 -3
- package/bridge/gateway/poller.d.ts +9 -1
- package/bridge/gateway/poller.js +11 -1
- package/bridge/heartbeat-runs.d.ts +20 -2
- package/bridge/heartbeat-runs.js +62 -8
- package/bridge/heartbeat-transcript.d.ts +58 -1
- package/bridge/heartbeat-transcript.js +187 -18
- package/bridge/index.js +51 -35
- package/bridge/providers/connector-update.d.ts +5 -0
- package/bridge/providers/connector-update.js +5 -1
- package/bridge/providers/gateway.d.ts +3 -0
- package/bridge/providers/gateway.js +94 -41
- package/bridge/providers/risk-calculator.d.ts +31 -0
- package/bridge/providers/risk-calculator.js +41 -1
- package/bridge/utils/skill-version.d.ts +1 -1
- package/bridge/utils/skill-version.js +4 -3
- package/bridge/utils/skills-snapshot-invalidation.d.ts +1 -1
- package/bridge/utils/skills-snapshot-invalidation.js +2 -2
- package/openclaw.plugin.json +1 -1
- package/package.json +1 -1
- package/release-notes.json +3 -1
|
@@ -16,7 +16,7 @@ import { EventParser, mapCcxtBalance, mapCcxtOrder, extractLiquidationFields, ex
|
|
|
16
16
|
import { Poller } from '../gateway/poller.js';
|
|
17
17
|
import { ensureHeartbeatCron, isHeartbeatLikeName } from '../gateway/heartbeat-cron.js';
|
|
18
18
|
import { parseIdentityName } from '../utils/identity-name.js';
|
|
19
|
-
import { computeEquity as _computeEquity, computePositionNotional as _computePositionNotional, computeRiskMetrics as _computeRiskMetrics, DEFAULT_RISK_LIMITS, DRAWDOWN_ZONE_THRESHOLDS, TENANT_LIMIT_BOUNDS, boundedNum, validateDrawdownLadder, } from './risk-calculator.js';
|
|
19
|
+
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';
|
|
20
20
|
import { executeKill as _executeKill, executeFlatten as _executeFlatten, executePause as _executePause, executeResume as _executeResume, cancelPendingProposals, withProposalDetail, } from './emergency-commands.js';
|
|
21
21
|
import { executeSetTradingMode, executeGetBracketConfig, executeSetBracketRequirement, executeSetExchangeCredentials, executeTestExchangeCredentials, executeClearExchangeCredentials, executeProvisionHlAgentWallet, executeHlAgentWalletStatus, executeSubmitHlAgentApproval, } from './onboarding-commands.js';
|
|
22
22
|
import { startConnectorUpdate, runConnectorUpdate, openAdminGatewaySession, checkPositionGuard, describeUpdateDisabled, } from './connector-update.js';
|
|
@@ -32,14 +32,19 @@ const TAG = 'gateway';
|
|
|
32
32
|
const DAY_NAV_FILENAME = 'day-start-nav.json';
|
|
33
33
|
const LEGACY_DAY_NAV_FILENAME = 'session-nav.json';
|
|
34
34
|
const TRADING_MODE_FILENAME = 'trading-mode.json';
|
|
35
|
-
|
|
36
|
-
|
|
35
|
+
/** The legacy single-agent workspace - what every box used before the bridge
|
|
36
|
+
* learned to follow a non-default agent (gateway/agent-scope.ts). Still the
|
|
37
|
+
* path for the default agent, so existing day-NAV/trading-mode files are
|
|
38
|
+
* read from exactly where they were written. */
|
|
39
|
+
const LEGACY_WORKSPACE_DIR = join(homedir(), '.openclaw', 'workspace');
|
|
40
|
+
function getDayNavPath(workspaceDir) {
|
|
41
|
+
return join(workspaceDir, DAY_NAV_FILENAME);
|
|
37
42
|
}
|
|
38
|
-
function getLegacyDayNavPath() {
|
|
39
|
-
return join(
|
|
43
|
+
function getLegacyDayNavPath(workspaceDir) {
|
|
44
|
+
return join(workspaceDir, LEGACY_DAY_NAV_FILENAME);
|
|
40
45
|
}
|
|
41
|
-
function getTradingModePath() {
|
|
42
|
-
return join(
|
|
46
|
+
function getTradingModePath(workspaceDir) {
|
|
47
|
+
return join(workspaceDir, TRADING_MODE_FILENAME);
|
|
43
48
|
}
|
|
44
49
|
function todayDateStr() {
|
|
45
50
|
return new Date().toISOString().slice(0, 10);
|
|
@@ -70,8 +75,8 @@ export function shouldSyncPluginSessionNav(pluginNav, currentNav) {
|
|
|
70
75
|
&& pluginNav > 0
|
|
71
76
|
&& Math.abs(currentNav - pluginNav) > 0.001;
|
|
72
77
|
}
|
|
73
|
-
function loadSessionStartNav() {
|
|
74
|
-
for (const path of [getDayNavPath(), getLegacyDayNavPath()]) {
|
|
78
|
+
function loadSessionStartNav(workspaceDir) {
|
|
79
|
+
for (const path of [getDayNavPath(workspaceDir), getLegacyDayNavPath(workspaceDir)]) {
|
|
75
80
|
try {
|
|
76
81
|
const raw = readFileSync(path, 'utf-8');
|
|
77
82
|
const data = JSON.parse(raw);
|
|
@@ -95,9 +100,9 @@ function loadSessionStartNav() {
|
|
|
95
100
|
* trading_mode event in fetchFreshBalance() — but until then, this prevents
|
|
96
101
|
* the visible PAPER flash.
|
|
97
102
|
*/
|
|
98
|
-
function loadLastTradingMode() {
|
|
103
|
+
function loadLastTradingMode(workspaceDir) {
|
|
99
104
|
try {
|
|
100
|
-
const raw = readFileSync(getTradingModePath(), 'utf-8');
|
|
105
|
+
const raw = readFileSync(getTradingModePath(workspaceDir), 'utf-8');
|
|
101
106
|
const data = JSON.parse(raw);
|
|
102
107
|
if (isTradingMode(data.mode)) {
|
|
103
108
|
return data.mode;
|
|
@@ -108,25 +113,23 @@ function loadLastTradingMode() {
|
|
|
108
113
|
return null;
|
|
109
114
|
}
|
|
110
115
|
}
|
|
111
|
-
function saveLastTradingMode(mode) {
|
|
116
|
+
function saveLastTradingMode(workspaceDir, mode) {
|
|
112
117
|
try {
|
|
113
|
-
|
|
114
|
-
mkdirSync(dir, { recursive: true });
|
|
118
|
+
mkdirSync(workspaceDir, { recursive: true });
|
|
115
119
|
const data = { mode, savedAt: new Date().toISOString() };
|
|
116
|
-
writeFileSync(getTradingModePath(), JSON.stringify(data, null, 2), 'utf-8');
|
|
120
|
+
writeFileSync(getTradingModePath(workspaceDir), JSON.stringify(data, null, 2), 'utf-8');
|
|
117
121
|
}
|
|
118
122
|
catch {
|
|
119
123
|
/* non-fatal — next save will retry */
|
|
120
124
|
}
|
|
121
125
|
}
|
|
122
|
-
function saveSessionStartNav(nav) {
|
|
126
|
+
function saveSessionStartNav(workspaceDir, nav) {
|
|
123
127
|
try {
|
|
124
|
-
|
|
125
|
-
mkdirSync(dir, { recursive: true });
|
|
128
|
+
mkdirSync(workspaceDir, { recursive: true });
|
|
126
129
|
const data = { date: todayDateStr(), sessionStartNav: nav };
|
|
127
|
-
writeFileSync(getDayNavPath(), JSON.stringify(data, null, 2), 'utf-8');
|
|
130
|
+
writeFileSync(getDayNavPath(workspaceDir), JSON.stringify(data, null, 2), 'utf-8');
|
|
128
131
|
try {
|
|
129
|
-
unlinkSync(getLegacyDayNavPath());
|
|
132
|
+
unlinkSync(getLegacyDayNavPath(workspaceDir));
|
|
130
133
|
}
|
|
131
134
|
catch { /* legacy file already gone */ }
|
|
132
135
|
}
|
|
@@ -167,6 +170,11 @@ export class GatewayProvider {
|
|
|
167
170
|
agentId() {
|
|
168
171
|
return this.config.agentId ?? DEFAULT_AGENT_ID;
|
|
169
172
|
}
|
|
173
|
+
/** The served agent's OpenClaw workspace (gateway-config.ts resolves it by
|
|
174
|
+
* OpenClaw's own rule); the legacy path for hand-built configs. */
|
|
175
|
+
workspaceDir() {
|
|
176
|
+
return this.config.agentWorkspaceDir ?? LEGACY_WORKSPACE_DIR;
|
|
177
|
+
}
|
|
170
178
|
/** Emit the one-time rollout probe (gateway response shape) only on the first attempt. */
|
|
171
179
|
loggedAgentIdentityProbe = false;
|
|
172
180
|
/** Last IDENTITY.md read (epoch ms) — TTL gate for the display-name re-read. */
|
|
@@ -310,7 +318,7 @@ export class GatewayProvider {
|
|
|
310
318
|
// mode change. Falls back to 'PAPER' only on first-ever boot (or after
|
|
311
319
|
// file is corrupt/deleted). Prevents the "dashboard flashes PAPER on every
|
|
312
320
|
// skill restart" UX bug — see saveLastTradingMode() comment above.
|
|
313
|
-
tradingMode =
|
|
321
|
+
tradingMode = 'PAPER';
|
|
314
322
|
listeners = {
|
|
315
323
|
ticker: new Set(),
|
|
316
324
|
candle: new Set(),
|
|
@@ -339,6 +347,9 @@ export class GatewayProvider {
|
|
|
339
347
|
};
|
|
340
348
|
constructor(config) {
|
|
341
349
|
this.config = config;
|
|
350
|
+
// Field initialisers run before parameter properties are assigned, so the
|
|
351
|
+
// workspace-dependent restore happens here, not on the field.
|
|
352
|
+
this.tradingMode = loadLastTradingMode(this.workspaceDir()) ?? 'PAPER';
|
|
342
353
|
// Extract quote currency from symbol (e.g. "BTC/USDT" -> "USDT")
|
|
343
354
|
const parts = config.symbol.split('/');
|
|
344
355
|
this.quoteCurrency = parts.length > 1 ? parts[1] : 'USDT';
|
|
@@ -768,7 +779,14 @@ export class GatewayProvider {
|
|
|
768
779
|
return { ok: false, status: 'failed', message: 'Not connected to the OpenClaw gateway.' };
|
|
769
780
|
}
|
|
770
781
|
const openPositionCount = this.positions.filter((p) => Math.abs(Number(p.contracts) || 0) > 0).length;
|
|
771
|
-
const guardArgs = {
|
|
782
|
+
const guardArgs = {
|
|
783
|
+
acknowledgeOpenPositions: args.acknowledgeOpenPositions,
|
|
784
|
+
openPositionCount,
|
|
785
|
+
// On a multi-agent gateway OpenClaw 2026.9 refuses an owner-less
|
|
786
|
+
// terminal.open ("no explicit owner"); the PTY belongs to the agent we
|
|
787
|
+
// serve. Single-agent boxes keep the historical request.
|
|
788
|
+
...(this.config.agentSharedGateway ? { agentId: this.agentId() } : {}),
|
|
789
|
+
};
|
|
772
790
|
// Position guard FIRST — never open an admin session for a request that is
|
|
773
791
|
// going to be refused anyway.
|
|
774
792
|
const blocked = checkPositionGuard(guardArgs);
|
|
@@ -999,7 +1017,7 @@ export class GatewayProvider {
|
|
|
999
1017
|
// the marker exists, every session runs on operator.read/write alone.
|
|
1000
1018
|
this.wsClient = new GatewayWsClient({
|
|
1001
1019
|
...this.config,
|
|
1002
|
-
requestAdminScope: !existsSync(join(
|
|
1020
|
+
requestAdminScope: !existsSync(join(this.workspaceDir(), 'heartbeat-cron-ensured.json')),
|
|
1003
1021
|
});
|
|
1004
1022
|
this.wireWsEvents();
|
|
1005
1023
|
// Wait for WS handshake to complete (or fail)
|
|
@@ -1240,7 +1258,7 @@ export class GatewayProvider {
|
|
|
1240
1258
|
logger.error(TAG, `positions handler failed: ${formatError(err)}`);
|
|
1241
1259
|
});
|
|
1242
1260
|
},
|
|
1243
|
-
onBalance: (balance) => this.onPollerBalance(balance),
|
|
1261
|
+
onBalance: (balance, extras) => this.onPollerBalance(balance, extras),
|
|
1244
1262
|
onOpenOrders: (orders) => this.onPollerOpenOrders(orders),
|
|
1245
1263
|
onMarketStructure: (data) => this.onPollerMarketStructure(data),
|
|
1246
1264
|
onCryptoMetrics: (data) => this.onPollerCryptoMetrics(data),
|
|
@@ -1361,8 +1379,13 @@ export class GatewayProvider {
|
|
|
1361
1379
|
if (ws) {
|
|
1362
1380
|
void ensureHeartbeatCron({
|
|
1363
1381
|
rpc: ws,
|
|
1364
|
-
markerPath: join(
|
|
1382
|
+
markerPath: join(this.workspaceDir(), 'heartbeat-cron-ensured.json'),
|
|
1365
1383
|
log: (msg) => logger.info(TAG, msg),
|
|
1384
|
+
// Scoped to the agent we serve: on a shared gateway the business
|
|
1385
|
+
// agent's own heartbeat must not suppress the trading agent's, and
|
|
1386
|
+
// a non-default agent's job carries agentId so it runs THERE.
|
|
1387
|
+
agentId: this.agentId(),
|
|
1388
|
+
agentIsDefault: this.config.agentIsDefault ?? true,
|
|
1366
1389
|
}).then((outcome) => {
|
|
1367
1390
|
// A transient failure retries on the next (re)connect, not just next boot.
|
|
1368
1391
|
if (outcome === 'failed')
|
|
@@ -1752,7 +1775,12 @@ export class GatewayProvider {
|
|
|
1752
1775
|
const action = isClose ? 'CLOSE' : 'OPEN';
|
|
1753
1776
|
this.emitTradeJournal(pos.symbol, side, action, quantity, fillPrice);
|
|
1754
1777
|
}
|
|
1755
|
-
onPollerBalance(balance) {
|
|
1778
|
+
onPollerBalance(balance, extras) {
|
|
1779
|
+
// Keep today's realized P&L as fresh as the wallet: the RED-zone
|
|
1780
|
+
// plausibility bound (assessDrawdownPlausibility) needs it on every
|
|
1781
|
+
// evaluation, and fetchFreshBalance() only runs on a reconnect snapshot.
|
|
1782
|
+
if (typeof extras?.realizedPnlToday === 'number')
|
|
1783
|
+
this.realizedPnlToday = extras.realizedPnlToday;
|
|
1756
1784
|
// Defensive guard: never downgrade a known-good wallet balance to zero.
|
|
1757
1785
|
// Binance Futures 429 rate-limits were causing fetchBalance responses
|
|
1758
1786
|
// to come back with an empty currency map; mapCcxtBalance then returned
|
|
@@ -1801,7 +1829,7 @@ export class GatewayProvider {
|
|
|
1801
1829
|
// Try loading from file first (persisted across restarts within same day).
|
|
1802
1830
|
// loadSessionStartNav() itself returns null on a different day, so on a
|
|
1803
1831
|
// fresh UTC day this falls through to recompute.
|
|
1804
|
-
const saved = loadSessionStartNav();
|
|
1832
|
+
const saved = loadSessionStartNav(this.workspaceDir());
|
|
1805
1833
|
if (saved !== null) {
|
|
1806
1834
|
this.sessionStartNav = saved;
|
|
1807
1835
|
this.sessionDate = today;
|
|
@@ -1811,7 +1839,7 @@ export class GatewayProvider {
|
|
|
1811
1839
|
// First anchor of the (UTC) day — compute and persist.
|
|
1812
1840
|
this.sessionStartNav = this.computeEquity();
|
|
1813
1841
|
this.sessionDate = today;
|
|
1814
|
-
saveSessionStartNav(this.sessionStartNav);
|
|
1842
|
+
saveSessionStartNav(this.workspaceDir(), this.sessionStartNav);
|
|
1815
1843
|
logger.info(TAG, `Session start NAV: ${this.sessionStartNav} ${this.quoteCurrency} (wallet=${this.balance.total}, positions=${this.positions.length})`);
|
|
1816
1844
|
}
|
|
1817
1845
|
onPollerOpenOrders(orders) {
|
|
@@ -1934,7 +1962,7 @@ export class GatewayProvider {
|
|
|
1934
1962
|
// up reading the correct value instead of the 'PAPER' constructor
|
|
1935
1963
|
// default. Cheap, idempotent — safe to write on every balance fetch
|
|
1936
1964
|
// even when no transition happened.
|
|
1937
|
-
saveLastTradingMode(mode);
|
|
1965
|
+
saveLastTradingMode(this.workspaceDir(), mode);
|
|
1938
1966
|
if (mode !== this.tradingMode) {
|
|
1939
1967
|
const prevMode = this.tradingMode;
|
|
1940
1968
|
this.tradingMode = mode;
|
|
@@ -1954,11 +1982,11 @@ export class GatewayProvider {
|
|
|
1954
1982
|
this.hasReceivedPositions = false;
|
|
1955
1983
|
this.pendingEmptyPoll = false;
|
|
1956
1984
|
try {
|
|
1957
|
-
unlinkSync(getDayNavPath());
|
|
1985
|
+
unlinkSync(getDayNavPath(this.workspaceDir()));
|
|
1958
1986
|
}
|
|
1959
1987
|
catch { /* ok if missing */ }
|
|
1960
1988
|
try {
|
|
1961
|
-
unlinkSync(getLegacyDayNavPath());
|
|
1989
|
+
unlinkSync(getLegacyDayNavPath(this.workspaceDir()));
|
|
1962
1990
|
}
|
|
1963
1991
|
catch { /* ok if missing */ }
|
|
1964
1992
|
logger.info(TAG, `Session start NAV reset on mode change (${prevMode} → ${this.tradingMode})`);
|
|
@@ -2007,7 +2035,7 @@ export class GatewayProvider {
|
|
|
2007
2035
|
// Stamp the day so the PAPER self-seed path (shouldAnchorSessionNav
|
|
2008
2036
|
// re-anchors on a stale sessionDate) doesn't flap against the sync.
|
|
2009
2037
|
this.sessionDate = todayDateStr();
|
|
2010
|
-
saveSessionStartNav(pluginNav);
|
|
2038
|
+
saveSessionStartNav(this.workspaceDir(), pluginNav);
|
|
2011
2039
|
logger.info(TAG, `Session start NAV synced from plugin: ${prev.toFixed(4)} -> ${pluginNav} (${this.tradingMode} mode)`);
|
|
2012
2040
|
}
|
|
2013
2041
|
}
|
|
@@ -2389,7 +2417,8 @@ export class GatewayProvider {
|
|
|
2389
2417
|
resolveAgentNameFromIdentity() {
|
|
2390
2418
|
const candidates = [
|
|
2391
2419
|
process.env.OPENCLAW_WORKSPACE ? join(process.env.OPENCLAW_WORKSPACE, 'IDENTITY.md') : undefined,
|
|
2392
|
-
join(
|
|
2420
|
+
join(this.workspaceDir(), 'IDENTITY.md'),
|
|
2421
|
+
join(LEGACY_WORKSPACE_DIR, 'IDENTITY.md'),
|
|
2393
2422
|
].filter((p) => !!p);
|
|
2394
2423
|
for (const p of candidates) {
|
|
2395
2424
|
try {
|
|
@@ -2553,10 +2582,13 @@ export class GatewayProvider {
|
|
|
2553
2582
|
// only — a $186 account with a $20 short showed as -89% drawdown, triggering
|
|
2554
2583
|
// an auto-flatten loop every minute. If we don't have fresh wallet data we
|
|
2555
2584
|
// cannot trust the drawdown number; wait for the next poll.
|
|
2556
|
-
// 3.
|
|
2557
|
-
//
|
|
2558
|
-
//
|
|
2559
|
-
//
|
|
2585
|
+
// 3. Plausibility bound (Ardi, report #6 — replaces the old "-50% feels
|
|
2586
|
+
// impossible" constant): a book cannot lose more than what is open
|
|
2587
|
+
// (at entry) plus what it already realized today. A claimed loss
|
|
2588
|
+
// beyond that is a calculation artifact — log loudly and refuse
|
|
2589
|
+
// instead of closing real positions on it. True at every account
|
|
2590
|
+
// size, paper and live alike; the -50% constant only remains as the
|
|
2591
|
+
// fallback while today's realized P&L is still unknown.
|
|
2560
2592
|
// 4. Persistence debounce (issue #213): the balance poll and the position
|
|
2561
2593
|
// snapshot are not atomic. In PAPER mode the simulator deducts FULL
|
|
2562
2594
|
// NOTIONAL from the wallet at open, so in the seconds after a fill the
|
|
@@ -2605,19 +2637,40 @@ export class GatewayProvider {
|
|
|
2605
2637
|
// component is the worse failure direction, so the tear only ever BUYS
|
|
2606
2638
|
// TIME; past the ceiling the ordinary #213 debounce governs again.
|
|
2607
2639
|
const tornSnapshotBlocks = !positionsCoverLatestFill && redForMs < MAX_TORN_SNAPSHOT_DEFER_MS;
|
|
2640
|
+
// Ardi #6: the claimed loss versus what THIS book could have lost —
|
|
2641
|
+
// computed from the same snapshot, so a torn one (missing notional)
|
|
2642
|
+
// shows up as a loss the known positions cannot explain.
|
|
2643
|
+
const plausibility = assessDrawdownPlausibility({
|
|
2644
|
+
sessionStartNav: this.sessionStartNav,
|
|
2645
|
+
equity: this.computeEquity(),
|
|
2646
|
+
positions: this.positions,
|
|
2647
|
+
realizedPnlToday: this.realizedPnlToday,
|
|
2648
|
+
});
|
|
2649
|
+
const impossibleForBook = plausibility.verdict === 'impossible' ||
|
|
2650
|
+
(plausibility.verdict === 'unknown' && metrics.utilization.dailyDrawdown < IMPOSSIBLE_DRAWDOWN);
|
|
2608
2651
|
if (uptimeMs < STARTUP_GRACE_PERIOD_MS) {
|
|
2609
2652
|
logger.warn(TAG, `RED zone drawdown detected (${metrics.drawdownZoneMessage}) but within startup grace period (${Math.round(uptimeMs / 1000)}s) — skipping auto-flatten`);
|
|
2610
2653
|
}
|
|
2611
2654
|
else if (!this.hasReceivedBalance || this.balance.total <= 0) {
|
|
2612
2655
|
logger.warn(TAG, `RED zone drawdown detected (${metrics.drawdownZoneMessage}) but balance data is stale/missing (received=${this.hasReceivedBalance}, total=${this.balance.total}) — skipping auto-flatten, waiting for fresh wallet data`);
|
|
2613
2656
|
}
|
|
2614
|
-
else if (
|
|
2615
|
-
|
|
2657
|
+
else if (tornSnapshotBlocks) {
|
|
2658
|
+
// The snapshot is torn BY DEFINITION (a fill debited the wallet after
|
|
2659
|
+
// the last positions refresh) — the verdict is not evidence of
|
|
2660
|
+
// anything yet. Close the tear now instead of waiting out the 10 s
|
|
2661
|
+
// poll, and say so at info: this is the expected paper fill race,
|
|
2662
|
+
// not an alarm (it read as one — Ardi #6).
|
|
2663
|
+
logger.info(TAG, `RED verdict on a torn snapshot (${metrics.drawdownZoneMessage}; fill ${Math.round((Date.now() - this.lastFillAt) / 1000)}s ago, positions from ${Math.round((Date.now() - this.positionsUpdatedAt) / 1000)}s ago) — refreshing positions before judging it`);
|
|
2664
|
+
void this.poller?.refreshPositionsNow().catch((err) => {
|
|
2665
|
+
logger.debug(TAG, `positions refresh after torn snapshot failed: ${formatError(err)}`);
|
|
2666
|
+
});
|
|
2667
|
+
}
|
|
2668
|
+
else if (impossibleForBook) {
|
|
2669
|
+
logger.error(TAG, `RED zone drawdown ${(metrics.utilization.dailyDrawdown * 100).toFixed(1)}% is more than this book could have lost (claimed ${plausibility.claimedLossUsd.toFixed(2)} vs open-at-entry ${plausibility.entryGrossUsd.toFixed(2)} + realized-today ${plausibility.realizedLossUsd?.toFixed(2) ?? 'unknown'}${plausibility.verdict === 'unknown' ? `; sanity floor ${IMPOSSIBLE_DRAWDOWN * 100}%` : ''}) — refusing auto-flatten, equity input is wrong (balance.total=${this.balance.total}, sessionStartNav=${this.sessionStartNav}, positions=${this.positions.length})`);
|
|
2616
2670
|
}
|
|
2617
2671
|
else if (this.redZoneStreak < REQUIRED_RED_STREAK ||
|
|
2618
2672
|
redForMs < MIN_RED_PERSISTENCE_MS ||
|
|
2619
|
-
!survivedPositionsRefresh
|
|
2620
|
-
tornSnapshotBlocks) {
|
|
2673
|
+
!survivedPositionsRefresh) {
|
|
2621
2674
|
logger.warn(TAG, `RED zone drawdown detected (${metrics.drawdownZoneMessage}) — deferring auto-flatten until the verdict persists (streak ${this.redZoneStreak}/${REQUIRED_RED_STREAK}, ${Math.round(redForMs / 1000)}s/${MIN_RED_PERSISTENCE_MS / 1000}s, survivedPositionsRefresh=${survivedPositionsRefresh}, positionsCoverLatestFill=${positionsCoverLatestFill}, tornSnapshotBlocks=${tornSnapshotBlocks}). A fresh entry's notional reads as phantom drawdown until the position snapshot catches up (issues #213/#248); a real drawdown will persist and flatten on a later evaluation.`);
|
|
2622
2675
|
}
|
|
2623
2676
|
else {
|
|
@@ -102,6 +102,37 @@ export declare function applyVolatilityAdjustment(baseLimits: RiskLimits, volFac
|
|
|
102
102
|
export declare function getDrawdownZone(drawdownRatio: number, thresholds?: DrawdownThresholds): DrawdownZone;
|
|
103
103
|
/** Human-readable message for a drawdown zone. */
|
|
104
104
|
export declare function getDrawdownZoneMessage(zone: DrawdownZone, ratio: number): string;
|
|
105
|
+
export interface DrawdownPlausibility {
|
|
106
|
+
/** 'impossible' = the claimed loss exceeds what this book could have lost;
|
|
107
|
+
* 'unknown' = no session anchor or today's realized P&L not known yet. */
|
|
108
|
+
verdict: 'plausible' | 'impossible' | 'unknown';
|
|
109
|
+
claimedLossUsd: number;
|
|
110
|
+
/** Σ |contracts| × contractSize × entryPrice — what computeEquity adds back. */
|
|
111
|
+
entryGrossUsd: number;
|
|
112
|
+
realizedLossUsd: number | null;
|
|
113
|
+
boundUsd: number | null;
|
|
114
|
+
}
|
|
115
|
+
/** Fees, funding and mark noise on the open book — the bound is not exact. A
|
|
116
|
+
* torn snapshot is missing a whole entry's notional (≥ the 2.5% RED threshold
|
|
117
|
+
* of NAV by construction), so 1% of NAV of slack cannot hide one. */
|
|
118
|
+
export declare const PLAUSIBILITY_SLACK_RATIO = 0.01;
|
|
119
|
+
/**
|
|
120
|
+
* Can this book have lost what the drawdown claims? Without leverage a
|
|
121
|
+
* position cannot lose more than its ENTRY notional (a long can go to zero; a
|
|
122
|
+
* short past +100% is stopped by brackets long before), and what is no longer
|
|
123
|
+
* open can only have contributed what was realized today. Anything beyond
|
|
124
|
+
* `entryGross + realizedLoss` was never lost — it is notional the snapshot does
|
|
125
|
+
* not know about (paper debits full notional at open; positions catch up on
|
|
126
|
+
* their own poll). Entry notional, NOT mark: a long that has fallen far has a
|
|
127
|
+
* mark notional smaller than its own loss and would be refused wrongly.
|
|
128
|
+
* Refuse-only by construction: this can never license a flatten.
|
|
129
|
+
*/
|
|
130
|
+
export declare function assessDrawdownPlausibility(i: {
|
|
131
|
+
sessionStartNav: number;
|
|
132
|
+
equity: number;
|
|
133
|
+
positions: CcxtPosition[];
|
|
134
|
+
realizedPnlToday: number | null | undefined;
|
|
135
|
+
}): DrawdownPlausibility;
|
|
105
136
|
/**
|
|
106
137
|
* Compute true equity: wallet + entry_notional (margin held) + unrealized P&L per position.
|
|
107
138
|
*
|
|
@@ -140,9 +140,49 @@ export function getDrawdownZoneMessage(zone, ratio) {
|
|
|
140
140
|
case 'GREEN': return `Green zone (${pct}%) — full trading`;
|
|
141
141
|
case 'YELLOW': return `Yellow zone (${pct}%) — position sizes halved`;
|
|
142
142
|
case 'ORANGE': return `Orange zone (${pct}%) — new entries blocked, exits only`;
|
|
143
|
-
|
|
143
|
+
// The bridge's zone ARMS the auto-flatten; entry rejection is the plugin's
|
|
144
|
+
// own pre-trade zone (plugin/src/risk/pre-trade-check.ts), computed from
|
|
145
|
+
// its consistent equity. "all orders rejected" here read as an event that
|
|
146
|
+
// never happened (Ardi, report #6).
|
|
147
|
+
case 'RED': return `Red zone (${pct}%) — auto-flatten armed`;
|
|
144
148
|
}
|
|
145
149
|
}
|
|
150
|
+
/** Fees, funding and mark noise on the open book — the bound is not exact. A
|
|
151
|
+
* torn snapshot is missing a whole entry's notional (≥ the 2.5% RED threshold
|
|
152
|
+
* of NAV by construction), so 1% of NAV of slack cannot hide one. */
|
|
153
|
+
export const PLAUSIBILITY_SLACK_RATIO = 0.01;
|
|
154
|
+
/**
|
|
155
|
+
* Can this book have lost what the drawdown claims? Without leverage a
|
|
156
|
+
* position cannot lose more than its ENTRY notional (a long can go to zero; a
|
|
157
|
+
* short past +100% is stopped by brackets long before), and what is no longer
|
|
158
|
+
* open can only have contributed what was realized today. Anything beyond
|
|
159
|
+
* `entryGross + realizedLoss` was never lost — it is notional the snapshot does
|
|
160
|
+
* not know about (paper debits full notional at open; positions catch up on
|
|
161
|
+
* their own poll). Entry notional, NOT mark: a long that has fallen far has a
|
|
162
|
+
* mark notional smaller than its own loss and would be refused wrongly.
|
|
163
|
+
* Refuse-only by construction: this can never license a flatten.
|
|
164
|
+
*/
|
|
165
|
+
export function assessDrawdownPlausibility(i) {
|
|
166
|
+
let entryGrossUsd = 0;
|
|
167
|
+
for (const pos of i.positions) {
|
|
168
|
+
entryGrossUsd += Math.abs(pos.contracts ?? 0) * (pos.contractSize ?? 1) * (pos.entryPrice ?? 0);
|
|
169
|
+
}
|
|
170
|
+
const claimedLossUsd = i.sessionStartNav > 0 ? Math.max(0, i.sessionStartNav - i.equity) : 0;
|
|
171
|
+
const realizedKnown = typeof i.realizedPnlToday === 'number' && Number.isFinite(i.realizedPnlToday);
|
|
172
|
+
if (i.sessionStartNav <= 0 || !realizedKnown) {
|
|
173
|
+
return { verdict: 'unknown', claimedLossUsd, entryGrossUsd, realizedLossUsd: null, boundUsd: null };
|
|
174
|
+
}
|
|
175
|
+
const realizedLossUsd = Math.max(0, -i.realizedPnlToday);
|
|
176
|
+
const boundUsd = entryGrossUsd + realizedLossUsd;
|
|
177
|
+
const slack = i.sessionStartNav * PLAUSIBILITY_SLACK_RATIO;
|
|
178
|
+
return {
|
|
179
|
+
verdict: claimedLossUsd > boundUsd + slack ? 'impossible' : 'plausible',
|
|
180
|
+
claimedLossUsd,
|
|
181
|
+
entryGrossUsd,
|
|
182
|
+
realizedLossUsd,
|
|
183
|
+
boundUsd,
|
|
184
|
+
};
|
|
185
|
+
}
|
|
146
186
|
// ---- Pure functions ----
|
|
147
187
|
/**
|
|
148
188
|
* Compute true equity: wallet + entry_notional (margin held) + unrealized P&L per position.
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
/** Extract version from SKILL.md frontmatter */
|
|
2
2
|
export declare function parseSkillVersion(content: string): string | null;
|
|
3
3
|
/** Read current SKILL.md version from disk */
|
|
4
|
-
export declare function readLocalSkillVersion(): string | null;
|
|
4
|
+
export declare function readLocalSkillVersion(workspaceDir?: string): string | null;
|
|
5
5
|
/** Versions of the AGENT-VISIBLE reefclaw SKILL.md copies under the
|
|
6
6
|
* plugin-extension layout (`~/.openclaw/extensions/<plugin>/skills/<skill>/`)
|
|
7
7
|
* — what OpenClaw's skill loader actually reads on chat-channel installs.
|
|
@@ -2,16 +2,17 @@
|
|
|
2
2
|
import { readFileSync, readdirSync } from 'fs';
|
|
3
3
|
import { join } from 'path';
|
|
4
4
|
import { homedir } from 'os';
|
|
5
|
-
|
|
5
|
+
/** Legacy single-agent location; callers serving another agent pass its workspace. */
|
|
6
|
+
const DEFAULT_WORKSPACE_DIR = join(homedir(), '.openclaw', 'workspace');
|
|
6
7
|
/** Extract version from SKILL.md frontmatter */
|
|
7
8
|
export function parseSkillVersion(content) {
|
|
8
9
|
const match = content.match(/^---[\s\S]*?version:\s*(\S+)[\s\S]*?---/);
|
|
9
10
|
return match ? match[1] : null;
|
|
10
11
|
}
|
|
11
12
|
/** Read current SKILL.md version from disk */
|
|
12
|
-
export function readLocalSkillVersion() {
|
|
13
|
+
export function readLocalSkillVersion(workspaceDir = DEFAULT_WORKSPACE_DIR) {
|
|
13
14
|
try {
|
|
14
|
-
const content = readFileSync(
|
|
15
|
+
const content = readFileSync(join(workspaceDir, 'SKILL.md'), 'utf-8');
|
|
15
16
|
return parseSkillVersion(content);
|
|
16
17
|
}
|
|
17
18
|
catch {
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
/** Default location of OpenClaw's session index. */
|
|
2
|
-
export declare function defaultSessionsJsonPath(): string;
|
|
2
|
+
export declare function defaultSessionsJsonPath(agentId?: string): string;
|
|
3
3
|
export type SnapshotInvalidationOutcome =
|
|
4
4
|
/** Removed the key from >= 1 session entry — the agent will re-read SKILL.md. */
|
|
5
5
|
'invalidated'
|
|
@@ -28,8 +28,8 @@ import { existsSync, readFileSync, writeFileSync } from 'fs';
|
|
|
28
28
|
import { join } from 'path';
|
|
29
29
|
import { homedir } from 'os';
|
|
30
30
|
/** Default location of OpenClaw's session index. */
|
|
31
|
-
export function defaultSessionsJsonPath() {
|
|
32
|
-
return join(homedir(), '.openclaw', 'agents',
|
|
31
|
+
export function defaultSessionsJsonPath(agentId = 'main') {
|
|
32
|
+
return join(homedir(), '.openclaw', 'agents', agentId, 'sessions', 'sessions.json');
|
|
33
33
|
}
|
|
34
34
|
/**
|
|
35
35
|
* Surgically delete every `skillsSnapshot` key from sessions.json, preserving
|
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.34",
|
|
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.",
|
|
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.34",
|
|
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: npx --yes @reefclaw/connect, or 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)",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"main": "index.js",
|
package/release-notes.json
CHANGED
|
@@ -3,5 +3,7 @@
|
|
|
3
3
|
"0.1.27": "Fixes paper positions showing as closed at $0 in the Journal while still open, and adds a 2-minute grace to the position reconciler.",
|
|
4
4
|
"0.1.28": "Fixes the connector's gateway handshake on OpenClaw 2026.9+ (it now connects as OpenClaw's local-backend client) and adds in-app update notices with one-click updates.",
|
|
5
5
|
"0.1.29": "Paper stop and target fills now use the price the decision was made on when the cached order book is stale (paper P&L gets more honest); on a gateway with several agents the connector shows only its own agent's runs; one-click updates can be switched off per box.",
|
|
6
|
-
"0.1.30": "Restores the connector's version reporting, so the dashboard's update notice works again for boxes that already updated (0.1.28 and 0.1.29 reported no version and could not be nudged)."
|
|
6
|
+
"0.1.30": "Restores the connector's version reporting, so the dashboard's update notice works again for boxes that already updated (0.1.28 and 0.1.29 reported no version and could not be nudged).",
|
|
7
|
+
"0.1.33": "Adds npx @reefclaw/connect --agent <id> for gateways that host several agents: the trading skill, heartbeat and dashboard attach to that agent and the trading tools are denied to the others.",
|
|
8
|
+
"0.1.34": "The heartbeat flight recorder now reads OpenClaw 2026.9's SQLite transcript store (it recorded nothing on those gateways) and warns when it cannot see beats; a RED-zone drawdown is re-checked on a fresh position snapshot before it is judged, and a loss larger than the open book plus today's realized losses is refused as a calculation error instead of trusting a -50% constant; RC_SHOCK_WAKE=off switches shock wakes off per box; the README lists what the connector sends and how to read the risk log."
|
|
7
9
|
}
|