@reefclaw/openclaw-plugin 0.1.13 → 0.1.14

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (48) hide show
  1. package/bridge/gateway/gateway-config.d.ts +16 -5
  2. package/bridge/gateway/gateway-config.js +68 -12
  3. package/bridge/gateway/poller.js +18 -8
  4. package/bridge/providers/emergency-commands.d.ts +9 -1
  5. package/bridge/providers/emergency-commands.js +38 -1
  6. package/bridge/providers/gateway.d.ts +23 -1
  7. package/bridge/providers/gateway.js +79 -17
  8. package/bridge/providers/onboarding-commands.d.ts +8 -0
  9. package/bridge/providers/onboarding-commands.js +4 -4
  10. package/ccxt/binance-public.d.ts +17 -5
  11. package/ccxt/binance-public.js +31 -3
  12. package/config/operator-provenance.d.ts +6 -0
  13. package/config/operator-provenance.js +50 -0
  14. package/config/plugin-config-io.d.ts +15 -1
  15. package/config/plugin-config-io.js +24 -0
  16. package/index.js +216 -173
  17. package/ingest/event-loop-monitor.d.ts +11 -0
  18. package/ingest/event-loop-monitor.js +113 -0
  19. package/ingest/position-auto-capture.d.ts +5 -0
  20. package/ingest/position-auto-capture.js +14 -5
  21. package/ingest/readiness-reporter.d.ts +17 -6
  22. package/ingest/readiness-reporter.js +88 -9
  23. package/ingest/skill-version-reader.d.ts +16 -0
  24. package/ingest/skill-version-reader.js +64 -0
  25. package/live/approval-lifecycle.d.ts +30 -0
  26. package/live/approval-lifecycle.js +80 -0
  27. package/live/bracket-types.d.ts +9 -0
  28. package/live/live-adapter.d.ts +0 -1
  29. package/onboarding/runtime.d.ts +34 -1
  30. package/onboarding/runtime.js +56 -5
  31. package/openclaw.plugin.json +1 -1
  32. package/package.json +2 -2
  33. package/simulator/exchange-simulator.d.ts +45 -2
  34. package/simulator/exchange-simulator.js +96 -4
  35. package/simulator/types.d.ts +17 -0
  36. package/tools/attach-brackets.js +50 -1
  37. package/venues/hyperliquid/hl-bracket-coordinator.d.ts +25 -1
  38. package/venues/hyperliquid/hl-bracket-coordinator.js +57 -0
  39. package/venues/hyperliquid/hl-brackets.d.ts +10 -0
  40. package/venues/hyperliquid/hl-brackets.js +45 -13
  41. package/venues/hyperliquid/hl-fill-ingest.d.ts +18 -0
  42. package/venues/hyperliquid/hl-fill-ingest.js +69 -0
  43. package/venues/hyperliquid/hl-live-adapter.d.ts +32 -0
  44. package/venues/hyperliquid/hl-live-adapter.js +112 -7
  45. package/venues/hyperliquid/hl-public.d.ts +12 -5
  46. package/venues/hyperliquid/hl-public.js +24 -3
  47. package/venues/hyperliquid/hl-user-stream.d.ts +13 -1
  48. package/venues/hyperliquid/hl-user-stream.js +4 -1
@@ -3,14 +3,31 @@ import type { ExchangeConfig, TradingMode } from '../types.js';
3
3
  import type { ExchangeSimulator } from '../simulator/exchange-simulator.js';
4
4
  import type { PaperMarketFeed } from '../simulator/paper-market-feed.js';
5
5
  import { LiveAdapter } from '../live/live-adapter.js';
6
+ import { HyperliquidLiveAdapter } from '../venues/hyperliquid/hl-live-adapter.js';
6
7
  import type { HlCredentials } from '../venues/hyperliquid/hl-private.js';
7
8
  import { type VenueId } from '../venues/registry.js';
8
9
  import { PositionWatcher } from '../live/stop-watcher.js';
10
+ import type { TradeStoreClient } from '../ingest/trade-store-client.js';
11
+ import type { AutoCaptureContext } from '../ingest/position-auto-capture.js';
9
12
  import type { TradingOperationLock } from '../lifecycle/trading-operation-lock.js';
10
13
  export interface MicroLiveConfig {
11
- sizeCapPercent?: number;
12
14
  maxPositionUSDT?: number;
13
15
  }
16
+ /** Boot-constructed live wiring reapplied to EVERY adapter build (audit
17
+ * 2026-07-26 F9). Reconnects previously rebuilt adapters with only the
18
+ * bracket mode — silently reverting WS authority to REST, dropping the
19
+ * audit-trail ingest, and losing journal auto-capture until restart. The
20
+ * clients live for the process lifetime (the SIGTERM drain holds them), so
21
+ * rebuilds must REUSE them, never re-instantiate. */
22
+ export interface LiveAdapterWiring {
23
+ /** Base of TradeIngestWiring — `exchange` is stamped per build from the
24
+ * TARGET venue (fillExchangeId), because a venue flip changes it. */
25
+ tradeIngestBase?: {
26
+ client: TradeStoreClient;
27
+ userId: string;
28
+ };
29
+ autoCapture?: AutoCaptureContext;
30
+ }
14
31
  export interface BuildAdapterInput {
15
32
  mode: TradingMode;
16
33
  exchange: ExchangeConfig | null;
@@ -24,6 +41,8 @@ export interface BuildAdapterInput {
24
41
  venue?: VenueId;
25
42
  /** Required for a live-mode build on the hyperliquid venue. */
26
43
  hlCredentials?: HlCredentials | null;
44
+ /** Boot wiring reapplied on every build — see LiveAdapterWiring (F9). */
45
+ wiring?: LiveAdapterWiring;
27
46
  }
28
47
  /** Wave 9 safety wiring is created only after its durable ledger is loaded.
29
48
  * Runtime reapplies these hooks to both the bootstrap objects and every
@@ -62,6 +81,17 @@ export declare class PluginRuntime {
62
81
  * for watcher closes (issue #199) — without it, a live<->paper reconnect
63
82
  * would silently shed the capture wiring. */
64
83
  private readonly onWatcherCreated?;
84
+ /** Observer applied to EVERY live adapter this runtime creates (audit F9,
85
+ * same pattern as onWatcherCreated). index.ts uses it to install the
86
+ * drift_detected → journal close-bypass cleanup listener — previously
87
+ * installed only on the BOOT adapter and lost on every reconnect. */
88
+ private readonly onAdapterCreated?;
89
+ /** Boot live wiring threaded into every buildAdapter call (audit F9). */
90
+ private readonly liveWiring?;
91
+ /** Fired after EVERY reconnect publishes its adapter (paper ones included) —
92
+ * set post-construction because its consumer (the approval-listener
93
+ * lifecycle, audit F10) is built after the runtime. */
94
+ private onAdapterSwapped?;
65
95
  /** Reconnect is serialized — a second caller waits for the first to finish
66
96
  * so we never tear down an adapter that's mid-rebuild. */
67
97
  private reconnectInFlight;
@@ -73,11 +103,14 @@ export declare class PluginRuntime {
73
103
  marketFeed?: PaperMarketFeed | null;
74
104
  operationLock?: TradingOperationLock;
75
105
  onWatcherCreated?: (watcher: PositionWatcher) => void;
106
+ onAdapterCreated?: (adapter: LiveAdapter | HyperliquidLiveAdapter) => void;
107
+ liveWiring?: LiveAdapterWiring;
76
108
  });
77
109
  get adapter(): IExchangeAdapter;
78
110
  get mode(): TradingMode;
79
111
  get stopWatcher(): PositionWatcher | null;
80
112
  get marketFeed(): PaperMarketFeed | null;
113
+ setOnAdapterSwapped(cb?: (adapter: IExchangeAdapter) => void): void;
81
114
  setWave9LiveLifecycleHooks(hooks?: Wave9LiveLifecycleHooks): void;
82
115
  /**
83
116
  * Swap the current adapter for a new one built from `next`. The old
@@ -14,10 +14,11 @@
14
14
  import { PaperAdapter } from '../paper-adapter.js';
15
15
  import { LiveAdapter } from '../live/live-adapter.js';
16
16
  import { HyperliquidLiveAdapter } from '../venues/hyperliquid/hl-live-adapter.js';
17
- import { createLiveAdapter } from '../venues/registry.js';
17
+ import { createLiveAdapter, fillExchangeId } from '../venues/registry.js';
18
18
  import { PositionWatcher } from '../live/stop-watcher.js';
19
19
  import { loadBracketMode } from '../config/brackets-config.js';
20
- import { loadStopWatcherIntervalMs, readPluginConfig } from '../config/plugin-config-io.js';
20
+ import { loadMicroLiveConfig, loadStopWatcherIntervalMs, readPluginConfig } from '../config/plugin-config-io.js';
21
+ import { loadUserDataStreamMode, loadUserDataStreamTunables } from '../config/user-data-stream-config.js';
21
22
  import { logger, formatError } from '../logger.js';
22
23
  const TAG = 'plugin-runtime';
23
24
  /** Pure-ish factory: builds an adapter for the requested mode.
@@ -25,12 +26,27 @@ const TAG = 'plugin-runtime';
25
26
  * callers should pre-validate via `modeRequiresCredentials`, but this
26
27
  * defense-in-depth prevents a crash if validation is bypassed. */
27
28
  export function buildAdapter(input) {
28
- const { mode, exchange, microLive, simulator } = input;
29
+ const { mode, exchange, simulator } = input;
29
30
  if (mode === 'PAPER' || mode === 'SHADOW') {
30
31
  // Shadow mode uses a paper adapter for execution; the separate
31
32
  // ShadowTracker wraps a BinancePrivateApi for real-balance comparison.
32
33
  return new PaperAdapter(simulator);
33
34
  }
35
+ // Micro-live cap resolves from plugin-config at adapter build time when the
36
+ // caller didn't pass one — every reconnect path (mode flip, credential save)
37
+ // used to omit it, silently resetting an operator-raised OR -lowered cap
38
+ // back to the $50 default (audit 2026-07-26 F8).
39
+ const microLive = input.microLive ?? loadMicroLiveConfig();
40
+ // Audit-trail ingest (F9): reuse the boot-constructed client, stamp the
41
+ // exchange id from the TARGET venue (a venue flip changes it; the id is
42
+ // half of the trades idempotency key and must never be stale or minted).
43
+ const tradeIngest = input.wiring?.tradeIngestBase
44
+ ? {
45
+ client: input.wiring.tradeIngestBase.client,
46
+ userId: input.wiring.tradeIngestBase.userId,
47
+ exchange: fillExchangeId(input.venue ?? 'binance'),
48
+ }
49
+ : undefined;
34
50
  // Hyperliquid live (issue #217): mirror the boot path's construction —
35
51
  // per-venue credential shape, the SAME factory (createLiveAdapter), and
36
52
  // the same fall-back-to-paper defense when credentials are absent.
@@ -45,6 +61,8 @@ export function buildAdapter(input) {
45
61
  credentials: input.hlCredentials,
46
62
  mode: mode,
47
63
  marketSlippagePct: readPluginConfig().hl?.marketSlippagePct,
64
+ microLive,
65
+ tradeIngest,
48
66
  },
49
67
  });
50
68
  }
@@ -55,7 +73,12 @@ export function buildAdapter(input) {
55
73
  // Read bracket-mode from plugin-config at adapter build time so a config
56
74
  // flip + "Reconnect Exchange" pattern picks up the new mode on the next swap.
57
75
  const bracketMode = loadBracketMode();
58
- return new LiveAdapter(exchange, mode, microLive, bracketMode);
76
+ // Same read-at-build-time rule for the user-data stream (F9): a rebuilt
77
+ // adapter wires its WS at construction, so passing nothing here reverted
78
+ // prod's `enforce` to REST-only polling on every dashboard reconnect.
79
+ const userDataStreamMode = loadUserDataStreamMode();
80
+ const userDataStreamTunables = loadUserDataStreamTunables();
81
+ return new LiveAdapter(exchange, mode, microLive, bracketMode, userDataStreamMode, userDataStreamTunables, tradeIngest, input.wiring?.autoCapture);
59
82
  }
60
83
  /**
61
84
  * Mutable runtime holder. Held once per plugin registration.
@@ -82,6 +105,17 @@ export class PluginRuntime {
82
105
  * for watcher closes (issue #199) — without it, a live<->paper reconnect
83
106
  * would silently shed the capture wiring. */
84
107
  onWatcherCreated;
108
+ /** Observer applied to EVERY live adapter this runtime creates (audit F9,
109
+ * same pattern as onWatcherCreated). index.ts uses it to install the
110
+ * drift_detected → journal close-bypass cleanup listener — previously
111
+ * installed only on the BOOT adapter and lost on every reconnect. */
112
+ onAdapterCreated;
113
+ /** Boot live wiring threaded into every buildAdapter call (audit F9). */
114
+ liveWiring;
115
+ /** Fired after EVERY reconnect publishes its adapter (paper ones included) —
116
+ * set post-construction because its consumer (the approval-listener
117
+ * lifecycle, audit F10) is built after the runtime. */
118
+ onAdapterSwapped;
85
119
  /** Reconnect is serialized — a second caller waits for the first to finish
86
120
  * so we never tear down an adapter that's mid-rebuild. */
87
121
  reconnectInFlight = null;
@@ -93,11 +127,16 @@ export class PluginRuntime {
93
127
  this._marketFeed = initial.marketFeed ?? null;
94
128
  this.operationLock = initial.operationLock;
95
129
  this.onWatcherCreated = initial.onWatcherCreated;
130
+ this.onAdapterCreated = initial.onAdapterCreated;
131
+ this.liveWiring = initial.liveWiring;
96
132
  }
97
133
  get adapter() { return this._adapter; }
98
134
  get mode() { return this._mode; }
99
135
  get stopWatcher() { return this._stopWatcher; }
100
136
  get marketFeed() { return this._marketFeed; }
137
+ setOnAdapterSwapped(cb) {
138
+ this.onAdapterSwapped = cb;
139
+ }
101
140
  setWave9LiveLifecycleHooks(hooks) {
102
141
  this.wave9LiveLifecycleHooks = hooks;
103
142
  if (this._adapter instanceof LiveAdapter) {
@@ -160,7 +199,9 @@ export class PluginRuntime {
160
199
  logger.warn(TAG, `old HL adapter stop failed: ${formatError(err)}`);
161
200
  }
162
201
  }
163
- // 3. Build the new adapter.
202
+ // 3. Build the new adapter — with the boot live wiring, so a reconnect
203
+ // can never silently shed WS authority / audit ingest / auto-capture
204
+ // (audit F9).
164
205
  const fresh = buildAdapter({
165
206
  mode: next.mode,
166
207
  exchange: next.exchange,
@@ -168,12 +209,18 @@ export class PluginRuntime {
168
209
  simulator: this.simulator,
169
210
  venue: next.venue,
170
211
  hlCredentials: next.hlCredentials,
212
+ wiring: this.liveWiring,
171
213
  });
172
214
  // Install autonomous protection callbacks before initialization can emit
173
215
  // user-data or bracket-reconciler events.
174
216
  if (fresh instanceof LiveAdapter) {
175
217
  this.wave9LiveLifecycleHooks?.configureLiveAdapter?.(fresh);
176
218
  }
219
+ // Same before-init rule for the drift_detected journal cleanup (F9): the
220
+ // reconciler can emit on its first poll.
221
+ if (fresh instanceof LiveAdapter || fresh instanceof HyperliquidLiveAdapter) {
222
+ this.onAdapterCreated?.(fresh);
223
+ }
177
224
  // 4. Fire async init for live adapters (non-blocking — readiness flips
178
225
  // INIT_PENDING → READY/DEGRADED/BLOCKED on its own).
179
226
  if (fresh instanceof LiveAdapter || fresh instanceof HyperliquidLiveAdapter) {
@@ -210,6 +257,10 @@ export class PluginRuntime {
210
257
  this._marketFeed.start();
211
258
  }
212
259
  }
260
+ // 8. Notify swap observers (approval-listener lifecycle etc. — F10).
261
+ // Fired for EVERY swap including paper, so a live→PAPER flip can tear
262
+ // down consumers bound to the orphaned live adapter.
263
+ this.onAdapterSwapped?.(fresh);
213
264
  logger.info(TAG, `Reconnect complete: now in ${this._mode} mode (readiness=${fresh.readiness})`);
214
265
  }
215
266
  }
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "id": "reefclaw-paper-trading",
3
3
  "name": "ReefClaw Trading",
4
- "version": "0.1.13",
4
+ "version": "0.1.14",
5
5
  "description": "Supervised trading plugin for the ReefClaw dashboard: paper trading with real market data (no API keys required), and optional live trading on Binance or Hyperliquid behind explicit operator opt-in, exchange API credentials, and always-on protective stop brackets. Includes the dashboard connector bridge, heartbeat automation, and remote SKILL.md instruction updates from the ReefClaw webapp.",
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.13",
3
+ "version": "0.1.14",
4
4
  "description": "ReefClaw supervised trading plugin for OpenClaw \u2014 paper trading with real market data, optional live trading on Binance or Hyperliquid (operator opt-in, API keys, always-on protective brackets), plus the ReefClaw dashboard connector with heartbeat automation and remote SKILL.md updates from the ReefClaw webapp. Install: /plugins install clawhub:@reefclaw/openclaw-plugin",
5
5
  "type": "module",
6
6
  "main": "index.js",
@@ -22,7 +22,7 @@
22
22
  "node": ">=20"
23
23
  },
24
24
  "dependencies": {
25
- "@reefclaw/shared": "0.1.2",
25
+ "@reefclaw/shared": "0.1.3",
26
26
  "ccxt": "4.5.37",
27
27
  "json5": "2.2.3",
28
28
  "ws": "8.19.0"
@@ -4,6 +4,9 @@ import type { CcxtOrder, CcxtBalance, CcxtPosition, CcxtTicker } from '../types.
4
4
  export declare class ExchangeSimulator extends EventEmitter {
5
5
  private state;
6
6
  private lastTicker;
7
+ /** Symbols with a take-profit close in flight — suppresses a re-entrant
8
+ * tick firing a second close on the same position. */
9
+ private takeProfitPending;
7
10
  private lastOrderBook;
8
11
  private simulationConfig;
9
12
  /** Metadata for pending limit orders, keyed by order ID. Cleaned up on fill/cancel. */
@@ -46,10 +49,21 @@ export declare class ExchangeSimulator extends EventEmitter {
46
49
  /** Cache the latest order book snapshot for a symbol. */
47
50
  updateOrderBook(symbol: string, orderbook: OrderBookDepth): void;
48
51
  getLastOrderBook(symbol: string): OrderBookDepth | undefined;
49
- createOrder(symbol: string, side: 'buy' | 'sell', type: 'market' | 'limit', amount: number, price?: number, metadata?: PositionMetadata): CcxtOrder;
52
+ createOrder(symbol: string, side: 'buy' | 'sell', type: 'market' | 'limit', amount: number, price?: number, metadata?: PositionMetadata,
53
+ /** Paper-only market-fill price override (take-profit leg). When set, the
54
+ * market branch prices off THIS instead of the last tick, and skips the
55
+ * stale-quote guard — the caller supplied the price, so quote age is
56
+ * irrelevant, and a protective exit must never be blocked (issue #202). */
57
+ referencePrice?: number): CcxtOrder;
50
58
  cancelOrder(orderId: string): CcxtOrder;
51
59
  cancelAllOrders(symbol?: string): CcxtOrder[];
52
- closePosition(symbol: string, closeReason?: CloseReason): CcxtOrder;
60
+ /**
61
+ * @param referencePrice Paper-only fill-price override. Used by the
62
+ * take-profit leg to fill AT the target level instead of the (possibly
63
+ * gapped-past) tick price — see `checkTakeProfitLegs`. Omitted everywhere
64
+ * else, which keeps the normal market-close path byte-identical.
65
+ */
66
+ closePosition(symbol: string, closeReason?: CloseReason, referencePrice?: number): CcxtOrder;
53
67
  /** Paper-only: move an open position's MUTABLE protective levels (stopPrice /
54
68
  * targetPrice) in place and persist, WITHOUT the close+reopen round-trip
55
69
  * (which pays an extra taker fee and resets the R/MFE denominators). The
@@ -63,6 +77,35 @@ export declare class ExchangeSimulator extends EventEmitter {
63
77
  }): void;
64
78
  updateTicker(ticker: CcxtTicker): void;
65
79
  getLastTicker(symbol: string): CcxtTicker | undefined;
80
+ /**
81
+ * Take-profit legs — the paper analog of the exchange-native
82
+ * `TAKE_PROFIT_MARKET` order live attaches at entry.
83
+ *
84
+ * ★ Why this exists: paper STORED `metadata.targetPrice` and surfaced it
85
+ * (chart line, positions table) but nothing ever closed on it, so the TP was
86
+ * a drawing rather than an order. Every paper winner ran straight past its
87
+ * exit — observed live 2026-07-27 on an OP/USDT short that reached +2.07R
88
+ * against a 1.0R target. That made paper the odd one out of three: the
89
+ * BACKTEST exits at target (`backtest/engine.ts` exitReason 'target') and
90
+ * LIVE exits at target (Binance TP_MARKET leg / HL coordinator TP leg), so
91
+ * a strategy forward-validated on paper was being measured on a book that
92
+ * let every winner run.
93
+ *
94
+ * Fill convention: the TARGET LEVEL is the decision price, and the normal
95
+ * realistic-fill engine applies its own adverse slippage around it (book
96
+ * VWAP + vol factor + taker fee) — the same model every other paper fill
97
+ * uses, rather than a second hand-rolled slippage constant. When a tick gaps
98
+ * past the target we deliberately do NOT credit the gap: filling at the
99
+ * level is worse for us than filling at the gapped tick, so this stays
100
+ * conservative against both the backtest and a real TP_MARKET (which would
101
+ * fill at the gapped price).
102
+ *
103
+ * Stops stay with the PositionWatcher: it is the safety floor and re-homing
104
+ * it is a separate, riskier change. A single tick can only breach one leg
105
+ * (stop and target sit on opposite sides of entry), so there is no
106
+ * stop-vs-target ordering ambiguity to resolve here.
107
+ */
108
+ private checkTakeProfitLegs;
66
109
  /** Walk every position for `symbol` and refresh MFE / give-back from the
67
110
  * latest mark. Idempotent — pure update of `metadata.mfePeakPrice` (only
68
111
  * ratchets favourably) plus derived `mfeR` and `giveBackRatio`. Safe to
@@ -6,7 +6,7 @@
6
6
  // via SimulationConfig and OrderBookDepth.
7
7
  import { EventEmitter } from 'node:events';
8
8
  import { randomUUID } from 'node:crypto';
9
- import { logger } from '../logger.js';
9
+ import { logger, formatError } from '../logger.js';
10
10
  import { MAX_TRADE_HISTORY, DEFAULT_SIMULATION_CONFIG } from './types.js';
11
11
  import { fillMarketOrder, fillLimitOrder, parseSymbol } from './fill-engine.js';
12
12
  import { updateMfe } from '../mfe.js';
@@ -15,6 +15,9 @@ const TAG = 'simulator';
15
15
  export class ExchangeSimulator extends EventEmitter {
16
16
  state;
17
17
  lastTicker = new Map();
18
+ /** Symbols with a take-profit close in flight — suppresses a re-entrant
19
+ * tick firing a second close on the same position. */
20
+ takeProfitPending = new Set();
18
21
  lastOrderBook = new Map();
19
22
  simulationConfig;
20
23
  /** Metadata for pending limit orders, keyed by order ID. Cleaned up on fill/cancel. */
@@ -247,7 +250,12 @@ export class ExchangeSimulator extends EventEmitter {
247
250
  return this.lastOrderBook.get(symbol);
248
251
  }
249
252
  // ---- Write operations (for tools) ----
250
- createOrder(symbol, side, type, amount, price, metadata) {
253
+ createOrder(symbol, side, type, amount, price, metadata,
254
+ /** Paper-only market-fill price override (take-profit leg). When set, the
255
+ * market branch prices off THIS instead of the last tick, and skips the
256
+ * stale-quote guard — the caller supplied the price, so quote age is
257
+ * irrelevant, and a protective exit must never be blocked (issue #202). */
258
+ referencePrice) {
251
259
  // ---- Startup trade lockout ----
252
260
  // Block trades during the first 15s after gateway restart IF there were
253
261
  // existing positions at startup. This prevents stale agent sessions from
@@ -281,6 +289,10 @@ export class ExchangeSimulator extends EventEmitter {
281
289
  createdAt: now,
282
290
  };
283
291
  if (type === 'market') {
292
+ // Explicit fill price (take-profit leg) — see the param doc above.
293
+ if (referencePrice !== undefined && Number.isFinite(referencePrice) && referencePrice > 0) {
294
+ return this.executeMarketFill(order, referencePrice, metadata);
295
+ }
284
296
  // Market orders fill immediately at current price
285
297
  const ticker = this.lastTicker.get(symbol);
286
298
  if (!ticker) {
@@ -345,7 +357,13 @@ export class ExchangeSimulator extends EventEmitter {
345
357
  }
346
358
  return cancelled.map(o => this.toCcxtOrder(o));
347
359
  }
348
- closePosition(symbol, closeReason) {
360
+ /**
361
+ * @param referencePrice Paper-only fill-price override. Used by the
362
+ * take-profit leg to fill AT the target level instead of the (possibly
363
+ * gapped-past) tick price — see `checkTakeProfitLegs`. Omitted everywhere
364
+ * else, which keeps the normal market-close path byte-identical.
365
+ */
366
+ closePosition(symbol, closeReason, referencePrice) {
349
367
  const position = this.state.positions.find(p => p.symbol === symbol);
350
368
  if (!position) {
351
369
  throw new Error(`No open position for ${symbol}`);
@@ -359,7 +377,7 @@ export class ExchangeSimulator extends EventEmitter {
359
377
  }
360
378
  // Create opposing market order to close the position
361
379
  const closeSide = position.side === 'long' ? 'sell' : 'buy';
362
- return this.createOrder(symbol, closeSide, 'market', position.quantity);
380
+ return this.createOrder(symbol, closeSide, 'market', position.quantity, undefined, undefined, referencePrice);
363
381
  }
364
382
  /** Paper-only: move an open position's MUTABLE protective levels (stopPrice /
365
383
  * targetPrice) in place and persist, WITHOUT the close+reopen round-trip
@@ -385,6 +403,10 @@ export class ExchangeSimulator extends EventEmitter {
385
403
  updateTicker(ticker) {
386
404
  this.lastTicker.set(ticker.symbol, ticker);
387
405
  this.refreshMfeForSymbol(ticker.symbol, ticker.last);
406
+ // MFE is refreshed FIRST so the peak this tick reached is recorded before a
407
+ // target close reads it — otherwise every TP exit would understate its own
408
+ // MFE and skew the capture-ratio analysis.
409
+ this.checkTakeProfitLegs(ticker.symbol, ticker.last);
388
410
  // Check if any pending limit orders should fill
389
411
  const toFill = [];
390
412
  const remaining = [];
@@ -429,6 +451,76 @@ export class ExchangeSimulator extends EventEmitter {
429
451
  getLastTicker(symbol) {
430
452
  return this.lastTicker.get(symbol);
431
453
  }
454
+ /**
455
+ * Take-profit legs — the paper analog of the exchange-native
456
+ * `TAKE_PROFIT_MARKET` order live attaches at entry.
457
+ *
458
+ * ★ Why this exists: paper STORED `metadata.targetPrice` and surfaced it
459
+ * (chart line, positions table) but nothing ever closed on it, so the TP was
460
+ * a drawing rather than an order. Every paper winner ran straight past its
461
+ * exit — observed live 2026-07-27 on an OP/USDT short that reached +2.07R
462
+ * against a 1.0R target. That made paper the odd one out of three: the
463
+ * BACKTEST exits at target (`backtest/engine.ts` exitReason 'target') and
464
+ * LIVE exits at target (Binance TP_MARKET leg / HL coordinator TP leg), so
465
+ * a strategy forward-validated on paper was being measured on a book that
466
+ * let every winner run.
467
+ *
468
+ * Fill convention: the TARGET LEVEL is the decision price, and the normal
469
+ * realistic-fill engine applies its own adverse slippage around it (book
470
+ * VWAP + vol factor + taker fee) — the same model every other paper fill
471
+ * uses, rather than a second hand-rolled slippage constant. When a tick gaps
472
+ * past the target we deliberately do NOT credit the gap: filling at the
473
+ * level is worse for us than filling at the gapped tick, so this stays
474
+ * conservative against both the backtest and a real TP_MARKET (which would
475
+ * fill at the gapped price).
476
+ *
477
+ * Stops stay with the PositionWatcher: it is the safety floor and re-homing
478
+ * it is a separate, riskier change. A single tick can only breach one leg
479
+ * (stop and target sit on opposite sides of entry), so there is no
480
+ * stop-vs-target ordering ambiguity to resolve here.
481
+ */
482
+ checkTakeProfitLegs(symbol, price) {
483
+ if (!Number.isFinite(price) || price <= 0)
484
+ return;
485
+ // Snapshot: closing mutates state.positions mid-iteration.
486
+ const candidates = this.state.positions.filter((p) => p.symbol === symbol);
487
+ for (const position of candidates) {
488
+ const target = position.metadata?.targetPrice;
489
+ if (target === undefined || !Number.isFinite(target) || target <= 0)
490
+ continue;
491
+ const breached = position.side === 'long' ? price >= target : price <= target;
492
+ if (!breached)
493
+ continue;
494
+ // Guard against a re-entrant tick firing a second close on the same
495
+ // symbol while the first is still settling.
496
+ if (this.takeProfitPending.has(symbol))
497
+ continue;
498
+ this.takeProfitPending.add(symbol);
499
+ try {
500
+ logger.info(TAG, `TARGET REACHED: ${symbol} ${position.side} price=${price} target=${target} — closing (exchange_target)`);
501
+ // Target = decision price; the fill engine adds realistic adverse
502
+ // slippage on top (see the fill-convention note above).
503
+ const order = this.closePosition(symbol, 'exchange_target', target);
504
+ this.emit('target_closed', {
505
+ symbol,
506
+ side: position.side,
507
+ targetPrice: target,
508
+ markPrice: price,
509
+ fillPrice: typeof order.average === 'number' ? order.average : target,
510
+ quantity: position.quantity,
511
+ order,
512
+ });
513
+ }
514
+ catch (err) {
515
+ // Never let a failed protective close kill the tick loop — the next
516
+ // tick retries, and the position is still visible to the agent.
517
+ logger.error(TAG, `Target close failed for ${symbol}: ${formatError(err)}`);
518
+ }
519
+ finally {
520
+ this.takeProfitPending.delete(symbol);
521
+ }
522
+ }
523
+ }
432
524
  /** Walk every position for `symbol` and refresh MFE / give-back from the
433
525
  * latest mark. Idempotent — pure update of `metadata.mfePeakPrice` (only
434
526
  * ratchets favourably) plus derived `mfeR` and `giveBackRatio`. Safe to
@@ -1,3 +1,4 @@
1
+ import type { CcxtOrder } from '../types.js';
1
2
  export interface FillError {
2
3
  orderId: string;
3
4
  symbol: string;
@@ -76,6 +77,22 @@ export interface ExecutionStats {
76
77
  export interface Wallet {
77
78
  [currency: string]: CurrencyBalance;
78
79
  }
80
+ /** Emitted when the paper take-profit leg fires (`ExchangeSimulator`
81
+ * 'target_closed'). The live analog is an exchange-native TAKE_PROFIT_MARKET
82
+ * fill; index.ts journals this the same way it journals a stop-watcher close,
83
+ * so a target exit can never leave a phantom-open journal row (issue #199). */
84
+ export interface TargetClosedEvent {
85
+ symbol: string;
86
+ side: 'long' | 'short';
87
+ /** The pinned target level that was breached. */
88
+ targetPrice: number;
89
+ /** The tick price that breached it (may have gapped past the target). */
90
+ markPrice: number;
91
+ /** Where we actually filled — the target level with adverse slippage. */
92
+ fillPrice: number;
93
+ quantity: number;
94
+ order: CcxtOrder;
95
+ }
79
96
  export interface CurrencyBalance {
80
97
  total: number;
81
98
  available: number;
@@ -323,13 +323,28 @@ async function attachBracketsHl(args, adapter) {
323
323
  let clearedStaleLedgerRow = false;
324
324
  if (existing && !isTerminalBracketState(existing.state)) {
325
325
  let cls = 'unknown';
326
+ // Per-LEG liveness (audit 2026-07-26 F4): "either cid survives ⇒ live"
327
+ // let a TP-only position no-op as "already protected" indefinitely while
328
+ // its stop was gone. A registered leg positively absent from a NON-EMPTY
329
+ // order set is a protection gap this tool must repair, not paper over.
330
+ const missingLegs = [];
326
331
  const hasCids = Boolean(existing.slCid || existing.tpCid);
327
332
  if (hasCids) {
328
333
  try {
329
334
  const open = await adapter.getOpenOrders(position.symbol);
330
335
  const liveCids = new Set(open.map(o => o.clientOrderId).filter(Boolean));
331
- if ((existing.slCid && liveCids.has(existing.slCid)) || (existing.tpCid && liveCids.has(existing.tpCid))) {
336
+ const stopLive = Boolean(existing.slCid && liveCids.has(existing.slCid));
337
+ const tpLive = Boolean(existing.tpCid && liveCids.has(existing.tpCid));
338
+ if (stopLive || tpLive) {
332
339
  cls = 'live';
340
+ if (open.length > 0) {
341
+ // Non-empty set = positive evidence for absence (d59e51b) — a
342
+ // registered-but-absent sibling is a repairable gap.
343
+ if (existing.slCid && !stopLive)
344
+ missingLegs.push('stop');
345
+ if (existing.tpCid && !tpLive)
346
+ missingLegs.push('target');
347
+ }
333
348
  }
334
349
  else if (open.length > 0) {
335
350
  cls = 'stale'; // non-empty set positively lacking our cids
@@ -351,6 +366,40 @@ async function attachBracketsHl(args, adapter) {
351
366
  if (cls === 'live') {
352
367
  if (pricesMatch(args.stop_price, existing.stopPrice)
353
368
  && pricesMatch(args.target_price, existing.targetPrice)) {
369
+ if (missingLegs.length > 0) {
370
+ // One registered leg is positively gone (a stop-less position is a
371
+ // safety-floor breach). Rebuild it at the registered price via the
372
+ // resize path — planResize submits ONLY the missing leg and leaves
373
+ // the healthy sibling untouched (F4).
374
+ try {
375
+ const coordinator = adapter.getHlBracketCoordinator();
376
+ await coordinator.resizeToPosition(position.symbol, contracts);
377
+ const healed = ledger.getBySymbol(position.symbol);
378
+ return {
379
+ ok: true,
380
+ symbol: position.symbol,
381
+ bracket_id: existing.bracketId,
382
+ entry_side: entrySide,
383
+ stop_price: existing.stopPrice,
384
+ target_price: existing.targetPrice,
385
+ sl_cid: healed?.slCid ?? existing.slCid,
386
+ tp_cid: healed?.tpCid ?? existing.tpCid,
387
+ attach_latency_ms: 0,
388
+ cancelled_stale_bracket_orders: 0,
389
+ cleared_stale_ledger_row: false,
390
+ attempts: 1,
391
+ idempotent_no_op: false,
392
+ note: `Missing ${missingLegs.join('+')} leg re-attached at the registered price(s); sibling leg untouched.`,
393
+ };
394
+ }
395
+ catch (err) {
396
+ return {
397
+ error: `Registered ${missingLegs.join('+')} leg is GONE from the exchange and the rebuild ` +
398
+ `failed (${formatError(err)}). The position is under-protected — retry attach_brackets ` +
399
+ `next heartbeat; the 60s truth sweep also retries. Do NOT record a protected review.`,
400
+ };
401
+ }
402
+ }
354
403
  return {
355
404
  ok: true,
356
405
  symbol: position.symbol,
@@ -1,7 +1,7 @@
1
1
  import { EventEmitter } from 'node:events';
2
2
  import type { CcxtOrder, CcxtPosition } from '../../types.js';
3
3
  import type { CloseReason } from '../../simulator/types.js';
4
- import type { BracketId, BracketRequest, BracketState } from '../../live/bracket-types.js';
4
+ import type { BracketId, BracketLedgerEntry, BracketRequest, BracketState } from '../../live/bracket-types.js';
5
5
  import type { BracketLedger } from '../../live/bracket-ledger.js';
6
6
  import type { HlOrderUpdateEvent } from './hl-user-stream.js';
7
7
  /** Narrow execution surface the coordinator needs — the HyperliquidLiveAdapter
@@ -24,6 +24,11 @@ export interface HlBracketExecutor {
24
24
  symbol: string;
25
25
  positionSide: 'long' | 'short';
26
26
  positionSize: number;
27
+ /** Ledger-registered prices — lets resize REBUILD a vanished leg (F4). */
28
+ registeredPrices?: {
29
+ stop?: number;
30
+ target?: number;
31
+ };
27
32
  }): Promise<{
28
33
  resized: boolean;
29
34
  slCid?: string;
@@ -88,6 +93,25 @@ export declare class HlBracketCoordinator extends EventEmitter {
88
93
  * fill signal against a non-terminal row is a warned NO-OP, never a fresh
89
94
  * bracketId that orphans the live legs' ledger identity. */
90
95
  registerEntry(req: BracketRequest, bracketId: BracketId, entryCid: string): void;
96
+ /** ★ Audit 2026-07-26 F5 — track a SECOND entry order placed against a live
97
+ * bracket row (a scale-in, or another entry while the first still rests).
98
+ *
99
+ * Each submission gets a fresh cloid, but the row keeps the ORIGINAL
100
+ * `entryCid`. The user-stream fill handler matches fills to rows by cid, so
101
+ * an unrecorded cid meant the later fill matched NOTHING: no attach, no
102
+ * resize. On HL that is naked exposure, not cosmetic drift — legs are FIXED
103
+ * SIZE (T-2), so the added contracts stayed unprotected until the 60s
104
+ * truth-check sweep happened to catch them.
105
+ *
106
+ * Idempotent; a terminal/absent row or a repeat of the primary cid is a
107
+ * no-op. Recording is deliberately CHEAP and local — the sweep remains the
108
+ * backstop, this just stops it being the only line of defence. */
109
+ registerAdditionalEntryCid(symbol: string, entryCid: string): void;
110
+ /** The bracket row a user-stream fill belongs to: the primary `entryCid` OR
111
+ * any cid recorded by `registerAdditionalEntryCid`. Terminal rows never
112
+ * match. Single home for the matching rule so the adapter's fill handler
113
+ * and the ledger can never disagree about what "our entry" means. */
114
+ findRowByEntryCid(cloid: string | undefined | null): BracketLedgerEntry | undefined;
91
115
  /** Attach both legs (ONE batched signed action) with retries. Idempotent on
92
116
  * a non-pending row. On exhaustion: ledger 'failed' + attach_failed event —
93
117
  * the ADAPTER escalates to auto-flatten (it owns closePosition). */